1 | """ |
---|
2 | CanSAS data reader - new recursive cansas_version. |
---|
3 | """ |
---|
4 | ############################################################################ |
---|
5 | #This software was developed by the University of Tennessee as part of the |
---|
6 | #Distributed Data Analysis of Neutron Scattering Experiments (DANSE) |
---|
7 | #project funded by the US National Science Foundation. |
---|
8 | #If you use DANSE applications to do scientific research that leads to |
---|
9 | #publication, we ask that you acknowledge the use of the software with the |
---|
10 | #following sentence: |
---|
11 | #This work benefited from DANSE software developed under NSF award DMR-0520547. |
---|
12 | #copyright 2008,2009 University of Tennessee |
---|
13 | ############################################################################# |
---|
14 | |
---|
15 | import logging |
---|
16 | import numpy as np |
---|
17 | import os |
---|
18 | import sys |
---|
19 | import datetime |
---|
20 | import inspect |
---|
21 | # For saving individual sections of data |
---|
22 | from sas.sascalc.dataloader.data_info import Data1D, Data2D, DataInfo, \ |
---|
23 | plottable_1D, plottable_2D |
---|
24 | from sas.sascalc.dataloader.data_info import Collimation, TransmissionSpectrum, \ |
---|
25 | Detector, Process, Aperture |
---|
26 | from sas.sascalc.dataloader.data_info import \ |
---|
27 | combine_data_info_with_plottable as combine_data |
---|
28 | import sas.sascalc.dataloader.readers.xml_reader as xml_reader |
---|
29 | from sas.sascalc.dataloader.readers.xml_reader import XMLreader |
---|
30 | from sas.sascalc.dataloader.readers.cansas_constants import CansasConstants, CurrentLevel |
---|
31 | |
---|
32 | # The following 2 imports *ARE* used. Do not remove either. |
---|
33 | import xml.dom.minidom |
---|
34 | from xml.dom.minidom import parseString |
---|
35 | |
---|
36 | PREPROCESS = "xmlpreprocess" |
---|
37 | ENCODING = "encoding" |
---|
38 | RUN_NAME_DEFAULT = "None" |
---|
39 | INVALID_SCHEMA_PATH_1_1 = "{0}/sas/sascalc/dataloader/readers/schema/cansas1d_invalid_v1_1.xsd" |
---|
40 | INVALID_SCHEMA_PATH_1_0 = "{0}/sas/sascalc/dataloader/readers/schema/cansas1d_invalid_v1_0.xsd" |
---|
41 | INVALID_XML = "\n\nThe loaded xml file, {0} does not fully meet the CanSAS v1.x specification. SasView loaded " + \ |
---|
42 | "as much of the data as possible.\n\n" |
---|
43 | HAS_CONVERTER = True |
---|
44 | try: |
---|
45 | from sas.sascalc.data_util.nxsunit import Converter |
---|
46 | except ImportError: |
---|
47 | HAS_CONVERTER = False |
---|
48 | |
---|
49 | CONSTANTS = CansasConstants() |
---|
50 | CANSAS_FORMAT = CONSTANTS.format |
---|
51 | CANSAS_NS = CONSTANTS.names |
---|
52 | ALLOW_ALL = True |
---|
53 | |
---|
54 | class Reader(XMLreader): |
---|
55 | """ |
---|
56 | Class to load cansas 1D XML files |
---|
57 | |
---|
58 | :Dependencies: |
---|
59 | The CanSAS reader requires PyXML 0.8.4 or later. |
---|
60 | """ |
---|
61 | # CanSAS version - defaults to version 1.0 |
---|
62 | cansas_version = "1.0" |
---|
63 | base_ns = "{cansas1d/1.0}" |
---|
64 | cansas_defaults = None |
---|
65 | type_name = "canSAS" |
---|
66 | invalid = True |
---|
67 | frm = "" |
---|
68 | # Log messages and errors |
---|
69 | logging = None |
---|
70 | errors = set() |
---|
71 | # Namespace hierarchy for current xml_file object |
---|
72 | names = None |
---|
73 | ns_list = None |
---|
74 | # Temporary storage location for loading multiple data sets in a single file |
---|
75 | current_datainfo = None |
---|
76 | current_dataset = None |
---|
77 | current_data1d = None |
---|
78 | data = None |
---|
79 | # List of data1D objects to be sent back to SasView |
---|
80 | output = None |
---|
81 | # Wildcards |
---|
82 | type = ["XML files (*.xml)|*.xml", "SasView Save Files (*.svs)|*.svs"] |
---|
83 | # List of allowed extensions |
---|
84 | ext = ['.xml', '.XML', '.svs', '.SVS'] |
---|
85 | # Flag to bypass extension check |
---|
86 | allow_all = True |
---|
87 | |
---|
88 | def reset_state(self): |
---|
89 | """ |
---|
90 | Resets the class state to a base case when loading a new data file so previous |
---|
91 | data files do not appear a second time |
---|
92 | """ |
---|
93 | self.current_datainfo = None |
---|
94 | self.current_dataset = None |
---|
95 | self.current_data1d = None |
---|
96 | self.data = [] |
---|
97 | self.process = Process() |
---|
98 | self.transspectrum = TransmissionSpectrum() |
---|
99 | self.aperture = Aperture() |
---|
100 | self.collimation = Collimation() |
---|
101 | self.detector = Detector() |
---|
102 | self.names = [] |
---|
103 | self.cansas_defaults = {} |
---|
104 | self.output = [] |
---|
105 | self.ns_list = None |
---|
106 | self.logging = [] |
---|
107 | self.encoding = None |
---|
108 | |
---|
109 | def read(self, xml_file, schema_path="", invalid=True): |
---|
110 | """ |
---|
111 | Validate and read in an xml_file file in the canSAS format. |
---|
112 | |
---|
113 | :param xml_file: A canSAS file path in proper XML format |
---|
114 | :param schema_path: A file path to an XML schema to validate the xml_file against |
---|
115 | """ |
---|
116 | # For every file loaded, reset everything to a base state |
---|
117 | self.reset_state() |
---|
118 | self.invalid = invalid |
---|
119 | # Check that the file exists |
---|
120 | if os.path.isfile(xml_file): |
---|
121 | basename, extension = os.path.splitext(os.path.basename(xml_file)) |
---|
122 | # If the file type is not allowed, return nothing |
---|
123 | if extension in self.ext or self.allow_all: |
---|
124 | # Get the file location of |
---|
125 | self.load_file_and_schema(xml_file, schema_path) |
---|
126 | self.add_data_set() |
---|
127 | # Try to load the file, but raise an error if unable to. |
---|
128 | # Check the file matches the XML schema |
---|
129 | try: |
---|
130 | self.is_cansas(extension) |
---|
131 | self.invalid = False |
---|
132 | # Get each SASentry from XML file and add it to a list. |
---|
133 | entry_list = self.xmlroot.xpath( |
---|
134 | '/ns:SASroot/ns:SASentry', |
---|
135 | namespaces={'ns': self.cansas_defaults.get("ns")}) |
---|
136 | self.names.append("SASentry") |
---|
137 | |
---|
138 | # Get all preprocessing events and encoding |
---|
139 | self.set_processing_instructions() |
---|
140 | |
---|
141 | # Parse each <SASentry> item |
---|
142 | for entry in entry_list: |
---|
143 | # Create a new DataInfo object for every <SASentry> |
---|
144 | |
---|
145 | # Set the file name and then parse the entry. |
---|
146 | self.current_datainfo.filename = basename + extension |
---|
147 | self.current_datainfo.meta_data["loader"] = "CanSAS XML 1D" |
---|
148 | self.current_datainfo.meta_data[PREPROCESS] = \ |
---|
149 | self.processing_instructions |
---|
150 | |
---|
151 | # Parse the XML SASentry |
---|
152 | self._parse_entry(entry) |
---|
153 | # Combine datasets with datainfo |
---|
154 | self.add_data_set() |
---|
155 | except RuntimeError: |
---|
156 | # If the file does not match the schema, raise this error |
---|
157 | invalid_xml = self.find_invalid_xml() |
---|
158 | invalid_xml = INVALID_XML.format(basename + extension) + invalid_xml |
---|
159 | self.errors.add(invalid_xml) |
---|
160 | # Try again with an invalid CanSAS schema, that requires only a data set in each |
---|
161 | base_name = xml_reader.__file__ |
---|
162 | base_name = base_name.replace("\\", "/") |
---|
163 | base = base_name.split("/sas/")[0] |
---|
164 | if self.cansas_version == "1.1": |
---|
165 | invalid_schema = INVALID_SCHEMA_PATH_1_1.format(base, self.cansas_defaults.get("schema")) |
---|
166 | else: |
---|
167 | invalid_schema = INVALID_SCHEMA_PATH_1_0.format(base, self.cansas_defaults.get("schema")) |
---|
168 | self.set_schema(invalid_schema) |
---|
169 | try: |
---|
170 | if self.invalid: |
---|
171 | if self.is_cansas(): |
---|
172 | self.output = self.read(xml_file, invalid_schema, False) |
---|
173 | else: |
---|
174 | raise RuntimeError |
---|
175 | else: |
---|
176 | raise RuntimeError |
---|
177 | except RuntimeError: |
---|
178 | x = np.zeros(1) |
---|
179 | y = np.zeros(1) |
---|
180 | self.current_data1d = Data1D(x,y) |
---|
181 | self.current_data1d.errors = self.errors |
---|
182 | return [self.current_data1d] |
---|
183 | else: |
---|
184 | self.output.append("Not a valid file path.") |
---|
185 | # Return a list of parsed entries that dataloader can manage |
---|
186 | return self.output |
---|
187 | |
---|
188 | def _parse_entry(self, dom, recurse=False): |
---|
189 | """ |
---|
190 | Parse a SASEntry - new recursive method for parsing the dom of |
---|
191 | the CanSAS data format. This will allow multiple data files |
---|
192 | and extra nodes to be read in simultaneously. |
---|
193 | |
---|
194 | :param dom: dom object with a namespace base of names |
---|
195 | """ |
---|
196 | |
---|
197 | if not self._is_call_local() and not recurse: |
---|
198 | self.reset_state() |
---|
199 | self.add_data_set() |
---|
200 | self.names.append("SASentry") |
---|
201 | self.parent_class = "SASentry" |
---|
202 | self._check_for_empty_data() |
---|
203 | self.base_ns = "{0}{1}{2}".format("{", \ |
---|
204 | CANSAS_NS.get(self.cansas_version).get("ns"), "}") |
---|
205 | |
---|
206 | # Go through each child in the parent element |
---|
207 | for node in dom: |
---|
208 | attr = node.attrib |
---|
209 | name = attr.get("name", "") |
---|
210 | type = attr.get("type", "") |
---|
211 | unit = attr.get("unit", "") |
---|
212 | # Get the element name and set the current names level |
---|
213 | tagname = node.tag.replace(self.base_ns, "") |
---|
214 | tagname_original = tagname |
---|
215 | # Skip this iteration when loading in save state information |
---|
216 | if tagname == "fitting_plug_in" or tagname == "pr_inversion" or tagname == "invariant": |
---|
217 | continue |
---|
218 | |
---|
219 | # Get where to store content |
---|
220 | self.names.append(tagname_original) |
---|
221 | self.ns_list = CONSTANTS.iterate_namespace(self.names) |
---|
222 | # If the element is a child element, recurse |
---|
223 | if len(node.getchildren()) > 0: |
---|
224 | self.parent_class = tagname_original |
---|
225 | if tagname == 'SASdata': |
---|
226 | self._initialize_new_data_set(node) |
---|
227 | if isinstance(self.current_dataset, plottable_2D): |
---|
228 | x_bins = attr.get("x_bins", "") |
---|
229 | y_bins = attr.get("y_bins", "") |
---|
230 | if x_bins is not "" and y_bins is not "": |
---|
231 | self.current_dataset.shape = (x_bins, y_bins) |
---|
232 | else: |
---|
233 | self.current_dataset.shape = () |
---|
234 | # Recursion step to access data within the group |
---|
235 | self._parse_entry(node, True) |
---|
236 | if tagname == "SASsample": |
---|
237 | self.current_datainfo.sample.name = name |
---|
238 | elif tagname == "beam_size": |
---|
239 | self.current_datainfo.source.beam_size_name = name |
---|
240 | elif tagname == "SAScollimation": |
---|
241 | self.collimation.name = name |
---|
242 | elif tagname == "aperture": |
---|
243 | self.aperture.name = name |
---|
244 | self.aperture.type = type |
---|
245 | self.add_intermediate() |
---|
246 | else: |
---|
247 | # I and Q - 1D data |
---|
248 | if tagname == 'I' and isinstance(self.current_dataset, |
---|
249 | plottable_1D): |
---|
250 | self.current_dataset.yaxis("Intensity", unit) |
---|
251 | data_list = node.text.split(',') |
---|
252 | for item in data_list: |
---|
253 | data_point, unit = self._get_node_value_from_text(node, |
---|
254 | item) |
---|
255 | self.current_dataset.y = np.append( |
---|
256 | self.current_dataset.y, data_point) |
---|
257 | elif tagname == 'Idev' and isinstance(self.current_dataset, |
---|
258 | plottable_1D): |
---|
259 | data_list = node.text.split(',') |
---|
260 | for item in data_list: |
---|
261 | data_point, unit = self._get_node_value_from_text(node, |
---|
262 | item) |
---|
263 | self.current_dataset.dy = np.append( |
---|
264 | self.current_dataset.dy, data_point) |
---|
265 | elif tagname == 'Q': |
---|
266 | data_list = node.text.split(',') |
---|
267 | for item in data_list: |
---|
268 | data_point, unit = self._get_node_value_from_text(node, |
---|
269 | item) |
---|
270 | self.current_dataset.x = np.append( |
---|
271 | self.current_dataset.x, data_point) |
---|
272 | elif tagname == 'Qdev': |
---|
273 | data_list = node.text.split(',') |
---|
274 | for item in data_list: |
---|
275 | data_point, unit = self._get_node_value_from_text(node, |
---|
276 | item) |
---|
277 | self.current_dataset.dx = np.append( |
---|
278 | self.current_dataset.dx, data_point) |
---|
279 | elif tagname == 'dQw': |
---|
280 | data_list = node.text.split(',') |
---|
281 | for item in data_list: |
---|
282 | data_point, unit = self._get_node_value_from_text(node, |
---|
283 | item) |
---|
284 | self.current_dataset.dqw = np.append( |
---|
285 | self.current_dataset.dqw, data_point) |
---|
286 | elif tagname == 'dQl': |
---|
287 | data_list = node.text.split(',') |
---|
288 | for item in data_list: |
---|
289 | data_point, unit = self._get_node_value_from_text(node, |
---|
290 | item) |
---|
291 | self.current_dataset.dxl = np.append( |
---|
292 | self.current_dataset.dxl, data_point) |
---|
293 | elif tagname == 'Qmean': |
---|
294 | pass |
---|
295 | elif tagname == 'Shadowfactor': |
---|
296 | pass |
---|
297 | elif isinstance(self.current_dataset, plottable_2D): |
---|
298 | data_point = node.text |
---|
299 | unit = attr.get('unit', '') |
---|
300 | else: |
---|
301 | data_point, unit = self._get_node_value(node) |
---|
302 | |
---|
303 | # If this is a dataset, store the data appropriately |
---|
304 | if tagname == 'Run': |
---|
305 | self.current_datainfo.run_name[data_point] = name |
---|
306 | self.current_datainfo.run.append(data_point) |
---|
307 | elif tagname == 'Title': |
---|
308 | self.current_datainfo.title = data_point |
---|
309 | elif tagname == 'SASnote': |
---|
310 | self.current_datainfo.notes.append(data_point) |
---|
311 | |
---|
312 | # I and Qx, Qy - 2D data |
---|
313 | elif tagname == 'I' and isinstance(self.current_dataset, plottable_2D): |
---|
314 | self.current_dataset.yaxis("Intensity", unit) |
---|
315 | self.current_dataset.data = np.fromstring(data_point, dtype=float, sep=",") |
---|
316 | elif tagname == 'Idev' and isinstance(self.current_dataset, plottable_2D): |
---|
317 | self.current_dataset.err_data = np.fromstring(data_point, dtype=float, sep=",") |
---|
318 | elif tagname == 'Qx': |
---|
319 | self.current_dataset.xaxis("Qx", unit) |
---|
320 | self.current_dataset.qx_data = np.fromstring(data_point, dtype=float, sep=",") |
---|
321 | elif tagname == 'Qy': |
---|
322 | self.current_dataset.yaxis("Qy", unit) |
---|
323 | self.current_dataset.qy_data = np.fromstring(data_point, dtype=float, sep=",") |
---|
324 | elif tagname == 'Qxdev': |
---|
325 | self.current_dataset.xaxis("Qxdev", unit) |
---|
326 | self.current_dataset.dqx_data = np.fromstring(data_point, dtype=float, sep=",") |
---|
327 | elif tagname == 'Qydev': |
---|
328 | self.current_dataset.yaxis("Qydev", unit) |
---|
329 | self.current_dataset.dqy_data = np.fromstring(data_point, dtype=float, sep=",") |
---|
330 | elif tagname == 'Mask': |
---|
331 | inter = [item == "1" for item in data_point.split(",")] |
---|
332 | self.current_dataset.mask = np.asarray(inter, dtype=bool) |
---|
333 | |
---|
334 | # Sample Information |
---|
335 | elif tagname == 'ID' and self.parent_class == 'SASsample': |
---|
336 | self.current_datainfo.sample.ID = data_point |
---|
337 | elif tagname == 'Title' and self.parent_class == 'SASsample': |
---|
338 | self.current_datainfo.sample.name = data_point |
---|
339 | elif tagname == 'thickness' and self.parent_class == 'SASsample': |
---|
340 | self.current_datainfo.sample.thickness = data_point |
---|
341 | self.current_datainfo.sample.thickness_unit = unit |
---|
342 | elif tagname == 'transmission' and self.parent_class == 'SASsample': |
---|
343 | self.current_datainfo.sample.transmission = data_point |
---|
344 | elif tagname == 'temperature' and self.parent_class == 'SASsample': |
---|
345 | self.current_datainfo.sample.temperature = data_point |
---|
346 | self.current_datainfo.sample.temperature_unit = unit |
---|
347 | elif tagname == 'details' and self.parent_class == 'SASsample': |
---|
348 | self.current_datainfo.sample.details.append(data_point) |
---|
349 | elif tagname == 'x' and self.parent_class == 'position': |
---|
350 | self.current_datainfo.sample.position.x = data_point |
---|
351 | self.current_datainfo.sample.position_unit = unit |
---|
352 | elif tagname == 'y' and self.parent_class == 'position': |
---|
353 | self.current_datainfo.sample.position.y = data_point |
---|
354 | self.current_datainfo.sample.position_unit = unit |
---|
355 | elif tagname == 'z' and self.parent_class == 'position': |
---|
356 | self.current_datainfo.sample.position.z = data_point |
---|
357 | self.current_datainfo.sample.position_unit = unit |
---|
358 | elif tagname == 'roll' and self.parent_class == 'orientation' and 'SASsample' in self.names: |
---|
359 | self.current_datainfo.sample.orientation.x = data_point |
---|
360 | self.current_datainfo.sample.orientation_unit = unit |
---|
361 | elif tagname == 'pitch' and self.parent_class == 'orientation' and 'SASsample' in self.names: |
---|
362 | self.current_datainfo.sample.orientation.y = data_point |
---|
363 | self.current_datainfo.sample.orientation_unit = unit |
---|
364 | elif tagname == 'yaw' and self.parent_class == 'orientation' and 'SASsample' in self.names: |
---|
365 | self.current_datainfo.sample.orientation.z = data_point |
---|
366 | self.current_datainfo.sample.orientation_unit = unit |
---|
367 | |
---|
368 | # Instrumental Information |
---|
369 | elif tagname == 'name' and self.parent_class == 'SASinstrument': |
---|
370 | self.current_datainfo.instrument = data_point |
---|
371 | # Detector Information |
---|
372 | elif tagname == 'name' and self.parent_class == 'SASdetector': |
---|
373 | self.detector.name = data_point |
---|
374 | elif tagname == 'SDD' and self.parent_class == 'SASdetector': |
---|
375 | self.detector.distance = data_point |
---|
376 | self.detector.distance_unit = unit |
---|
377 | elif tagname == 'slit_length' and self.parent_class == 'SASdetector': |
---|
378 | self.detector.slit_length = data_point |
---|
379 | self.detector.slit_length_unit = unit |
---|
380 | elif tagname == 'x' and self.parent_class == 'offset': |
---|
381 | self.detector.offset.x = data_point |
---|
382 | self.detector.offset_unit = unit |
---|
383 | elif tagname == 'y' and self.parent_class == 'offset': |
---|
384 | self.detector.offset.y = data_point |
---|
385 | self.detector.offset_unit = unit |
---|
386 | elif tagname == 'z' and self.parent_class == 'offset': |
---|
387 | self.detector.offset.z = data_point |
---|
388 | self.detector.offset_unit = unit |
---|
389 | elif tagname == 'x' and self.parent_class == 'beam_center': |
---|
390 | self.detector.beam_center.x = data_point |
---|
391 | self.detector.beam_center_unit = unit |
---|
392 | elif tagname == 'y' and self.parent_class == 'beam_center': |
---|
393 | self.detector.beam_center.y = data_point |
---|
394 | self.detector.beam_center_unit = unit |
---|
395 | elif tagname == 'z' and self.parent_class == 'beam_center': |
---|
396 | self.detector.beam_center.z = data_point |
---|
397 | self.detector.beam_center_unit = unit |
---|
398 | elif tagname == 'x' and self.parent_class == 'pixel_size': |
---|
399 | self.detector.pixel_size.x = data_point |
---|
400 | self.detector.pixel_size_unit = unit |
---|
401 | elif tagname == 'y' and self.parent_class == 'pixel_size': |
---|
402 | self.detector.pixel_size.y = data_point |
---|
403 | self.detector.pixel_size_unit = unit |
---|
404 | elif tagname == 'z' and self.parent_class == 'pixel_size': |
---|
405 | self.detector.pixel_size.z = data_point |
---|
406 | self.detector.pixel_size_unit = unit |
---|
407 | elif tagname == 'roll' and self.parent_class == 'orientation' and 'SASdetector' in self.names: |
---|
408 | self.detector.orientation.x = data_point |
---|
409 | self.detector.orientation_unit = unit |
---|
410 | elif tagname == 'pitch' and self.parent_class == 'orientation' and 'SASdetector' in self.names: |
---|
411 | self.detector.orientation.y = data_point |
---|
412 | self.detector.orientation_unit = unit |
---|
413 | elif tagname == 'yaw' and self.parent_class == 'orientation' and 'SASdetector' in self.names: |
---|
414 | self.detector.orientation.z = data_point |
---|
415 | self.detector.orientation_unit = unit |
---|
416 | # Collimation and Aperture |
---|
417 | elif tagname == 'length' and self.parent_class == 'SAScollimation': |
---|
418 | self.collimation.length = data_point |
---|
419 | self.collimation.length_unit = unit |
---|
420 | elif tagname == 'name' and self.parent_class == 'SAScollimation': |
---|
421 | self.collimation.name = data_point |
---|
422 | elif tagname == 'distance' and self.parent_class == 'aperture': |
---|
423 | self.aperture.distance = data_point |
---|
424 | self.aperture.distance_unit = unit |
---|
425 | elif tagname == 'x' and self.parent_class == 'size': |
---|
426 | self.aperture.size.x = data_point |
---|
427 | self.collimation.size_unit = unit |
---|
428 | elif tagname == 'y' and self.parent_class == 'size': |
---|
429 | self.aperture.size.y = data_point |
---|
430 | self.collimation.size_unit = unit |
---|
431 | elif tagname == 'z' and self.parent_class == 'size': |
---|
432 | self.aperture.size.z = data_point |
---|
433 | self.collimation.size_unit = unit |
---|
434 | |
---|
435 | # Process Information |
---|
436 | elif tagname == 'name' and self.parent_class == 'SASprocess': |
---|
437 | self.process.name = data_point |
---|
438 | elif tagname == 'description' and self.parent_class == 'SASprocess': |
---|
439 | self.process.description = data_point |
---|
440 | elif tagname == 'date' and self.parent_class == 'SASprocess': |
---|
441 | try: |
---|
442 | self.process.date = datetime.datetime.fromtimestamp(data_point) |
---|
443 | except: |
---|
444 | self.process.date = data_point |
---|
445 | elif tagname == 'SASprocessnote': |
---|
446 | self.process.notes.append(data_point) |
---|
447 | elif tagname == 'term' and self.parent_class == 'SASprocess': |
---|
448 | unit = attr.get("unit", "") |
---|
449 | dic = {} |
---|
450 | dic["name"] = name |
---|
451 | dic["value"] = data_point |
---|
452 | dic["unit"] = unit |
---|
453 | self.process.term.append(dic) |
---|
454 | |
---|
455 | # Transmission Spectrum |
---|
456 | elif tagname == 'T' and self.parent_class == 'Tdata': |
---|
457 | self.transspectrum.transmission = np.append(self.transspectrum.transmission, data_point) |
---|
458 | self.transspectrum.transmission_unit = unit |
---|
459 | elif tagname == 'Tdev' and self.parent_class == 'Tdata': |
---|
460 | self.transspectrum.transmission_deviation = np.append(self.transspectrum.transmission_deviation, data_point) |
---|
461 | self.transspectrum.transmission_deviation_unit = unit |
---|
462 | elif tagname == 'Lambda' and self.parent_class == 'Tdata': |
---|
463 | self.transspectrum.wavelength = np.append(self.transspectrum.wavelength, data_point) |
---|
464 | self.transspectrum.wavelength_unit = unit |
---|
465 | |
---|
466 | # Source Information |
---|
467 | elif tagname == 'wavelength' and (self.parent_class == 'SASsource' or self.parent_class == 'SASData'): |
---|
468 | self.current_datainfo.source.wavelength = data_point |
---|
469 | self.current_datainfo.source.wavelength_unit = unit |
---|
470 | elif tagname == 'wavelength_min' and self.parent_class == 'SASsource': |
---|
471 | self.current_datainfo.source.wavelength_min = data_point |
---|
472 | self.current_datainfo.source.wavelength_min_unit = unit |
---|
473 | elif tagname == 'wavelength_max' and self.parent_class == 'SASsource': |
---|
474 | self.current_datainfo.source.wavelength_max = data_point |
---|
475 | self.current_datainfo.source.wavelength_max_unit = unit |
---|
476 | elif tagname == 'wavelength_spread' and self.parent_class == 'SASsource': |
---|
477 | self.current_datainfo.source.wavelength_spread = data_point |
---|
478 | self.current_datainfo.source.wavelength_spread_unit = unit |
---|
479 | elif tagname == 'x' and self.parent_class == 'beam_size': |
---|
480 | self.current_datainfo.source.beam_size.x = data_point |
---|
481 | self.current_datainfo.source.beam_size_unit = unit |
---|
482 | elif tagname == 'y' and self.parent_class == 'beam_size': |
---|
483 | self.current_datainfo.source.beam_size.y = data_point |
---|
484 | self.current_datainfo.source.beam_size_unit = unit |
---|
485 | elif tagname == 'z' and self.parent_class == 'pixel_size': |
---|
486 | self.current_datainfo.source.data_point.z = data_point |
---|
487 | self.current_datainfo.source.beam_size_unit = unit |
---|
488 | elif tagname == 'radiation' and self.parent_class == 'SASsource': |
---|
489 | self.current_datainfo.source.radiation = data_point |
---|
490 | elif tagname == 'beam_shape' and self.parent_class == 'SASsource': |
---|
491 | self.current_datainfo.source.beam_shape = data_point |
---|
492 | |
---|
493 | # Everything else goes in meta_data |
---|
494 | else: |
---|
495 | new_key = self._create_unique_key(self.current_datainfo.meta_data, tagname) |
---|
496 | self.current_datainfo.meta_data[new_key] = data_point |
---|
497 | |
---|
498 | self.names.remove(tagname_original) |
---|
499 | length = 0 |
---|
500 | if len(self.names) > 1: |
---|
501 | length = len(self.names) - 1 |
---|
502 | self.parent_class = self.names[length] |
---|
503 | if not self._is_call_local() and not recurse: |
---|
504 | self.frm = "" |
---|
505 | self.add_data_set() |
---|
506 | empty = None |
---|
507 | return self.output[0], empty |
---|
508 | |
---|
509 | |
---|
510 | def _is_call_local(self): |
---|
511 | """ |
---|
512 | |
---|
513 | """ |
---|
514 | if self.frm == "": |
---|
515 | inter = inspect.stack() |
---|
516 | self.frm = inter[2] |
---|
517 | mod_name = self.frm[1].replace("\\", "/").replace(".pyc", "") |
---|
518 | mod_name = mod_name.replace(".py", "") |
---|
519 | mod = mod_name.split("sas/") |
---|
520 | mod_name = mod[1] |
---|
521 | if mod_name != "sascalc/dataloader/readers/cansas_reader": |
---|
522 | return False |
---|
523 | return True |
---|
524 | |
---|
525 | def is_cansas(self, ext="xml"): |
---|
526 | """ |
---|
527 | Checks to see if the xml file is a CanSAS file |
---|
528 | |
---|
529 | :param ext: The file extension of the data file |
---|
530 | """ |
---|
531 | if self.validate_xml(): |
---|
532 | name = "{http://www.w3.org/2001/XMLSchema-instance}schemaLocation" |
---|
533 | value = self.xmlroot.get(name) |
---|
534 | if CANSAS_NS.get(self.cansas_version).get("ns") == \ |
---|
535 | value.rsplit(" ")[0]: |
---|
536 | return True |
---|
537 | if ext == "svs": |
---|
538 | return True |
---|
539 | raise RuntimeError |
---|
540 | |
---|
541 | def load_file_and_schema(self, xml_file, schema_path=""): |
---|
542 | """ |
---|
543 | Loads the file and associates a schema, if a schema is passed in or if one already exists |
---|
544 | |
---|
545 | :param xml_file: The xml file path sent to Reader.read |
---|
546 | :param schema_path: The path to a schema associated with the xml_file, or find one based on the file |
---|
547 | """ |
---|
548 | base_name = xml_reader.__file__ |
---|
549 | base_name = base_name.replace("\\", "/") |
---|
550 | base = base_name.split("/sas/")[0] |
---|
551 | |
---|
552 | # Load in xml file and get the cansas version from the header |
---|
553 | self.set_xml_file(xml_file) |
---|
554 | self.cansas_version = self.xmlroot.get("version", "1.0") |
---|
555 | |
---|
556 | # Generic values for the cansas file based on the version |
---|
557 | self.cansas_defaults = CANSAS_NS.get(self.cansas_version, "1.0") |
---|
558 | if schema_path == "": |
---|
559 | schema_path = "{0}/sas/sascalc/dataloader/readers/schema/{1}".format \ |
---|
560 | (base, self.cansas_defaults.get("schema")).replace("\\", "/") |
---|
561 | |
---|
562 | # Link a schema to the XML file. |
---|
563 | self.set_schema(schema_path) |
---|
564 | |
---|
565 | def add_data_set(self): |
---|
566 | """ |
---|
567 | Adds the current_dataset to the list of outputs after preforming final processing on the data and then calls a |
---|
568 | private method to generate a new data set. |
---|
569 | |
---|
570 | :param key: NeXus group name for current tree level |
---|
571 | """ |
---|
572 | |
---|
573 | if self.current_datainfo and self.current_dataset: |
---|
574 | self._final_cleanup() |
---|
575 | self.data = [] |
---|
576 | self.current_datainfo = DataInfo() |
---|
577 | |
---|
578 | def _initialize_new_data_set(self, node=None): |
---|
579 | """ |
---|
580 | A private class method to generate a new 1D data object. |
---|
581 | Outside methods should call add_data_set() to be sure any existing data is stored properly. |
---|
582 | |
---|
583 | :param node: XML node to determine if 1D or 2D data |
---|
584 | """ |
---|
585 | x = np.array(0) |
---|
586 | y = np.array(0) |
---|
587 | for child in node: |
---|
588 | if child.tag.replace(self.base_ns, "") == "Idata": |
---|
589 | for i_child in child: |
---|
590 | if i_child.tag.replace(self.base_ns, "") == "Qx": |
---|
591 | self.current_dataset = plottable_2D() |
---|
592 | return |
---|
593 | self.current_dataset = plottable_1D(x, y) |
---|
594 | |
---|
595 | def add_intermediate(self): |
---|
596 | """ |
---|
597 | This method stores any intermediate objects within the final data set after fully reading the set. |
---|
598 | |
---|
599 | :param parent: The NXclass name for the h5py Group object that just finished being processed |
---|
600 | """ |
---|
601 | |
---|
602 | if self.parent_class == 'SASprocess': |
---|
603 | self.current_datainfo.process.append(self.process) |
---|
604 | self.process = Process() |
---|
605 | elif self.parent_class == 'SASdetector': |
---|
606 | self.current_datainfo.detector.append(self.detector) |
---|
607 | self.detector = Detector() |
---|
608 | elif self.parent_class == 'SAStransmission_spectrum': |
---|
609 | self.current_datainfo.trans_spectrum.append(self.transspectrum) |
---|
610 | self.transspectrum = TransmissionSpectrum() |
---|
611 | elif self.parent_class == 'SAScollimation': |
---|
612 | self.current_datainfo.collimation.append(self.collimation) |
---|
613 | self.collimation = Collimation() |
---|
614 | elif self.parent_class == 'aperture': |
---|
615 | self.collimation.aperture.append(self.aperture) |
---|
616 | self.aperture = Aperture() |
---|
617 | elif self.parent_class == 'SASdata': |
---|
618 | self._check_for_empty_resolution() |
---|
619 | self.data.append(self.current_dataset) |
---|
620 | |
---|
621 | def _final_cleanup(self): |
---|
622 | """ |
---|
623 | Final cleanup of the Data1D object to be sure it has all the |
---|
624 | appropriate information needed for perspectives |
---|
625 | """ |
---|
626 | |
---|
627 | # Append errors to dataset and reset class errors |
---|
628 | self.current_datainfo.errors = set() |
---|
629 | for error in self.errors: |
---|
630 | self.current_datainfo.errors.add(error) |
---|
631 | self.errors.clear() |
---|
632 | |
---|
633 | # Combine all plottables with datainfo and append each to output |
---|
634 | # Type cast data arrays to float64 and find min/max as appropriate |
---|
635 | for dataset in self.data: |
---|
636 | if isinstance(dataset, plottable_1D): |
---|
637 | if dataset.x is not None: |
---|
638 | dataset.x = np.delete(dataset.x, [0]) |
---|
639 | dataset.x = dataset.x.astype(np.float64) |
---|
640 | dataset.xmin = np.min(dataset.x) |
---|
641 | dataset.xmax = np.max(dataset.x) |
---|
642 | if dataset.y is not None: |
---|
643 | dataset.y = np.delete(dataset.y, [0]) |
---|
644 | dataset.y = dataset.y.astype(np.float64) |
---|
645 | dataset.ymin = np.min(dataset.y) |
---|
646 | dataset.ymax = np.max(dataset.y) |
---|
647 | if dataset.dx is not None: |
---|
648 | dataset.dx = np.delete(dataset.dx, [0]) |
---|
649 | dataset.dx = dataset.dx.astype(np.float64) |
---|
650 | if dataset.dxl is not None: |
---|
651 | dataset.dxl = np.delete(dataset.dxl, [0]) |
---|
652 | dataset.dxl = dataset.dxl.astype(np.float64) |
---|
653 | if dataset.dxw is not None: |
---|
654 | dataset.dxw = np.delete(dataset.dxw, [0]) |
---|
655 | dataset.dxw = dataset.dxw.astype(np.float64) |
---|
656 | if dataset.dy is not None: |
---|
657 | dataset.dy = np.delete(dataset.dy, [0]) |
---|
658 | dataset.dy = dataset.dy.astype(np.float64) |
---|
659 | np.trim_zeros(dataset.x) |
---|
660 | np.trim_zeros(dataset.y) |
---|
661 | np.trim_zeros(dataset.dy) |
---|
662 | elif isinstance(dataset, plottable_2D): |
---|
663 | dataset.data = dataset.data.astype(np.float64) |
---|
664 | dataset.qx_data = dataset.qx_data.astype(np.float64) |
---|
665 | dataset.xmin = np.min(dataset.qx_data) |
---|
666 | dataset.xmax = np.max(dataset.qx_data) |
---|
667 | dataset.qy_data = dataset.qy_data.astype(np.float64) |
---|
668 | dataset.ymin = np.min(dataset.qy_data) |
---|
669 | dataset.ymax = np.max(dataset.qy_data) |
---|
670 | dataset.q_data = np.sqrt(dataset.qx_data * dataset.qx_data |
---|
671 | + dataset.qy_data * dataset.qy_data) |
---|
672 | if dataset.err_data is not None: |
---|
673 | dataset.err_data = dataset.err_data.astype(np.float64) |
---|
674 | if dataset.dqx_data is not None: |
---|
675 | dataset.dqx_data = dataset.dqx_data.astype(np.float64) |
---|
676 | if dataset.dqy_data is not None: |
---|
677 | dataset.dqy_data = dataset.dqy_data.astype(np.float64) |
---|
678 | if dataset.mask is not None: |
---|
679 | dataset.mask = dataset.mask.astype(dtype=bool) |
---|
680 | |
---|
681 | if len(dataset.shape) == 2: |
---|
682 | n_rows, n_cols = dataset.shape |
---|
683 | dataset.y_bins = dataset.qy_data[0::int(n_cols)] |
---|
684 | dataset.x_bins = dataset.qx_data[:int(n_cols)] |
---|
685 | dataset.data = dataset.data.flatten() |
---|
686 | else: |
---|
687 | dataset.y_bins = [] |
---|
688 | dataset.x_bins = [] |
---|
689 | dataset.data = dataset.data.flatten() |
---|
690 | |
---|
691 | final_dataset = combine_data(dataset, self.current_datainfo) |
---|
692 | self.output.append(final_dataset) |
---|
693 | |
---|
694 | def _create_unique_key(self, dictionary, name, numb=0): |
---|
695 | """ |
---|
696 | Create a unique key value for any dictionary to prevent overwriting |
---|
697 | Recurse until a unique key value is found. |
---|
698 | |
---|
699 | :param dictionary: A dictionary with any number of entries |
---|
700 | :param name: The index of the item to be added to dictionary |
---|
701 | :param numb: The number to be appended to the name, starts at 0 |
---|
702 | """ |
---|
703 | if dictionary.get(name) is not None: |
---|
704 | numb += 1 |
---|
705 | name = name.split("_")[0] |
---|
706 | name += "_{0}".format(numb) |
---|
707 | name = self._create_unique_key(dictionary, name, numb) |
---|
708 | return name |
---|
709 | |
---|
710 | def _get_node_value_from_text(self, node, node_text): |
---|
711 | """ |
---|
712 | Get the value of a node and any applicable units |
---|
713 | |
---|
714 | :param node: The XML node to get the value of |
---|
715 | :param tagname: The tagname of the node |
---|
716 | """ |
---|
717 | units = "" |
---|
718 | # If the value is a float, compile with units. |
---|
719 | if self.ns_list.ns_datatype == "float": |
---|
720 | # If an empty value is given, set as zero. |
---|
721 | if node_text is None or node_text.isspace() \ |
---|
722 | or node_text.lower() == "nan": |
---|
723 | node_text = "0.0" |
---|
724 | # Convert the value to the base units |
---|
725 | tag = node.tag.replace(self.base_ns, "") |
---|
726 | node_text, units = self._unit_conversion(node, tag, node_text) |
---|
727 | |
---|
728 | # If the value is a timestamp, convert to a datetime object |
---|
729 | elif self.ns_list.ns_datatype == "timestamp": |
---|
730 | if node_text is None or node_text.isspace(): |
---|
731 | pass |
---|
732 | else: |
---|
733 | try: |
---|
734 | node_text = \ |
---|
735 | datetime.datetime.fromtimestamp(node_text) |
---|
736 | except ValueError: |
---|
737 | node_text = None |
---|
738 | return node_text, units |
---|
739 | |
---|
740 | def _get_node_value(self, node): |
---|
741 | """ |
---|
742 | Get the value of a node and any applicable units |
---|
743 | |
---|
744 | :param node: The XML node to get the value of |
---|
745 | :param tagname: The tagname of the node |
---|
746 | """ |
---|
747 | #Get the text from the node and convert all whitespace to spaces |
---|
748 | units = '' |
---|
749 | node_value = node.text |
---|
750 | if node_value is not None: |
---|
751 | node_value = ' '.join(node_value.split()) |
---|
752 | else: |
---|
753 | node_value = "" |
---|
754 | node_value, units = self._get_node_value_from_text(node, node_value) |
---|
755 | return node_value, units |
---|
756 | |
---|
757 | def _unit_conversion(self, node, tagname, node_value): |
---|
758 | """ |
---|
759 | A unit converter method used to convert the data included in the file |
---|
760 | to the default units listed in data_info |
---|
761 | |
---|
762 | :param node: XML node |
---|
763 | :param tagname: name of the node |
---|
764 | :param node_value: The value of the current dom node |
---|
765 | """ |
---|
766 | attr = node.attrib |
---|
767 | value_unit = '' |
---|
768 | err_msg = None |
---|
769 | default_unit = None |
---|
770 | if not isinstance(node_value, float): |
---|
771 | node_value = float(node_value) |
---|
772 | if 'unit' in attr and attr.get('unit') is not None: |
---|
773 | try: |
---|
774 | local_unit = attr['unit'] |
---|
775 | unitname = self.ns_list.current_level.get("unit", "") |
---|
776 | if "SASdetector" in self.names: |
---|
777 | save_in = "detector" |
---|
778 | elif "aperture" in self.names: |
---|
779 | save_in = "aperture" |
---|
780 | elif "SAScollimation" in self.names: |
---|
781 | save_in = "collimation" |
---|
782 | elif "SAStransmission_spectrum" in self.names: |
---|
783 | save_in = "transspectrum" |
---|
784 | elif "SASdata" in self.names: |
---|
785 | x = np.zeros(1) |
---|
786 | y = np.zeros(1) |
---|
787 | self.current_data1d = Data1D(x, y) |
---|
788 | save_in = "current_data1d" |
---|
789 | elif "SASsource" in self.names: |
---|
790 | save_in = "current_datainfo.source" |
---|
791 | elif "SASsample" in self.names: |
---|
792 | save_in = "current_datainfo.sample" |
---|
793 | elif "SASprocess" in self.names: |
---|
794 | save_in = "process" |
---|
795 | else: |
---|
796 | save_in = "current_datainfo" |
---|
797 | exec "default_unit = self.{0}.{1}".format(save_in, unitname) |
---|
798 | if local_unit and default_unit and local_unit.lower() != default_unit.lower() \ |
---|
799 | and local_unit.lower() != "none": |
---|
800 | if HAS_CONVERTER == True: |
---|
801 | # Check local units - bad units raise KeyError |
---|
802 | data_conv_q = Converter(local_unit) |
---|
803 | value_unit = default_unit |
---|
804 | node_value = data_conv_q(node_value, units=default_unit) |
---|
805 | else: |
---|
806 | value_unit = local_unit |
---|
807 | err_msg = "Unit converter is not available.\n" |
---|
808 | else: |
---|
809 | value_unit = local_unit |
---|
810 | except KeyError: |
---|
811 | err_msg = "CanSAS reader: unexpected " |
---|
812 | err_msg += "\"{0}\" unit [{1}]; " |
---|
813 | err_msg = err_msg.format(tagname, local_unit) |
---|
814 | err_msg += "expecting [{0}]".format(default_unit) |
---|
815 | value_unit = local_unit |
---|
816 | except: |
---|
817 | err_msg = "CanSAS reader: unknown error converting " |
---|
818 | err_msg += "\"{0}\" unit [{1}]" |
---|
819 | err_msg = err_msg.format(tagname, local_unit) |
---|
820 | value_unit = local_unit |
---|
821 | elif 'unit' in attr: |
---|
822 | value_unit = attr['unit'] |
---|
823 | if err_msg: |
---|
824 | self.errors.add(err_msg) |
---|
825 | return node_value, value_unit |
---|
826 | |
---|
827 | def _check_for_empty_data(self): |
---|
828 | """ |
---|
829 | Creates an empty data set if no data is passed to the reader |
---|
830 | |
---|
831 | :param data1d: presumably a Data1D object |
---|
832 | """ |
---|
833 | if self.current_dataset == None: |
---|
834 | x_vals = np.empty(0) |
---|
835 | y_vals = np.empty(0) |
---|
836 | dx_vals = np.empty(0) |
---|
837 | dy_vals = np.empty(0) |
---|
838 | dxl = np.empty(0) |
---|
839 | dxw = np.empty(0) |
---|
840 | self.current_dataset = plottable_1D(x_vals, y_vals, dx_vals, dy_vals) |
---|
841 | self.current_dataset.dxl = dxl |
---|
842 | self.current_dataset.dxw = dxw |
---|
843 | |
---|
844 | def _check_for_empty_resolution(self): |
---|
845 | """ |
---|
846 | A method to check all resolution data sets are the same size as I and Q |
---|
847 | """ |
---|
848 | if isinstance(self.current_dataset, plottable_1D): |
---|
849 | dql_exists = False |
---|
850 | dqw_exists = False |
---|
851 | dq_exists = False |
---|
852 | di_exists = False |
---|
853 | if self.current_dataset.dxl is not None: |
---|
854 | dql_exists = True |
---|
855 | if self.current_dataset.dxw is not None: |
---|
856 | dqw_exists = True |
---|
857 | if self.current_dataset.dx is not None: |
---|
858 | dq_exists = True |
---|
859 | if self.current_dataset.dy is not None: |
---|
860 | di_exists = True |
---|
861 | if dqw_exists and not dql_exists: |
---|
862 | array_size = self.current_dataset.dxw.size - 1 |
---|
863 | self.current_dataset.dxl = np.append(self.current_dataset.dxl, |
---|
864 | np.zeros([array_size])) |
---|
865 | elif dql_exists and not dqw_exists: |
---|
866 | array_size = self.current_dataset.dxl.size - 1 |
---|
867 | self.current_dataset.dxw = np.append(self.current_dataset.dxw, |
---|
868 | np.zeros([array_size])) |
---|
869 | elif not dql_exists and not dqw_exists and not dq_exists: |
---|
870 | array_size = self.current_dataset.x.size - 1 |
---|
871 | self.current_dataset.dx = np.append(self.current_dataset.dx, |
---|
872 | np.zeros([array_size])) |
---|
873 | if not di_exists: |
---|
874 | array_size = self.current_dataset.y.size - 1 |
---|
875 | self.current_dataset.dy = np.append(self.current_dataset.dy, |
---|
876 | np.zeros([array_size])) |
---|
877 | elif isinstance(self.current_dataset, plottable_2D): |
---|
878 | dqx_exists = False |
---|
879 | dqy_exists = False |
---|
880 | di_exists = False |
---|
881 | mask_exists = False |
---|
882 | if self.current_dataset.dqx_data is not None: |
---|
883 | dqx_exists = True |
---|
884 | if self.current_dataset.dqy_data is not None: |
---|
885 | dqy_exists = True |
---|
886 | if self.current_dataset.err_data is not None: |
---|
887 | di_exists = True |
---|
888 | if self.current_dataset.mask is not None: |
---|
889 | mask_exists = True |
---|
890 | if not dqy_exists: |
---|
891 | array_size = self.current_dataset.qy_data.size - 1 |
---|
892 | self.current_dataset.dqy_data = np.append( |
---|
893 | self.current_dataset.dqy_data, np.zeros([array_size])) |
---|
894 | if not dqx_exists: |
---|
895 | array_size = self.current_dataset.qx_data.size - 1 |
---|
896 | self.current_dataset.dqx_data = np.append( |
---|
897 | self.current_dataset.dqx_data, np.zeros([array_size])) |
---|
898 | if not di_exists: |
---|
899 | array_size = self.current_dataset.data.size - 1 |
---|
900 | self.current_dataset.err_data = np.append( |
---|
901 | self.current_dataset.err_data, np.zeros([array_size])) |
---|
902 | if not mask_exists: |
---|
903 | array_size = self.current_dataset.data.size - 1 |
---|
904 | self.current_dataset.mask = np.append( |
---|
905 | self.current_dataset.mask, |
---|
906 | np.ones([array_size] ,dtype=bool)) |
---|
907 | |
---|
908 | ####### All methods below are for writing CanSAS XML files ####### |
---|
909 | |
---|
910 | def write(self, filename, datainfo): |
---|
911 | """ |
---|
912 | Write the content of a Data1D as a CanSAS XML file |
---|
913 | |
---|
914 | :param filename: name of the file to write |
---|
915 | :param datainfo: Data1D object |
---|
916 | """ |
---|
917 | # Create XML document |
---|
918 | doc, _ = self._to_xml_doc(datainfo) |
---|
919 | # Write the file |
---|
920 | file_ref = open(filename, 'w') |
---|
921 | if self.encoding == None: |
---|
922 | self.encoding = "UTF-8" |
---|
923 | doc.write(file_ref, encoding=self.encoding, |
---|
924 | pretty_print=True, xml_declaration=True) |
---|
925 | file_ref.close() |
---|
926 | |
---|
927 | def _to_xml_doc(self, datainfo): |
---|
928 | """ |
---|
929 | Create an XML document to contain the content of a Data1D |
---|
930 | |
---|
931 | :param datainfo: Data1D object |
---|
932 | """ |
---|
933 | is_2d = False |
---|
934 | if issubclass(datainfo.__class__, Data2D): |
---|
935 | is_2d = True |
---|
936 | |
---|
937 | # Get PIs and create root element |
---|
938 | pi_string = self._get_pi_string() |
---|
939 | # Define namespaces and create SASroot object |
---|
940 | main_node = self._create_main_node() |
---|
941 | # Create ElementTree, append SASroot and apply processing instructions |
---|
942 | base_string = pi_string + self.to_string(main_node) |
---|
943 | base_element = self.create_element_from_string(base_string) |
---|
944 | doc = self.create_tree(base_element) |
---|
945 | # Create SASentry Element |
---|
946 | entry_node = self.create_element("SASentry") |
---|
947 | root = doc.getroot() |
---|
948 | root.append(entry_node) |
---|
949 | |
---|
950 | # Add Title to SASentry |
---|
951 | self.write_node(entry_node, "Title", datainfo.title) |
---|
952 | # Add Run to SASentry |
---|
953 | self._write_run_names(datainfo, entry_node) |
---|
954 | # Add Data info to SASEntry |
---|
955 | if is_2d: |
---|
956 | self._write_data_2d(datainfo, entry_node) |
---|
957 | else: |
---|
958 | if self._check_root(): |
---|
959 | self._write_data(datainfo, entry_node) |
---|
960 | else: |
---|
961 | self._write_data_linearized(datainfo, entry_node) |
---|
962 | # Transmission Spectrum Info |
---|
963 | self._write_trans_spectrum(datainfo, entry_node) |
---|
964 | # Sample info |
---|
965 | self._write_sample_info(datainfo, entry_node) |
---|
966 | # Instrument info |
---|
967 | instr = self._write_instrument(datainfo, entry_node) |
---|
968 | # Source |
---|
969 | self._write_source(datainfo, instr) |
---|
970 | # Collimation |
---|
971 | self._write_collimation(datainfo, instr) |
---|
972 | # Detectors |
---|
973 | self._write_detectors(datainfo, instr) |
---|
974 | # Processes info |
---|
975 | self._write_process_notes(datainfo, entry_node) |
---|
976 | # Note info |
---|
977 | self._write_notes(datainfo, entry_node) |
---|
978 | # Return the document, and the SASentry node associated with |
---|
979 | # the data we just wrote |
---|
980 | # If the calling function was not the cansas reader, return a minidom |
---|
981 | # object rather than an lxml object. |
---|
982 | self.frm = inspect.stack()[1] |
---|
983 | doc, entry_node = self._check_origin(entry_node, doc) |
---|
984 | return doc, entry_node |
---|
985 | |
---|
986 | def write_node(self, parent, name, value, attr=None): |
---|
987 | """ |
---|
988 | :param doc: document DOM |
---|
989 | :param parent: parent node |
---|
990 | :param name: tag of the element |
---|
991 | :param value: value of the child text node |
---|
992 | :param attr: attribute dictionary |
---|
993 | |
---|
994 | :return: True if something was appended, otherwise False |
---|
995 | """ |
---|
996 | if value is not None: |
---|
997 | parent = self.ebuilder(parent, name, value, attr) |
---|
998 | return True |
---|
999 | return False |
---|
1000 | |
---|
1001 | def _get_pi_string(self): |
---|
1002 | """ |
---|
1003 | Creates the processing instructions header for writing to file |
---|
1004 | """ |
---|
1005 | pis = self.return_processing_instructions() |
---|
1006 | if len(pis) > 0: |
---|
1007 | pi_tree = self.create_tree(pis[0]) |
---|
1008 | i = 1 |
---|
1009 | for i in range(1, len(pis) - 1): |
---|
1010 | pi_tree = self.append(pis[i], pi_tree) |
---|
1011 | pi_string = self.to_string(pi_tree) |
---|
1012 | else: |
---|
1013 | pi_string = "" |
---|
1014 | return pi_string |
---|
1015 | |
---|
1016 | def _create_main_node(self): |
---|
1017 | """ |
---|
1018 | Creates the primary xml header used when writing to file |
---|
1019 | """ |
---|
1020 | xsi = "http://www.w3.org/2001/XMLSchema-instance" |
---|
1021 | version = self.cansas_version |
---|
1022 | n_s = CANSAS_NS.get(version).get("ns") |
---|
1023 | if version == "1.1": |
---|
1024 | url = "http://www.cansas.org/formats/1.1/" |
---|
1025 | else: |
---|
1026 | url = "http://www.cansas.org/formats/1.0/" |
---|
1027 | schema_location = "{0} {1}cansas1d.xsd".format(n_s, url) |
---|
1028 | attrib = {"{" + xsi + "}schemaLocation" : schema_location, |
---|
1029 | "version" : version} |
---|
1030 | nsmap = {'xsi' : xsi, None: n_s} |
---|
1031 | |
---|
1032 | main_node = self.create_element("{" + n_s + "}SASroot", |
---|
1033 | attrib=attrib, nsmap=nsmap) |
---|
1034 | return main_node |
---|
1035 | |
---|
1036 | def _write_run_names(self, datainfo, entry_node): |
---|
1037 | """ |
---|
1038 | Writes the run names to the XML file |
---|
1039 | |
---|
1040 | :param datainfo: The Data1D object the information is coming from |
---|
1041 | :param entry_node: lxml node ElementTree object to be appended to |
---|
1042 | """ |
---|
1043 | if datainfo.run == None or datainfo.run == []: |
---|
1044 | datainfo.run.append(RUN_NAME_DEFAULT) |
---|
1045 | datainfo.run_name[RUN_NAME_DEFAULT] = RUN_NAME_DEFAULT |
---|
1046 | for item in datainfo.run: |
---|
1047 | runname = {} |
---|
1048 | if item in datainfo.run_name and \ |
---|
1049 | len(str(datainfo.run_name[item])) > 1: |
---|
1050 | runname = {'name': datainfo.run_name[item]} |
---|
1051 | self.write_node(entry_node, "Run", item, runname) |
---|
1052 | |
---|
1053 | def _write_data(self, datainfo, entry_node): |
---|
1054 | """ |
---|
1055 | Writes 1D I and Q data to the XML file |
---|
1056 | |
---|
1057 | :param datainfo: The Data1D object the information is coming from |
---|
1058 | :param entry_node: lxml node ElementTree object to be appended to |
---|
1059 | """ |
---|
1060 | node = self.create_element("SASdata") |
---|
1061 | self.append(node, entry_node) |
---|
1062 | |
---|
1063 | for i in range(len(datainfo.x)): |
---|
1064 | point = self.create_element("Idata") |
---|
1065 | node.append(point) |
---|
1066 | self.write_node(point, "Q", datainfo.x[i], |
---|
1067 | {'unit': datainfo.x_unit}) |
---|
1068 | if len(datainfo.y) >= i: |
---|
1069 | self.write_node(point, "I", datainfo.y[i], |
---|
1070 | {'unit': datainfo.y_unit}) |
---|
1071 | if datainfo.dy is not None and len(datainfo.dy) > i: |
---|
1072 | self.write_node(point, "Idev", datainfo.dy[i], |
---|
1073 | {'unit': datainfo.y_unit}) |
---|
1074 | if datainfo.dx is not None and len(datainfo.dx) > i: |
---|
1075 | self.write_node(point, "Qdev", datainfo.dx[i], |
---|
1076 | {'unit': datainfo.x_unit}) |
---|
1077 | if datainfo.dxw is not None and len(datainfo.dxw) > i: |
---|
1078 | self.write_node(point, "dQw", datainfo.dxw[i], |
---|
1079 | {'unit': datainfo.x_unit}) |
---|
1080 | if datainfo.dxl is not None and len(datainfo.dxl) > i: |
---|
1081 | self.write_node(point, "dQl", datainfo.dxl[i], |
---|
1082 | {'unit': datainfo.x_unit}) |
---|
1083 | |
---|
1084 | def _write_data_linearized(self, datainfo, entry_node): |
---|
1085 | """ |
---|
1086 | Writes 1D I and Q data to an XML file is a single Idata element |
---|
1087 | |
---|
1088 | :param datainfo: The Data1D object the information is coming from |
---|
1089 | :param entry_node: lxml node ElementTree object to be appended to |
---|
1090 | """ |
---|
1091 | node = self.create_element("SASdata") |
---|
1092 | self.append(node, entry_node) |
---|
1093 | |
---|
1094 | point = self.create_element("Idata") |
---|
1095 | node.append(point) |
---|
1096 | x = ','.join([str(datainfo.x[i]) for i in xrange(len(datainfo.x))]) |
---|
1097 | self.write_node(point, "Q", x, {'unit': datainfo.x_unit}) |
---|
1098 | y = ','.join([str(datainfo.y[i]) for i in xrange(len(datainfo.y))]) |
---|
1099 | self.write_node(point, "I", y, {'unit': datainfo.y_unit}) |
---|
1100 | if datainfo.dy is not None: |
---|
1101 | dy = ','.join( |
---|
1102 | [str(datainfo.dy[i]) for i in xrange(len(datainfo.dy))]) |
---|
1103 | self.write_node(point, "Idev", dy, {'unit': datainfo.y_unit}) |
---|
1104 | if datainfo.dx is not None: |
---|
1105 | dx = ','.join( |
---|
1106 | [str(datainfo.dx[i]) for i in xrange(len(datainfo.dx))]) |
---|
1107 | self.write_node(point, "Qdev", dx, {'unit': datainfo.x_unit}) |
---|
1108 | if datainfo.dxw is not None: |
---|
1109 | dxw = ','.join( |
---|
1110 | [str(datainfo.dxw[i]) for i in xrange(len(datainfo.dxw))]) |
---|
1111 | self.write_node(point, "dQw", dxw, {'unit': datainfo.x_unit}) |
---|
1112 | if datainfo.dxl is not None: |
---|
1113 | dxl = ','.join( |
---|
1114 | [str(datainfo.dxl[i]) for i in xrange(len(datainfo.dxl))]) |
---|
1115 | self.write_node(point, "dQl", dxl, {'unit': datainfo.x_unit}) |
---|
1116 | |
---|
1117 | def _write_data_2d(self, datainfo, entry_node): |
---|
1118 | """ |
---|
1119 | Writes 2D data to the XML file |
---|
1120 | |
---|
1121 | :param datainfo: The Data2D object the information is coming from |
---|
1122 | :param entry_node: lxml node ElementTree object to be appended to |
---|
1123 | """ |
---|
1124 | attr = {} |
---|
1125 | if datainfo.data.shape: |
---|
1126 | attr["x_bins"] = str(len(datainfo.x_bins)) |
---|
1127 | attr["y_bins"] = str(len(datainfo.y_bins)) |
---|
1128 | node = self.create_element("SASdata", attr) |
---|
1129 | self.append(node, entry_node) |
---|
1130 | |
---|
1131 | point = self.create_element("Idata") |
---|
1132 | node.append(point) |
---|
1133 | qx = ','.join([str(datainfo.qx_data[i]) for i in xrange(len(datainfo.qx_data))]) |
---|
1134 | qy = ','.join([str(datainfo.qy_data[i]) for i in xrange(len(datainfo.qy_data))]) |
---|
1135 | intensity = ','.join([str(datainfo.data[i]) for i in xrange(len(datainfo.data))]) |
---|
1136 | |
---|
1137 | self.write_node(point, "Qx", qx, |
---|
1138 | {'unit': datainfo._xunit}) |
---|
1139 | self.write_node(point, "Qy", qy, |
---|
1140 | {'unit': datainfo._yunit}) |
---|
1141 | self.write_node(point, "I", intensity, |
---|
1142 | {'unit': datainfo._zunit}) |
---|
1143 | if datainfo.err_data is not None: |
---|
1144 | err = ','.join([str(datainfo.err_data[i]) for i in |
---|
1145 | xrange(len(datainfo.err_data))]) |
---|
1146 | self.write_node(point, "Idev", err, |
---|
1147 | {'unit': datainfo._zunit}) |
---|
1148 | if datainfo.dqy_data is not None: |
---|
1149 | dqy = ','.join([str(datainfo.dqy_data[i]) for i in |
---|
1150 | xrange(len(datainfo.dqy_data))]) |
---|
1151 | self.write_node(point, "Qydev", dqy, |
---|
1152 | {'unit': datainfo._yunit}) |
---|
1153 | if datainfo.dqx_data is not None: |
---|
1154 | dqx = ','.join([str(datainfo.dqx_data[i]) for i in |
---|
1155 | xrange(len(datainfo.dqx_data))]) |
---|
1156 | self.write_node(point, "Qxdev", dqx, |
---|
1157 | {'unit': datainfo._xunit}) |
---|
1158 | if datainfo.mask is not None: |
---|
1159 | mask = ','.join( |
---|
1160 | ["1" if datainfo.mask[i] else "0" |
---|
1161 | for i in xrange(len(datainfo.mask))]) |
---|
1162 | self.write_node(point, "Mask", mask) |
---|
1163 | |
---|
1164 | def _write_trans_spectrum(self, datainfo, entry_node): |
---|
1165 | """ |
---|
1166 | Writes the transmission spectrum data to the XML file |
---|
1167 | |
---|
1168 | :param datainfo: The Data1D object the information is coming from |
---|
1169 | :param entry_node: lxml node ElementTree object to be appended to |
---|
1170 | """ |
---|
1171 | for i in range(len(datainfo.trans_spectrum)): |
---|
1172 | spectrum = datainfo.trans_spectrum[i] |
---|
1173 | node = self.create_element("SAStransmission_spectrum", |
---|
1174 | {"name" : spectrum.name}) |
---|
1175 | self.append(node, entry_node) |
---|
1176 | if isinstance(spectrum.timestamp, datetime.datetime): |
---|
1177 | node.setAttribute("timestamp", spectrum.timestamp) |
---|
1178 | for i in range(len(spectrum.wavelength)): |
---|
1179 | point = self.create_element("Tdata") |
---|
1180 | node.append(point) |
---|
1181 | self.write_node(point, "Lambda", spectrum.wavelength[i], |
---|
1182 | {'unit': spectrum.wavelength_unit}) |
---|
1183 | self.write_node(point, "T", spectrum.transmission[i], |
---|
1184 | {'unit': spectrum.transmission_unit}) |
---|
1185 | if spectrum.transmission_deviation != None \ |
---|
1186 | and len(spectrum.transmission_deviation) >= i: |
---|
1187 | self.write_node(point, "Tdev", |
---|
1188 | spectrum.transmission_deviation[i], |
---|
1189 | {'unit': |
---|
1190 | spectrum.transmission_deviation_unit}) |
---|
1191 | |
---|
1192 | def _write_sample_info(self, datainfo, entry_node): |
---|
1193 | """ |
---|
1194 | Writes the sample information to the XML file |
---|
1195 | |
---|
1196 | :param datainfo: The Data1D object the information is coming from |
---|
1197 | :param entry_node: lxml node ElementTree object to be appended to |
---|
1198 | """ |
---|
1199 | sample = self.create_element("SASsample") |
---|
1200 | if datainfo.sample.name is not None: |
---|
1201 | self.write_attribute(sample, "name", |
---|
1202 | str(datainfo.sample.name)) |
---|
1203 | self.append(sample, entry_node) |
---|
1204 | self.write_node(sample, "ID", str(datainfo.sample.ID)) |
---|
1205 | self.write_node(sample, "thickness", datainfo.sample.thickness, |
---|
1206 | {"unit": datainfo.sample.thickness_unit}) |
---|
1207 | self.write_node(sample, "transmission", datainfo.sample.transmission) |
---|
1208 | self.write_node(sample, "temperature", datainfo.sample.temperature, |
---|
1209 | {"unit": datainfo.sample.temperature_unit}) |
---|
1210 | |
---|
1211 | pos = self.create_element("position") |
---|
1212 | written = self.write_node(pos, |
---|
1213 | "x", |
---|
1214 | datainfo.sample.position.x, |
---|
1215 | {"unit": datainfo.sample.position_unit}) |
---|
1216 | written = written | self.write_node( \ |
---|
1217 | pos, "y", datainfo.sample.position.y, |
---|
1218 | {"unit": datainfo.sample.position_unit}) |
---|
1219 | written = written | self.write_node( \ |
---|
1220 | pos, "z", datainfo.sample.position.z, |
---|
1221 | {"unit": datainfo.sample.position_unit}) |
---|
1222 | if written == True: |
---|
1223 | self.append(pos, sample) |
---|
1224 | |
---|
1225 | ori = self.create_element("orientation") |
---|
1226 | written = self.write_node(ori, "roll", |
---|
1227 | datainfo.sample.orientation.x, |
---|
1228 | {"unit": datainfo.sample.orientation_unit}) |
---|
1229 | written = written | self.write_node( \ |
---|
1230 | ori, "pitch", datainfo.sample.orientation.y, |
---|
1231 | {"unit": datainfo.sample.orientation_unit}) |
---|
1232 | written = written | self.write_node( \ |
---|
1233 | ori, "yaw", datainfo.sample.orientation.z, |
---|
1234 | {"unit": datainfo.sample.orientation_unit}) |
---|
1235 | if written == True: |
---|
1236 | self.append(ori, sample) |
---|
1237 | |
---|
1238 | for item in datainfo.sample.details: |
---|
1239 | self.write_node(sample, "details", item) |
---|
1240 | |
---|
1241 | def _write_instrument(self, datainfo, entry_node): |
---|
1242 | """ |
---|
1243 | Writes the instrumental information to the XML file |
---|
1244 | |
---|
1245 | :param datainfo: The Data1D object the information is coming from |
---|
1246 | :param entry_node: lxml node ElementTree object to be appended to |
---|
1247 | """ |
---|
1248 | instr = self.create_element("SASinstrument") |
---|
1249 | self.append(instr, entry_node) |
---|
1250 | self.write_node(instr, "name", datainfo.instrument) |
---|
1251 | return instr |
---|
1252 | |
---|
1253 | def _write_source(self, datainfo, instr): |
---|
1254 | """ |
---|
1255 | Writes the source information to the XML file |
---|
1256 | |
---|
1257 | :param datainfo: The Data1D object the information is coming from |
---|
1258 | :param instr: instrument node to be appended to |
---|
1259 | """ |
---|
1260 | source = self.create_element("SASsource") |
---|
1261 | if datainfo.source.name is not None: |
---|
1262 | self.write_attribute(source, "name", |
---|
1263 | str(datainfo.source.name)) |
---|
1264 | self.append(source, instr) |
---|
1265 | if datainfo.source.radiation == None or datainfo.source.radiation == '': |
---|
1266 | datainfo.source.radiation = "neutron" |
---|
1267 | self.write_node(source, "radiation", datainfo.source.radiation) |
---|
1268 | |
---|
1269 | size = self.create_element("beam_size") |
---|
1270 | if datainfo.source.beam_size_name is not None: |
---|
1271 | self.write_attribute(size, "name", |
---|
1272 | str(datainfo.source.beam_size_name)) |
---|
1273 | written = self.write_node( \ |
---|
1274 | size, "x", datainfo.source.beam_size.x, |
---|
1275 | {"unit": datainfo.source.beam_size_unit}) |
---|
1276 | written = written | self.write_node( \ |
---|
1277 | size, "y", datainfo.source.beam_size.y, |
---|
1278 | {"unit": datainfo.source.beam_size_unit}) |
---|
1279 | written = written | self.write_node( \ |
---|
1280 | size, "z", datainfo.source.beam_size.z, |
---|
1281 | {"unit": datainfo.source.beam_size_unit}) |
---|
1282 | if written == True: |
---|
1283 | self.append(size, source) |
---|
1284 | |
---|
1285 | self.write_node(source, "beam_shape", datainfo.source.beam_shape) |
---|
1286 | self.write_node(source, "wavelength", |
---|
1287 | datainfo.source.wavelength, |
---|
1288 | {"unit": datainfo.source.wavelength_unit}) |
---|
1289 | self.write_node(source, "wavelength_min", |
---|
1290 | datainfo.source.wavelength_min, |
---|
1291 | {"unit": datainfo.source.wavelength_min_unit}) |
---|
1292 | self.write_node(source, "wavelength_max", |
---|
1293 | datainfo.source.wavelength_max, |
---|
1294 | {"unit": datainfo.source.wavelength_max_unit}) |
---|
1295 | self.write_node(source, "wavelength_spread", |
---|
1296 | datainfo.source.wavelength_spread, |
---|
1297 | {"unit": datainfo.source.wavelength_spread_unit}) |
---|
1298 | |
---|
1299 | def _write_collimation(self, datainfo, instr): |
---|
1300 | """ |
---|
1301 | Writes the collimation information to the XML file |
---|
1302 | |
---|
1303 | :param datainfo: The Data1D object the information is coming from |
---|
1304 | :param instr: lxml node ElementTree object to be appended to |
---|
1305 | """ |
---|
1306 | if datainfo.collimation == [] or datainfo.collimation == None: |
---|
1307 | coll = Collimation() |
---|
1308 | datainfo.collimation.append(coll) |
---|
1309 | for item in datainfo.collimation: |
---|
1310 | coll = self.create_element("SAScollimation") |
---|
1311 | if item.name is not None: |
---|
1312 | self.write_attribute(coll, "name", str(item.name)) |
---|
1313 | self.append(coll, instr) |
---|
1314 | |
---|
1315 | self.write_node(coll, "length", item.length, |
---|
1316 | {"unit": item.length_unit}) |
---|
1317 | |
---|
1318 | for aperture in item.aperture: |
---|
1319 | apert = self.create_element("aperture") |
---|
1320 | if aperture.name is not None: |
---|
1321 | self.write_attribute(apert, "name", str(aperture.name)) |
---|
1322 | if aperture.type is not None: |
---|
1323 | self.write_attribute(apert, "type", str(aperture.type)) |
---|
1324 | self.append(apert, coll) |
---|
1325 | |
---|
1326 | size = self.create_element("size") |
---|
1327 | if aperture.size_name is not None: |
---|
1328 | self.write_attribute(size, "name", |
---|
1329 | str(aperture.size_name)) |
---|
1330 | written = self.write_node(size, "x", aperture.size.x, |
---|
1331 | {"unit": aperture.size_unit}) |
---|
1332 | written = written | self.write_node( \ |
---|
1333 | size, "y", aperture.size.y, |
---|
1334 | {"unit": aperture.size_unit}) |
---|
1335 | written = written | self.write_node( \ |
---|
1336 | size, "z", aperture.size.z, |
---|
1337 | {"unit": aperture.size_unit}) |
---|
1338 | if written == True: |
---|
1339 | self.append(size, apert) |
---|
1340 | |
---|
1341 | self.write_node(apert, "distance", aperture.distance, |
---|
1342 | {"unit": aperture.distance_unit}) |
---|
1343 | |
---|
1344 | def _write_detectors(self, datainfo, instr): |
---|
1345 | """ |
---|
1346 | Writes the detector information to the XML file |
---|
1347 | |
---|
1348 | :param datainfo: The Data1D object the information is coming from |
---|
1349 | :param inst: lxml instrument node to be appended to |
---|
1350 | """ |
---|
1351 | if datainfo.detector == None or datainfo.detector == []: |
---|
1352 | det = Detector() |
---|
1353 | det.name = "" |
---|
1354 | datainfo.detector.append(det) |
---|
1355 | |
---|
1356 | for item in datainfo.detector: |
---|
1357 | det = self.create_element("SASdetector") |
---|
1358 | written = self.write_node(det, "name", item.name) |
---|
1359 | written = written | self.write_node(det, "SDD", item.distance, |
---|
1360 | {"unit": item.distance_unit}) |
---|
1361 | if written == True: |
---|
1362 | self.append(det, instr) |
---|
1363 | |
---|
1364 | off = self.create_element("offset") |
---|
1365 | written = self.write_node(off, "x", item.offset.x, |
---|
1366 | {"unit": item.offset_unit}) |
---|
1367 | written = written | self.write_node(off, "y", item.offset.y, |
---|
1368 | {"unit": item.offset_unit}) |
---|
1369 | written = written | self.write_node(off, "z", item.offset.z, |
---|
1370 | {"unit": item.offset_unit}) |
---|
1371 | if written == True: |
---|
1372 | self.append(off, det) |
---|
1373 | |
---|
1374 | ori = self.create_element("orientation") |
---|
1375 | written = self.write_node(ori, "roll", item.orientation.x, |
---|
1376 | {"unit": item.orientation_unit}) |
---|
1377 | written = written | self.write_node(ori, "pitch", |
---|
1378 | item.orientation.y, |
---|
1379 | {"unit": item.orientation_unit}) |
---|
1380 | written = written | self.write_node(ori, "yaw", |
---|
1381 | item.orientation.z, |
---|
1382 | {"unit": item.orientation_unit}) |
---|
1383 | if written == True: |
---|
1384 | self.append(ori, det) |
---|
1385 | |
---|
1386 | center = self.create_element("beam_center") |
---|
1387 | written = self.write_node(center, "x", item.beam_center.x, |
---|
1388 | {"unit": item.beam_center_unit}) |
---|
1389 | written = written | self.write_node(center, "y", |
---|
1390 | item.beam_center.y, |
---|
1391 | {"unit": item.beam_center_unit}) |
---|
1392 | written = written | self.write_node(center, "z", |
---|
1393 | item.beam_center.z, |
---|
1394 | {"unit": item.beam_center_unit}) |
---|
1395 | if written == True: |
---|
1396 | self.append(center, det) |
---|
1397 | |
---|
1398 | pix = self.create_element("pixel_size") |
---|
1399 | written = self.write_node(pix, "x", item.pixel_size.x, |
---|
1400 | {"unit": item.pixel_size_unit}) |
---|
1401 | written = written | self.write_node(pix, "y", item.pixel_size.y, |
---|
1402 | {"unit": item.pixel_size_unit}) |
---|
1403 | written = written | self.write_node(pix, "z", item.pixel_size.z, |
---|
1404 | {"unit": item.pixel_size_unit}) |
---|
1405 | if written == True: |
---|
1406 | self.append(pix, det) |
---|
1407 | self.write_node(det, "slit_length", item.slit_length, |
---|
1408 | {"unit": item.slit_length_unit}) |
---|
1409 | |
---|
1410 | def _write_process_notes(self, datainfo, entry_node): |
---|
1411 | """ |
---|
1412 | Writes the process notes to the XML file |
---|
1413 | |
---|
1414 | :param datainfo: The Data1D object the information is coming from |
---|
1415 | :param entry_node: lxml node ElementTree object to be appended to |
---|
1416 | |
---|
1417 | """ |
---|
1418 | for item in datainfo.process: |
---|
1419 | node = self.create_element("SASprocess") |
---|
1420 | self.append(node, entry_node) |
---|
1421 | self.write_node(node, "name", item.name) |
---|
1422 | self.write_node(node, "date", item.date) |
---|
1423 | self.write_node(node, "description", item.description) |
---|
1424 | for term in item.term: |
---|
1425 | if isinstance(term, list): |
---|
1426 | value = term['value'] |
---|
1427 | del term['value'] |
---|
1428 | elif isinstance(term, dict): |
---|
1429 | value = term.get("value") |
---|
1430 | del term['value'] |
---|
1431 | else: |
---|
1432 | value = term |
---|
1433 | self.write_node(node, "term", value, term) |
---|
1434 | for note in item.notes: |
---|
1435 | self.write_node(node, "SASprocessnote", note) |
---|
1436 | if len(item.notes) == 0: |
---|
1437 | self.write_node(node, "SASprocessnote", "") |
---|
1438 | |
---|
1439 | def _write_notes(self, datainfo, entry_node): |
---|
1440 | """ |
---|
1441 | Writes the notes to the XML file and creates an empty note if none |
---|
1442 | exist |
---|
1443 | |
---|
1444 | :param datainfo: The Data1D object the information is coming from |
---|
1445 | :param entry_node: lxml node ElementTree object to be appended to |
---|
1446 | |
---|
1447 | """ |
---|
1448 | if len(datainfo.notes) == 0: |
---|
1449 | node = self.create_element("SASnote") |
---|
1450 | self.append(node, entry_node) |
---|
1451 | else: |
---|
1452 | for item in datainfo.notes: |
---|
1453 | node = self.create_element("SASnote") |
---|
1454 | self.write_text(node, item) |
---|
1455 | self.append(node, entry_node) |
---|
1456 | |
---|
1457 | def _check_root(self): |
---|
1458 | """ |
---|
1459 | Return the document, and the SASentry node associated with |
---|
1460 | the data we just wrote. |
---|
1461 | If the calling function was not the cansas reader, return a minidom |
---|
1462 | object rather than an lxml object. |
---|
1463 | |
---|
1464 | :param entry_node: lxml node ElementTree object to be appended to |
---|
1465 | :param doc: entire xml tree |
---|
1466 | """ |
---|
1467 | if not self.frm: |
---|
1468 | self.frm = inspect.stack()[2] |
---|
1469 | mod_name = self.frm[1].replace("\\", "/").replace(".pyc", "") |
---|
1470 | mod_name = mod_name.replace(".py", "") |
---|
1471 | mod = mod_name.split("sas/") |
---|
1472 | mod_name = mod[1] |
---|
1473 | return mod_name == "sascalc/dataloader/readers/cansas_reader" |
---|
1474 | |
---|
1475 | def _check_origin(self, entry_node, doc): |
---|
1476 | """ |
---|
1477 | Return the document, and the SASentry node associated with |
---|
1478 | the data we just wrote. |
---|
1479 | If the calling function was not the cansas reader, return a minidom |
---|
1480 | object rather than an lxml object. |
---|
1481 | |
---|
1482 | :param entry_node: lxml node ElementTree object to be appended to |
---|
1483 | :param doc: entire xml tree |
---|
1484 | """ |
---|
1485 | if not self._check_root(): |
---|
1486 | string = self.to_string(doc, pretty_print=False) |
---|
1487 | doc = parseString(string) |
---|
1488 | node_name = entry_node.tag |
---|
1489 | node_list = doc.getElementsByTagName(node_name) |
---|
1490 | entry_node = node_list.item(0) |
---|
1491 | return doc, entry_node |
---|
1492 | |
---|
1493 | # DO NOT REMOVE - used in saving and loading panel states. |
---|
1494 | def _store_float(self, location, node, variable, storage, optional=True): |
---|
1495 | """ |
---|
1496 | Get the content of a xpath location and store |
---|
1497 | the result. Check that the units are compatible |
---|
1498 | with the destination. The value is expected to |
---|
1499 | be a float. |
---|
1500 | |
---|
1501 | The xpath location might or might not exist. |
---|
1502 | If it does not exist, nothing is done |
---|
1503 | |
---|
1504 | :param location: xpath location to fetch |
---|
1505 | :param node: node to read the data from |
---|
1506 | :param variable: name of the data member to store it in [string] |
---|
1507 | :param storage: data object that has the 'variable' data member |
---|
1508 | :param optional: if True, no exception will be raised |
---|
1509 | if unit conversion can't be done |
---|
1510 | |
---|
1511 | :raise ValueError: raised when the units are not recognized |
---|
1512 | """ |
---|
1513 | entry = get_content(location, node) |
---|
1514 | try: |
---|
1515 | value = float(entry.text) |
---|
1516 | except: |
---|
1517 | value = None |
---|
1518 | |
---|
1519 | if value is not None: |
---|
1520 | # If the entry has units, check to see that they are |
---|
1521 | # compatible with what we currently have in the data object |
---|
1522 | units = entry.get('unit') |
---|
1523 | if units is not None: |
---|
1524 | toks = variable.split('.') |
---|
1525 | local_unit = None |
---|
1526 | exec "local_unit = storage.%s_unit" % toks[0] |
---|
1527 | if local_unit != None and units.lower() != local_unit.lower(): |
---|
1528 | if HAS_CONVERTER == True: |
---|
1529 | try: |
---|
1530 | conv = Converter(units) |
---|
1531 | exec "storage.%s = %g" % \ |
---|
1532 | (variable, conv(value, units=local_unit)) |
---|
1533 | except: |
---|
1534 | _, exc_value, _ = sys.exc_info() |
---|
1535 | err_mess = "CanSAS reader: could not convert" |
---|
1536 | err_mess += " %s unit [%s]; expecting [%s]\n %s" \ |
---|
1537 | % (variable, units, local_unit, exc_value) |
---|
1538 | self.errors.add(err_mess) |
---|
1539 | if optional: |
---|
1540 | logging.info(err_mess) |
---|
1541 | else: |
---|
1542 | raise ValueError, err_mess |
---|
1543 | else: |
---|
1544 | err_mess = "CanSAS reader: unrecognized %s unit [%s];"\ |
---|
1545 | % (variable, units) |
---|
1546 | err_mess += " expecting [%s]" % local_unit |
---|
1547 | self.errors.add(err_mess) |
---|
1548 | if optional: |
---|
1549 | logging.info(err_mess) |
---|
1550 | else: |
---|
1551 | raise ValueError, err_mess |
---|
1552 | else: |
---|
1553 | exec "storage.%s = value" % variable |
---|
1554 | else: |
---|
1555 | exec "storage.%s = value" % variable |
---|
1556 | |
---|
1557 | # DO NOT REMOVE - used in saving and loading panel states. |
---|
1558 | def _store_content(self, location, node, variable, storage): |
---|
1559 | """ |
---|
1560 | Get the content of a xpath location and store |
---|
1561 | the result. The value is treated as a string. |
---|
1562 | |
---|
1563 | The xpath location might or might not exist. |
---|
1564 | If it does not exist, nothing is done |
---|
1565 | |
---|
1566 | :param location: xpath location to fetch |
---|
1567 | :param node: node to read the data from |
---|
1568 | :param variable: name of the data member to store it in [string] |
---|
1569 | :param storage: data object that has the 'variable' data member |
---|
1570 | |
---|
1571 | :return: return a list of errors |
---|
1572 | """ |
---|
1573 | entry = get_content(location, node) |
---|
1574 | if entry is not None and entry.text is not None: |
---|
1575 | exec "storage.%s = entry.text.strip()" % variable |
---|
1576 | |
---|
1577 | |
---|
1578 | # DO NOT REMOVE Called by outside packages: |
---|
1579 | # sas.sasgui.perspectives.invariant.invariant_state |
---|
1580 | # sas.sasgui.perspectives.fitting.pagestate |
---|
1581 | def get_content(location, node): |
---|
1582 | """ |
---|
1583 | Get the first instance of the content of a xpath location. |
---|
1584 | |
---|
1585 | :param location: xpath location |
---|
1586 | :param node: node to start at |
---|
1587 | |
---|
1588 | :return: Element, or None |
---|
1589 | """ |
---|
1590 | nodes = node.xpath(location, |
---|
1591 | namespaces={'ns': CANSAS_NS.get("1.0").get("ns")}) |
---|
1592 | if len(nodes) > 0: |
---|
1593 | return nodes[0] |
---|
1594 | else: |
---|
1595 | return None |
---|
1596 | |
---|
1597 | # DO NOT REMOVE Called by outside packages: |
---|
1598 | # sas.sasgui.perspectives.fitting.pagestate |
---|
1599 | def write_node(doc, parent, name, value, attr=None): |
---|
1600 | """ |
---|
1601 | :param doc: document DOM |
---|
1602 | :param parent: parent node |
---|
1603 | :param name: tag of the element |
---|
1604 | :param value: value of the child text node |
---|
1605 | :param attr: attribute dictionary |
---|
1606 | |
---|
1607 | :return: True if something was appended, otherwise False |
---|
1608 | """ |
---|
1609 | if attr is None: |
---|
1610 | attr = {} |
---|
1611 | if value is not None: |
---|
1612 | node = doc.createElement(name) |
---|
1613 | node.appendChild(doc.createTextNode(str(value))) |
---|
1614 | for item in attr: |
---|
1615 | node.setAttribute(item, attr[item]) |
---|
1616 | parent.appendChild(node) |
---|
1617 | return True |
---|
1618 | return False |
---|