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 | self._check_for_empty_data() |
---|
198 | self._initialize_new_data_set(dom) |
---|
199 | |
---|
200 | self.names.append("SASentry") |
---|
201 | self.parent_class = "SASentry" |
---|
202 | |
---|
203 | self.base_ns = "{0}{1}{2}".format("{", \ |
---|
204 | CANSAS_NS.get(self.cansas_version).get("ns"), "}") |
---|
205 | |
---|
206 | self.ns_list = CONSTANTS.iterate_namespace(self.names) |
---|
207 | |
---|
208 | # Go through each child in the parent element |
---|
209 | for sasNode in dom: |
---|
210 | # Get the element name and set the current name's level |
---|
211 | currentTagName = sasNode.tag.replace(self.base_ns, "") |
---|
212 | # As this is the most likely tag to examine, lets put it first! |
---|
213 | if currentTagName == "SASdata": |
---|
214 | # Are there multiple entries here? |
---|
215 | if len(sasNode) <= 1: |
---|
216 | multipleEntries = False |
---|
217 | else: |
---|
218 | multipleEntries = True |
---|
219 | |
---|
220 | for setupNode in sasNode[0]: |
---|
221 | # Iterating through the tags in the unit node, getting their tag name and respective unit |
---|
222 | setupTagName = setupNode.tag.replace(self.base_ns, "") |
---|
223 | units = setupNode.attrib.get("unit", "") |
---|
224 | |
---|
225 | # Creating our data array first, if there's only one dataNode we will handle this... |
---|
226 | startArray = np.fromstring(setupNode.text, dtype=float, sep=",") |
---|
227 | |
---|
228 | if multipleEntries == True: |
---|
229 | setupArray = np.zeros((len(sasNode), len(startArray))) |
---|
230 | setupArray[0] = startArray |
---|
231 | else: |
---|
232 | setupArray = startArray |
---|
233 | |
---|
234 | # Now put this into the relevant location |
---|
235 | if setupTagName == "I": |
---|
236 | self.current_dataset.yaxis("Intensity", units) |
---|
237 | self.current_dataset.y = setupArray |
---|
238 | elif setupTagName == "Q": |
---|
239 | self.current_dataset.xaxis("Q", units) |
---|
240 | self.current_dataset.x = setupArray |
---|
241 | |
---|
242 | elif setupTagName == "Idev": |
---|
243 | self.current_dataset.dy = setupArray |
---|
244 | elif setupTagName == "Qdev": |
---|
245 | self.current_dataset.dx = setupArray |
---|
246 | |
---|
247 | elif setupTagName == "Qx": |
---|
248 | self.current_dataset.xaxis("Qx", units) |
---|
249 | self.current_dataset.qx_data = setupArray |
---|
250 | elif setupTagName == "Qy": |
---|
251 | self.current_dataset.yaxis("Qy", units) |
---|
252 | self.current_dataset.qy_data = setupArray |
---|
253 | elif setupTagName == "Qxdev": |
---|
254 | self.current_dataset.xaxis("Qxdev", units) |
---|
255 | self.current_dataset.dqx_data = setupArray |
---|
256 | elif setupTagName == "Qydev": |
---|
257 | self.current_dataset.yaxis("Qydev", units) |
---|
258 | self.current_dataset.dqy_data = setupArray |
---|
259 | elif setupTagName == "dQw": |
---|
260 | self.current_dataset.dxw = setupArray |
---|
261 | elif setupTagName == "dQl": |
---|
262 | self.current_dataset.dxl = setupArray |
---|
263 | |
---|
264 | elif setupTagName == "Mask": |
---|
265 | self.current_dataset.mask = np.ndarray.astype(setupArray, dtype=bool) |
---|
266 | elif setupTagName == "Sesans": |
---|
267 | self.current_datainfo.isSesans = bool(setupNode.text) |
---|
268 | |
---|
269 | elif setupTagName == "zacceptance": |
---|
270 | self.current_datainfo.sample.zacceptance = (setupNode.text, units) |
---|
271 | elif setupTagName == "Qmean": |
---|
272 | pass |
---|
273 | elif setupTagName == "Shadowfactor": |
---|
274 | pass |
---|
275 | |
---|
276 | # If there's more data present, let's deal with that too |
---|
277 | for loopIter in range(1, len(sasNode)): |
---|
278 | for dataNode in sasNode[loopIter]: |
---|
279 | # Iterating through the tags in the unit node, getting their tag name and respective unit |
---|
280 | dataTagName = dataNode.tag.replace(self.base_ns, "") |
---|
281 | # Creating our data array first |
---|
282 | dataArray = np.fromstring(dataNode.text, dtype=float, sep=",") |
---|
283 | |
---|
284 | if dataTagName == "I": |
---|
285 | self.current_dataset.y[loopIter] = dataArray |
---|
286 | elif dataTagName == "Q": |
---|
287 | self.current_dataset.x[loopIter] = dataArray |
---|
288 | elif dataTagName == "Idev": |
---|
289 | self.current_dataset.dy[loopIter] = dataArray |
---|
290 | elif dataTagName == "Qdev": |
---|
291 | self.current_dataset.dx[loopIter] = dataArray |
---|
292 | elif dataTagName == "Qx": |
---|
293 | self.current_dataset.qx_data[loopIter] = dataArray |
---|
294 | elif dataTagName == "Qy": |
---|
295 | self.current_dataset.qy_data[loopIter] = dataArray |
---|
296 | elif dataTagName == "Qxdev": |
---|
297 | self.current_dataset.dqx_data[loopIter] = dataArray |
---|
298 | elif dataTagName == "Qydev": |
---|
299 | self.current_dataset.dqy_data[loopIter] = dataArray |
---|
300 | elif dataTagName == "dQw": |
---|
301 | self.current_dataset.dxw[loopIter] = dataArray |
---|
302 | elif dataTagName == "dQl": |
---|
303 | self.current_dataset.dxl[loopIter] = dataArray |
---|
304 | |
---|
305 | self._check_for_empty_resolution() |
---|
306 | self.data.append(self.current_dataset) |
---|
307 | |
---|
308 | # If it's not data, let's check for other tags starting with skippable ones... |
---|
309 | elif currentTagName == "fitting_plug_in" or currentTagName == "pr_inversion" or currentTagName == "invariant": |
---|
310 | continue |
---|
311 | |
---|
312 | # If we'e dealing with a title node then extract the text of the node and put it in the right place |
---|
313 | elif currentTagName == "Title": |
---|
314 | self.current_datainfo.title = sasNode.text |
---|
315 | |
---|
316 | |
---|
317 | # If we'e dealing with a run node then extract the name and text of the node and put it in the right place |
---|
318 | elif currentTagName == "Run": |
---|
319 | self.current_datainfo.run_name[sasNode.text] = sasNode.attrib.get("name", "") |
---|
320 | self.current_datainfo.run.append(sasNode.text) |
---|
321 | |
---|
322 | # If we'e dealing with a sample node |
---|
323 | elif currentTagName == "SASsample": |
---|
324 | for sampleNode in sasNode: |
---|
325 | # Get the variables |
---|
326 | sampleTagName = sampleNode.tag.replace(self.base_ns, "") |
---|
327 | sampleUnits = sampleNode.attrib.get("unit", "") |
---|
328 | sampleData = sampleNode.text |
---|
329 | |
---|
330 | # Populate it via if switching |
---|
331 | if sampleTagName == "ID": |
---|
332 | self.current_datainfo.sample.ID = sampleData |
---|
333 | elif sampleTagName == "Title": |
---|
334 | self.current_datainfo.sample.name = sampleData |
---|
335 | elif sampleTagName == "thickness": |
---|
336 | self.current_datainfo.sample.thickness = sampleData |
---|
337 | self.current_datainfo.sample.thickness_unit = sampleUnits |
---|
338 | elif sampleTagName == "transmission": |
---|
339 | self.current_datainfo.sample.transmission = sampleData |
---|
340 | elif sampleTagName == "temperature": |
---|
341 | self.current_datainfo.sample.temperature = sampleData |
---|
342 | self.current_datainfo.sample.temperature_unit = sampleUnits |
---|
343 | elif sampleTagName == "details": |
---|
344 | self.current_datainfo.sample.details.append(sampleData) |
---|
345 | |
---|
346 | # Extract the positional data |
---|
347 | elif sampleTagName == "position": |
---|
348 | for positionNode in sampleNode: |
---|
349 | positionTagName = positionNode.tag.replace(self.base_ns, "") |
---|
350 | positionUnits = positionNode.attrib.get("unit", "") |
---|
351 | positionData = positionNode.text |
---|
352 | |
---|
353 | # Extract specific tags |
---|
354 | if positionTagName == "x": |
---|
355 | self.current_datainfo.sample.position.x = positionData |
---|
356 | self.current_datainfo.sample.position_unit = positionUnits |
---|
357 | elif positionTagName == "y": |
---|
358 | self.current_datainfo.sample.position.y = positionData |
---|
359 | self.current_datainfo.sample.position_unit = positionUnits |
---|
360 | elif positionTagName == "z": |
---|
361 | self.current_datainfo.sample.position.z = positionData |
---|
362 | self.current_datainfo.sample.position_unit = positionUnits |
---|
363 | |
---|
364 | # Extract the orientation data |
---|
365 | elif sampleTagName == "orientation": |
---|
366 | for orientationNode in sampleNode: |
---|
367 | orientationTagName = orientationNode.tag.replace(self.base_ns, "") |
---|
368 | orientationUnits = orientationNode.attrib.get("unit", "") |
---|
369 | orientationData = orientationNode.text |
---|
370 | |
---|
371 | # Extract specific tags |
---|
372 | if orientationTagName == "roll": |
---|
373 | self.current_datainfo.sample.orientation.x = orientationData |
---|
374 | self.current_datainfo.sample.orientation_unit = orientationUnits |
---|
375 | elif orientationTagName == "pitch": |
---|
376 | self.current_datainfo.sample.orientation.y = orientationData |
---|
377 | self.current_datainfo.sample.orientation_unit = orientationUnits |
---|
378 | elif orientationTagName == "yaw": |
---|
379 | self.current_datainfo.sample.orientation.z = orientationData |
---|
380 | self.current_datainfo.sample.orientation_unit = orientationUnits |
---|
381 | |
---|
382 | # If we're dealing with an instrument node |
---|
383 | elif currentTagName == "SASinstrument": |
---|
384 | for instrumentNode in sasNode: |
---|
385 | instrumentTagName = instrumentNode.tag.replace(self.base_ns, "") |
---|
386 | instrumentUnits = instrumentNode.attrib.get("unit", "") |
---|
387 | instrumentData = instrumentNode.text |
---|
388 | |
---|
389 | # Extract the source name |
---|
390 | if instrumentTagName == "SASsource": |
---|
391 | self.name = instrumentNode.attrib.get("name", "") |
---|
392 | |
---|
393 | for sourceNode in instrumentNode: |
---|
394 | sourceTagName = sourceNode.tag.replace(self.base_ns, "") |
---|
395 | sourceUnits = sourceNode.attrib.get("unit", "") |
---|
396 | sourceData = sourceNode.text |
---|
397 | |
---|
398 | ## Source Information |
---|
399 | if sourceTagName == "wavelength": |
---|
400 | self.current_datainfo.source.wavelength = sourceData |
---|
401 | self.current_datainfo.source.wavelength_unit = sourceUnits |
---|
402 | elif sourceTagName == "wavelength_min": |
---|
403 | self.current_datainfo.source.wavelength_min = sourceData |
---|
404 | self.current_datainfo.source.wavelength_min_unit = sourceUnits |
---|
405 | elif sourceTagName == "wavelength_max": |
---|
406 | self.current_datainfo.source.wavelength_max = sourceData |
---|
407 | self.current_datainfo.source.wavelength_max_unit = sourceUnits |
---|
408 | elif sourceTagName == "wavelength_spread": |
---|
409 | self.current_datainfo.source.wavelength_spread = sourceData |
---|
410 | self.current_datainfo.source.wavelength_spread_unit = sourceUnits |
---|
411 | elif sourceTagName == "radiation": |
---|
412 | self.current_datainfo.source.radiation = sourceData |
---|
413 | elif sourceTagName == "beam_shape": |
---|
414 | self.current_datainfo.source.beam_shape = sourceData |
---|
415 | |
---|
416 | elif sourceTagName == "beam_size": |
---|
417 | for beamNode in sourceNode: |
---|
418 | beamTagName = beamNode.tag.replace(self.base_ns, "") |
---|
419 | beamUnits = beamNode.attrib.get("unit", "") |
---|
420 | beamData = beamNode.text |
---|
421 | |
---|
422 | if beamTagName == "x" and self.parent_class == "beam_size": |
---|
423 | self.current_datainfo.source.beam_size.x = beamData |
---|
424 | self.current_datainfo.source.beam_size_unit = beamUnits |
---|
425 | elif beamTagName == "y" and self.parent_class == "beam_size": |
---|
426 | self.current_datainfo.source.beam_size.y = beamData |
---|
427 | self.current_datainfo.source.beam_size_unit = beamUnits |
---|
428 | |
---|
429 | elif sourceTagName == "pixel_size": |
---|
430 | for pixelNode in sourceNode: |
---|
431 | pixelTagName = pixelNode.tag.replace(self.base_ns, "") |
---|
432 | pixelUnits = pixelNode.attrib.get("unit", "") |
---|
433 | pixelData = pixelNode.text |
---|
434 | |
---|
435 | if pixelTagName == "z": |
---|
436 | self.current_datainfo.source.data_point.z = pixelData |
---|
437 | self.current_datainfo.source.beam_size_unit = pixelUnits |
---|
438 | |
---|
439 | # Extract the collimation |
---|
440 | elif instrumentTagName == "SAScollimation": |
---|
441 | self.collimation.name = instrumentNode.attrib.get("name", "") |
---|
442 | |
---|
443 | for collimationNode in instrumentNode: |
---|
444 | collimationTagName = pixelNode.tag.replace(self.base_ns, "") |
---|
445 | collimationUnits = pixelNode.attrib.get("unit", "") |
---|
446 | collimationData = pixelNode.text |
---|
447 | |
---|
448 | if collimationTagName == "length": |
---|
449 | self.collimation.length = collimationData |
---|
450 | self.collimation.length_unit = collimationUnits |
---|
451 | elif collimationTagName == "name": |
---|
452 | self.collimation.name = collimationData |
---|
453 | |
---|
454 | if collimationTagName == "aperture": |
---|
455 | for apertureNode in collimationNode: |
---|
456 | apertureTagName = apertureNode.tag.replace(self.base_ns, "") |
---|
457 | apertureUnits = apertureNode.attrib.get("unit", "") |
---|
458 | apertureData = apertureNode.text |
---|
459 | |
---|
460 | if tagname == "distance": |
---|
461 | self.aperture.distance = apertureData |
---|
462 | self.aperture.distance_unit = apertureUnits |
---|
463 | |
---|
464 | if collimationTagName == "size": |
---|
465 | for sizeNode in collimationNode: |
---|
466 | sizeTagName = sizeNode.tag.replace(self.base_ns, "") |
---|
467 | sizeUnits = sizeNode.attrib.get("unit", "") |
---|
468 | sizeData = sizeNode.text |
---|
469 | |
---|
470 | if tagname == "x": |
---|
471 | self.aperture.size.x = sizeData |
---|
472 | self.collimation.size_unit = sizeUnits |
---|
473 | elif tagname == "y": |
---|
474 | self.aperture.size.y = sizeData |
---|
475 | self.collimation.size_unit = sizeUnits |
---|
476 | elif tagname == "z": |
---|
477 | self.aperture.size.z = sizeData |
---|
478 | self.collimation.size_unit = sizeUnits |
---|
479 | |
---|
480 | self.current_datainfo.collimation.append(self.collimation) |
---|
481 | self.collimation = Collimation() |
---|
482 | |
---|
483 | # Extract the detector |
---|
484 | elif instrumentTagName == "SASdetector": |
---|
485 | self.name = instrumentNode.attrib.get("name", "") |
---|
486 | |
---|
487 | for detectorNode in instrumentNode: |
---|
488 | detectorTagName = detectorNode.tag.replace(self.base_ns, "") |
---|
489 | detectorUnits = detectorNode.attrib.get("unit", "") |
---|
490 | detectorData = detectorNode.text |
---|
491 | |
---|
492 | if detectorTagName == "name": |
---|
493 | self.detector.name = detectorData |
---|
494 | elif detectorTagName == "SDD": |
---|
495 | self.detector.distance = detectorData |
---|
496 | self.detector.distance_unit = detectorUnits |
---|
497 | elif detectorTagName == "slit_length": |
---|
498 | self.detector.slit_length = detectorData |
---|
499 | self.detector.slit_length_unit = detectorUnits |
---|
500 | |
---|
501 | elif detectorTagName == "offset": |
---|
502 | for offsetNode in detectorNode: |
---|
503 | offsetTagName = offsetNode.tag.replace(self.base_ns, "") |
---|
504 | offsetUnits = offsetNode.attrib.get("unit", "") |
---|
505 | offsetData = offsetNode.text |
---|
506 | |
---|
507 | if offsetTagName == "x": |
---|
508 | self.detector.offset.x = offsetData |
---|
509 | self.detector.offset_unit = offsetUnits |
---|
510 | elif offsetTagName == "y": |
---|
511 | self.detector.offset.y = offsetData |
---|
512 | self.detector.offset_unit = offsetUnits |
---|
513 | elif offsetTagName == "z": |
---|
514 | self.detector.offset.z = offsetData |
---|
515 | self.detector.offset_unit = offsetUnits |
---|
516 | |
---|
517 | elif detectorTagName == "beam_center": |
---|
518 | for beamCenterNode in detectorNode: |
---|
519 | beamCenterTagName = beamCenterNode.tag.replace(self.base_ns, "") |
---|
520 | beamCenterUnits = beamCenterNode.attrib.get("unit", "") |
---|
521 | beamCenterData = beamCenterNode.text |
---|
522 | |
---|
523 | if beamCenterTagName == "x": |
---|
524 | self.detector.beam_center.x = beamCenterData |
---|
525 | self.detector.beam_center_unit = beamCenterUnits |
---|
526 | elif beamCenterTagName == "y": |
---|
527 | self.detector.beam_center.y = beamCenterData |
---|
528 | self.detector.beam_center_unit = beamCenterUnits |
---|
529 | elif beamCenterTagName == "z": |
---|
530 | self.detector.beam_center.z = beamCenterData |
---|
531 | self.detector.beam_center_unit = beamCenterUnits |
---|
532 | |
---|
533 | elif detectorTagName == "pixel_size": |
---|
534 | for pixelSizeNode in detectorNode: |
---|
535 | pixelSizeTagName = pixelSizeNode.tag.replace(self.base_ns, "") |
---|
536 | pixelSizeUnits = pixelSizeNode.attrib.get("unit", "") |
---|
537 | pixelSizeData = pixelSizeNode.text |
---|
538 | |
---|
539 | if pixelSizeTagName == "x": |
---|
540 | self.detector.pixel_size.x = pixelSizeData |
---|
541 | self.detector.pixel_size_unit = pixelSizeUnits |
---|
542 | elif pixelSizeTagName == "y": |
---|
543 | self.detector.pixel_size.y = pixelSizeData |
---|
544 | self.detector.pixel_size_unit = pixelSizeUnits |
---|
545 | elif pixelSizeTagName == "z": |
---|
546 | self.detector.pixel_size.z = pixelSizeData |
---|
547 | self.detector.pixel_size_unit = pixelSizeUnits |
---|
548 | |
---|
549 | elif detectorTagName == "orientation": |
---|
550 | for orientationNode in detectorNode: |
---|
551 | orientationTagName = orientationNode.tag.replace(self.base_ns, "") |
---|
552 | orientationUnits = orientationNode.attrib.get("unit", "") |
---|
553 | orientationData = orientationNode.text |
---|
554 | |
---|
555 | if orientationTagName == "roll": |
---|
556 | self.detector.orientation.x = orientationData |
---|
557 | self.detector.orientation_unit = orientationUnits |
---|
558 | elif orientationTagName == "pitch": |
---|
559 | self.detector.orientation.y = orientationData |
---|
560 | self.detector.orientation_unit = orientationUnits |
---|
561 | elif orientationTagName == "yaw": |
---|
562 | self.detector.orientation.z = orientationData |
---|
563 | self.detector.orientation_unit = orientationUnits |
---|
564 | |
---|
565 | self.current_datainfo.detector.append(self.detector) |
---|
566 | self.detector = Detector() |
---|
567 | |
---|
568 | ## If we'e dealing with a process node |
---|
569 | elif currentTagName == "SASprocess": |
---|
570 | for processNode in sasNode: |
---|
571 | setupTagName = setupNode.tag.replace(self.base_ns, "") |
---|
572 | units = setupNode.attrib.get("unit", "") |
---|
573 | |
---|
574 | if processTagName == "name": |
---|
575 | self.process.name = processNode.text |
---|
576 | elif processTagName == "description": |
---|
577 | self.process.description = processNode.text |
---|
578 | elif processTagName == "date": |
---|
579 | try: |
---|
580 | self.process.date = datetime.datetime.fromtimestamp(processNode.text) |
---|
581 | except: |
---|
582 | self.process.date = processNode.text |
---|
583 | elif processTagName == "term": |
---|
584 | unit = attr.get("unit", "") |
---|
585 | dic = {} |
---|
586 | dic["name"] = processNode.attrib.get("name", "") |
---|
587 | dic["value"] = processNode.text |
---|
588 | dic["unit"] = processNode.attrib.get("unit", "") |
---|
589 | self.process.term.append(dic) |
---|
590 | |
---|
591 | self.current_datainfo.process.append(self.process) |
---|
592 | self.process = Process() |
---|
593 | |
---|
594 | # If we're dealing with a process note node |
---|
595 | elif currentTagName == "SASprocessnote": |
---|
596 | for processNoteNode in sasNode: |
---|
597 | self.process.notes.append(processNoteNode.text) |
---|
598 | |
---|
599 | # If we're dealing with a sas note node |
---|
600 | elif currentTagName == "SASnote": |
---|
601 | for noteNode in sasNode: |
---|
602 | self.current_datainfo.notes.append(noteNode.text) |
---|
603 | |
---|
604 | # If we're dealing with a transmission data node |
---|
605 | elif currentTagName == "Tdata": |
---|
606 | for transmissionDataNode in sasNode: |
---|
607 | transmissionDataTagName = transmissionDataNode.tag.replace(self.base_ns, "") |
---|
608 | transmissionDataUnits = transmissionDataNode.attrib.get("unit", "") |
---|
609 | transmissionDataData = transmissionDataNode.text |
---|
610 | |
---|
611 | # Are there multiple entries here? |
---|
612 | if len(sasNode) <= 1: |
---|
613 | multipleEntries == False |
---|
614 | else: |
---|
615 | multipleEntries == True |
---|
616 | |
---|
617 | for setupNode in sasNode[0]: |
---|
618 | # Iterating through the tags in the unit node, getting their tag name and respective unit |
---|
619 | setupTagName = setupNode.tag.replace(self.base_ns, "") |
---|
620 | transmissionDataUnits = setupNode.attrib.get("unit", "") |
---|
621 | |
---|
622 | # Creating our data array first, if there's only one dataNode we will handle this... |
---|
623 | startArray = np.fromstring(setupNode.text, dtype=float, sep=",") |
---|
624 | |
---|
625 | if multipleEntries == True: |
---|
626 | setupArray = np.zeros((len(sasNode), len(startArray))) |
---|
627 | setupArray[0] = startArray |
---|
628 | else: |
---|
629 | setupArray = startArray |
---|
630 | |
---|
631 | ## Transmission Spectrum |
---|
632 | if setupTagName == "T": |
---|
633 | self.transspectrum.transmission = setupArray |
---|
634 | self.transspectrum.transmission_unit = transmissionDataUnits |
---|
635 | elif setupTagName == "Tdev": |
---|
636 | self.transspectrum.transmission_deviation = setupArray |
---|
637 | self.transspectrum.transmission_deviation_unit = transmissionDataUnits |
---|
638 | elif setupTagName == "Lambda": |
---|
639 | self.transspectrum.wavelength = setupArray |
---|
640 | self.transspectrum.wavelength_unit = transmissionDataUnits |
---|
641 | |
---|
642 | # If there's more data present, let's deal with that too |
---|
643 | for loopIter in range(1, len(sasNode)): |
---|
644 | for dataNode in sasNode[loopIter]: |
---|
645 | dataTagName = dataNode.tag.replace(self.base_ns, "") |
---|
646 | dataArray = np.fromstring(dataNode.text, dtype=float, sep=",") |
---|
647 | |
---|
648 | if dataTagName == "T": |
---|
649 | self.transspectrum.transmission[loopIter] = setupArray |
---|
650 | elif dataTagName == "Tdev": |
---|
651 | self.transspectrum.transmission_deviation[loopIter] = setupArray |
---|
652 | elif dataTagName == "Lambda": |
---|
653 | self.transspectrum.wavelength[loopIter] = setupArray |
---|
654 | |
---|
655 | self.current_datainfo.trans_spectrum.append(self.transspectrum) |
---|
656 | self.transspectrum = TransmissionSpectrum() |
---|
657 | |
---|
658 | |
---|
659 | ## Everything else goes in meta_data |
---|
660 | else: |
---|
661 | new_key = self._create_unique_key(self.current_datainfo.meta_data, currentTagName) |
---|
662 | self.current_datainfo.meta_data[new_key] = sasNode.text |
---|
663 | |
---|
664 | self.add_intermediate() |
---|
665 | |
---|
666 | # As before in the code, I guess in case we have to return a tuple for some reason... |
---|
667 | return self.output, None |
---|
668 | |
---|
669 | def _is_call_local(self): |
---|
670 | """ |
---|
671 | |
---|
672 | """ |
---|
673 | if self.frm == "": |
---|
674 | inter = inspect.stack() |
---|
675 | self.frm = inter[2] |
---|
676 | mod_name = self.frm[1].replace("\\", "/").replace(".pyc", "") |
---|
677 | mod_name = mod_name.replace(".py", "") |
---|
678 | mod = mod_name.split("sas/") |
---|
679 | mod_name = mod[1] |
---|
680 | if mod_name != "sascalc/dataloader/readers/cansas_reader": |
---|
681 | return False |
---|
682 | return True |
---|
683 | |
---|
684 | def is_cansas(self, ext="xml"): |
---|
685 | """ |
---|
686 | Checks to see if the xml file is a CanSAS file |
---|
687 | |
---|
688 | :param ext: The file extension of the data file |
---|
689 | """ |
---|
690 | if self.validate_xml(): |
---|
691 | name = "{http://www.w3.org/2001/XMLSchema-instance}schemaLocation" |
---|
692 | value = self.xmlroot.get(name) |
---|
693 | if CANSAS_NS.get(self.cansas_version).get("ns") == \ |
---|
694 | value.rsplit(" ")[0]: |
---|
695 | return True |
---|
696 | if ext == "svs": |
---|
697 | return True |
---|
698 | raise RuntimeError |
---|
699 | |
---|
700 | def load_file_and_schema(self, xml_file, schema_path=""): |
---|
701 | """ |
---|
702 | Loads the file and associates a schema, if a schema is passed in or if one already exists |
---|
703 | |
---|
704 | :param xml_file: The xml file path sent to Reader.read |
---|
705 | :param schema_path: The path to a schema associated with the xml_file, or find one based on the file |
---|
706 | """ |
---|
707 | base_name = xml_reader.__file__ |
---|
708 | base_name = base_name.replace("\\", "/") |
---|
709 | base = base_name.split("/sas/")[0] |
---|
710 | |
---|
711 | # Load in xml file and get the cansas version from the header |
---|
712 | self.set_xml_file(xml_file) |
---|
713 | self.cansas_version = self.xmlroot.get("version", "1.0") |
---|
714 | |
---|
715 | # Generic values for the cansas file based on the version |
---|
716 | self.cansas_defaults = CANSAS_NS.get(self.cansas_version, "1.0") |
---|
717 | if schema_path == "": |
---|
718 | schema_path = "{0}/sas/sascalc/dataloader/readers/schema/{1}".format \ |
---|
719 | (base, self.cansas_defaults.get("schema")).replace("\\", "/") |
---|
720 | |
---|
721 | # Link a schema to the XML file. |
---|
722 | self.set_schema(schema_path) |
---|
723 | |
---|
724 | def add_data_set(self): |
---|
725 | """ |
---|
726 | Adds the current_dataset to the list of outputs after preforming final processing on the data and then calls a |
---|
727 | private method to generate a new data set. |
---|
728 | |
---|
729 | :param key: NeXus group name for current tree level |
---|
730 | """ |
---|
731 | |
---|
732 | if self.current_datainfo and self.current_dataset: |
---|
733 | self._final_cleanup() |
---|
734 | self.data = [] |
---|
735 | self.current_datainfo = DataInfo() |
---|
736 | |
---|
737 | def _initialize_new_data_set(self, node=None): |
---|
738 | """ |
---|
739 | A private class method to generate a new 1D data object. |
---|
740 | Outside methods should call add_data_set() to be sure any existing data is stored properly. |
---|
741 | |
---|
742 | :param node: XML node to determine if 1D or 2D data |
---|
743 | """ |
---|
744 | x = np.array(0) |
---|
745 | y = np.array(0) |
---|
746 | for child in node: |
---|
747 | if child.tag.replace(self.base_ns, "") == "Idata": |
---|
748 | for i_child in child: |
---|
749 | if i_child.tag.replace(self.base_ns, "") == "Qx": |
---|
750 | self.current_dataset = plottable_2D() |
---|
751 | return |
---|
752 | self.current_dataset = plottable_1D(x, y) |
---|
753 | |
---|
754 | def add_intermediate(self): |
---|
755 | """ |
---|
756 | This method stores any intermediate objects within the final data set after fully reading the set. |
---|
757 | |
---|
758 | :param parent: The NXclass name for the h5py Group object that just finished being processed |
---|
759 | """ |
---|
760 | |
---|
761 | if self.parent_class == 'SASprocess': |
---|
762 | self.current_datainfo.process.append(self.process) |
---|
763 | self.process = Process() |
---|
764 | elif self.parent_class == 'SASdetector': |
---|
765 | self.current_datainfo.detector.append(self.detector) |
---|
766 | self.detector = Detector() |
---|
767 | elif self.parent_class == 'SAStransmission_spectrum': |
---|
768 | self.current_datainfo.trans_spectrum.append(self.transspectrum) |
---|
769 | self.transspectrum = TransmissionSpectrum() |
---|
770 | elif self.parent_class == 'SAScollimation': |
---|
771 | self.current_datainfo.collimation.append(self.collimation) |
---|
772 | self.collimation = Collimation() |
---|
773 | elif self.parent_class == 'aperture': |
---|
774 | self.collimation.aperture.append(self.aperture) |
---|
775 | self.aperture = Aperture() |
---|
776 | elif self.parent_class == 'SASdata': |
---|
777 | self._check_for_empty_resolution() |
---|
778 | self.data.append(self.current_dataset) |
---|
779 | |
---|
780 | def _final_cleanup(self): |
---|
781 | """ |
---|
782 | Final cleanup of the Data1D object to be sure it has all the |
---|
783 | appropriate information needed for perspectives |
---|
784 | """ |
---|
785 | |
---|
786 | # Append errors to dataset and reset class errors |
---|
787 | self.current_datainfo.errors = set() |
---|
788 | for error in self.errors: |
---|
789 | self.current_datainfo.errors.add(error) |
---|
790 | self.errors.clear() |
---|
791 | |
---|
792 | # Combine all plottables with datainfo and append each to output |
---|
793 | # Type cast data arrays to float64 and find min/max as appropriate |
---|
794 | for dataset in self.data: |
---|
795 | if isinstance(dataset, plottable_1D): |
---|
796 | if dataset.x is not None: |
---|
797 | dataset.x = np.delete(dataset.x, [0]) |
---|
798 | dataset.x = dataset.x.astype(np.float64) |
---|
799 | dataset.xmin = np.min(dataset.x) |
---|
800 | dataset.xmax = np.max(dataset.x) |
---|
801 | if dataset.y is not None: |
---|
802 | dataset.y = np.delete(dataset.y, [0]) |
---|
803 | dataset.y = dataset.y.astype(np.float64) |
---|
804 | dataset.ymin = np.min(dataset.y) |
---|
805 | dataset.ymax = np.max(dataset.y) |
---|
806 | if dataset.dx is not None: |
---|
807 | dataset.dx = np.delete(dataset.dx, [0]) |
---|
808 | dataset.dx = dataset.dx.astype(np.float64) |
---|
809 | if dataset.dxl is not None: |
---|
810 | dataset.dxl = np.delete(dataset.dxl, [0]) |
---|
811 | dataset.dxl = dataset.dxl.astype(np.float64) |
---|
812 | if dataset.dxw is not None: |
---|
813 | dataset.dxw = np.delete(dataset.dxw, [0]) |
---|
814 | dataset.dxw = dataset.dxw.astype(np.float64) |
---|
815 | if dataset.dy is not None: |
---|
816 | dataset.dy = np.delete(dataset.dy, [0]) |
---|
817 | dataset.dy = dataset.dy.astype(np.float64) |
---|
818 | np.trim_zeros(dataset.x) |
---|
819 | np.trim_zeros(dataset.y) |
---|
820 | np.trim_zeros(dataset.dy) |
---|
821 | elif isinstance(dataset, plottable_2D): |
---|
822 | dataset.data = dataset.data.astype(np.float64) |
---|
823 | dataset.qx_data = dataset.qx_data.astype(np.float64) |
---|
824 | dataset.xmin = np.min(dataset.qx_data) |
---|
825 | dataset.xmax = np.max(dataset.qx_data) |
---|
826 | dataset.qy_data = dataset.qy_data.astype(np.float64) |
---|
827 | dataset.ymin = np.min(dataset.qy_data) |
---|
828 | dataset.ymax = np.max(dataset.qy_data) |
---|
829 | dataset.q_data = np.sqrt(dataset.qx_data * dataset.qx_data |
---|
830 | + dataset.qy_data * dataset.qy_data) |
---|
831 | if dataset.err_data is not None: |
---|
832 | dataset.err_data = dataset.err_data.astype(np.float64) |
---|
833 | if dataset.dqx_data is not None: |
---|
834 | dataset.dqx_data = dataset.dqx_data.astype(np.float64) |
---|
835 | if dataset.dqy_data is not None: |
---|
836 | dataset.dqy_data = dataset.dqy_data.astype(np.float64) |
---|
837 | if dataset.mask is not None: |
---|
838 | dataset.mask = dataset.mask.astype(dtype=bool) |
---|
839 | |
---|
840 | if len(dataset.shape) == 2: |
---|
841 | n_rows, n_cols = dataset.shape |
---|
842 | dataset.y_bins = dataset.qy_data[0::int(n_cols)] |
---|
843 | dataset.x_bins = dataset.qx_data[:int(n_cols)] |
---|
844 | dataset.data = dataset.data.flatten() |
---|
845 | else: |
---|
846 | dataset.y_bins = [] |
---|
847 | dataset.x_bins = [] |
---|
848 | dataset.data = dataset.data.flatten() |
---|
849 | |
---|
850 | final_dataset = combine_data(dataset, self.current_datainfo) |
---|
851 | self.output.append(final_dataset) |
---|
852 | |
---|
853 | def _create_unique_key(self, dictionary, name, numb=0): |
---|
854 | """ |
---|
855 | Create a unique key value for any dictionary to prevent overwriting |
---|
856 | Recurse until a unique key value is found. |
---|
857 | |
---|
858 | :param dictionary: A dictionary with any number of entries |
---|
859 | :param name: The index of the item to be added to dictionary |
---|
860 | :param numb: The number to be appended to the name, starts at 0 |
---|
861 | """ |
---|
862 | if dictionary.get(name) is not None: |
---|
863 | numb += 1 |
---|
864 | name = name.split("_")[0] |
---|
865 | name += "_{0}".format(numb) |
---|
866 | name = self._create_unique_key(dictionary, name, numb) |
---|
867 | return name |
---|
868 | |
---|
869 | def _get_node_value_from_text(self, node, node_text): |
---|
870 | """ |
---|
871 | Get the value of a node and any applicable units |
---|
872 | |
---|
873 | :param node: The XML node to get the value of |
---|
874 | :param tagname: The tagname of the node |
---|
875 | """ |
---|
876 | units = "" |
---|
877 | # If the value is a float, compile with units. |
---|
878 | if self.ns_list.ns_datatype == "float": |
---|
879 | # If an empty value is given, set as zero. |
---|
880 | if node_text is None or node_text.isspace() \ |
---|
881 | or node_text.lower() == "nan": |
---|
882 | node_text = "0.0" |
---|
883 | # Convert the value to the base units |
---|
884 | tag = node.tag.replace(self.base_ns, "") |
---|
885 | node_text, units = self._unit_conversion(node, tag, node_text) |
---|
886 | |
---|
887 | # If the value is a timestamp, convert to a datetime object |
---|
888 | elif self.ns_list.ns_datatype == "timestamp": |
---|
889 | if node_text is None or node_text.isspace(): |
---|
890 | pass |
---|
891 | else: |
---|
892 | try: |
---|
893 | node_text = \ |
---|
894 | datetime.datetime.fromtimestamp(node_text) |
---|
895 | except ValueError: |
---|
896 | node_text = None |
---|
897 | return node_text, units |
---|
898 | |
---|
899 | def _get_node_value(self, node): |
---|
900 | """ |
---|
901 | Get the value of a node and any applicable units |
---|
902 | |
---|
903 | :param node: The XML node to get the value of |
---|
904 | :param tagname: The tagname of the node |
---|
905 | """ |
---|
906 | #Get the text from the node and convert all whitespace to spaces |
---|
907 | units = '' |
---|
908 | node_value = node.text |
---|
909 | if node_value is not None: |
---|
910 | node_value = ' '.join(node_value.split()) |
---|
911 | else: |
---|
912 | node_value = "" |
---|
913 | node_value, units = self._get_node_value_from_text(node, node_value) |
---|
914 | return node_value, units |
---|
915 | |
---|
916 | def _unit_conversion(self, node, tagname, node_value): |
---|
917 | """ |
---|
918 | A unit converter method used to convert the data included in the file |
---|
919 | to the default units listed in data_info |
---|
920 | |
---|
921 | :param node: XML node |
---|
922 | :param tagname: name of the node |
---|
923 | :param node_value: The value of the current dom node |
---|
924 | """ |
---|
925 | attr = node.attrib |
---|
926 | value_unit = '' |
---|
927 | err_msg = None |
---|
928 | default_unit = None |
---|
929 | if not isinstance(node_value, float): |
---|
930 | node_value = float(node_value) |
---|
931 | if 'unit' in attr and attr.get('unit') is not None: |
---|
932 | try: |
---|
933 | local_unit = attr['unit'] |
---|
934 | unitname = self.ns_list.current_level.get("unit", "") |
---|
935 | if "SASdetector" in self.names: |
---|
936 | save_in = "detector" |
---|
937 | elif "aperture" in self.names: |
---|
938 | save_in = "aperture" |
---|
939 | elif "SAScollimation" in self.names: |
---|
940 | save_in = "collimation" |
---|
941 | elif "SAStransmission_spectrum" in self.names: |
---|
942 | save_in = "transspectrum" |
---|
943 | elif "SASdata" in self.names: |
---|
944 | x = np.zeros(1) |
---|
945 | y = np.zeros(1) |
---|
946 | self.current_data1d = Data1D(x, y) |
---|
947 | save_in = "current_data1d" |
---|
948 | elif "SASsource" in self.names: |
---|
949 | save_in = "current_datainfo.source" |
---|
950 | elif "SASsample" in self.names: |
---|
951 | save_in = "current_datainfo.sample" |
---|
952 | elif "SASprocess" in self.names: |
---|
953 | save_in = "process" |
---|
954 | else: |
---|
955 | save_in = "current_datainfo" |
---|
956 | exec "default_unit = self.{0}.{1}".format(save_in, unitname) |
---|
957 | if local_unit and default_unit and local_unit.lower() != default_unit.lower() \ |
---|
958 | and local_unit.lower() != "none": |
---|
959 | if HAS_CONVERTER == True: |
---|
960 | # Check local units - bad units raise KeyError |
---|
961 | data_conv_q = Converter(local_unit) |
---|
962 | value_unit = default_unit |
---|
963 | node_value = data_conv_q(node_value, units=default_unit) |
---|
964 | else: |
---|
965 | value_unit = local_unit |
---|
966 | err_msg = "Unit converter is not available.\n" |
---|
967 | else: |
---|
968 | value_unit = local_unit |
---|
969 | except KeyError: |
---|
970 | err_msg = "CanSAS reader: unexpected " |
---|
971 | err_msg += "\"{0}\" unit [{1}]; " |
---|
972 | err_msg = err_msg.format(tagname, local_unit) |
---|
973 | err_msg += "expecting [{0}]".format(default_unit) |
---|
974 | value_unit = local_unit |
---|
975 | except: |
---|
976 | err_msg = "CanSAS reader: unknown error converting " |
---|
977 | err_msg += "\"{0}\" unit [{1}]" |
---|
978 | err_msg = err_msg.format(tagname, local_unit) |
---|
979 | value_unit = local_unit |
---|
980 | elif 'unit' in attr: |
---|
981 | value_unit = attr['unit'] |
---|
982 | if err_msg: |
---|
983 | self.errors.add(err_msg) |
---|
984 | return node_value, value_unit |
---|
985 | |
---|
986 | def _check_for_empty_data(self): |
---|
987 | """ |
---|
988 | Creates an empty data set if no data is passed to the reader |
---|
989 | |
---|
990 | :param data1d: presumably a Data1D object |
---|
991 | """ |
---|
992 | if self.current_dataset == None: |
---|
993 | x_vals = np.empty(0) |
---|
994 | y_vals = np.empty(0) |
---|
995 | dx_vals = np.empty(0) |
---|
996 | dy_vals = np.empty(0) |
---|
997 | dxl = np.empty(0) |
---|
998 | dxw = np.empty(0) |
---|
999 | self.current_dataset = plottable_1D(x_vals, y_vals, dx_vals, dy_vals) |
---|
1000 | self.current_dataset.dxl = dxl |
---|
1001 | self.current_dataset.dxw = dxw |
---|
1002 | |
---|
1003 | def _check_for_empty_resolution(self): |
---|
1004 | """ |
---|
1005 | A method to check all resolution data sets are the same size as I and Q |
---|
1006 | """ |
---|
1007 | if isinstance(self.current_dataset, plottable_1D): |
---|
1008 | dql_exists = False |
---|
1009 | dqw_exists = False |
---|
1010 | dq_exists = False |
---|
1011 | di_exists = False |
---|
1012 | if self.current_dataset.dxl is not None: |
---|
1013 | dql_exists = True |
---|
1014 | if self.current_dataset.dxw is not None: |
---|
1015 | dqw_exists = True |
---|
1016 | if self.current_dataset.dx is not None: |
---|
1017 | dq_exists = True |
---|
1018 | if self.current_dataset.dy is not None: |
---|
1019 | di_exists = True |
---|
1020 | if dqw_exists and not dql_exists: |
---|
1021 | array_size = self.current_dataset.dxw.size - 1 |
---|
1022 | self.current_dataset.dxl = np.append(self.current_dataset.dxl, |
---|
1023 | np.zeros([array_size])) |
---|
1024 | elif dql_exists and not dqw_exists: |
---|
1025 | array_size = self.current_dataset.dxl.size - 1 |
---|
1026 | self.current_dataset.dxw = np.append(self.current_dataset.dxw, |
---|
1027 | np.zeros([array_size])) |
---|
1028 | elif not dql_exists and not dqw_exists and not dq_exists: |
---|
1029 | array_size = self.current_dataset.x.size - 1 |
---|
1030 | self.current_dataset.dx = np.append(self.current_dataset.dx, |
---|
1031 | np.zeros([array_size])) |
---|
1032 | if not di_exists: |
---|
1033 | array_size = self.current_dataset.y.size - 1 |
---|
1034 | self.current_dataset.dy = np.append(self.current_dataset.dy, |
---|
1035 | np.zeros([array_size])) |
---|
1036 | elif isinstance(self.current_dataset, plottable_2D): |
---|
1037 | dqx_exists = False |
---|
1038 | dqy_exists = False |
---|
1039 | di_exists = False |
---|
1040 | mask_exists = False |
---|
1041 | if self.current_dataset.dqx_data is not None: |
---|
1042 | dqx_exists = True |
---|
1043 | if self.current_dataset.dqy_data is not None: |
---|
1044 | dqy_exists = True |
---|
1045 | if self.current_dataset.err_data is not None: |
---|
1046 | di_exists = True |
---|
1047 | if self.current_dataset.mask is not None: |
---|
1048 | mask_exists = True |
---|
1049 | if not dqy_exists: |
---|
1050 | array_size = self.current_dataset.qy_data.size - 1 |
---|
1051 | self.current_dataset.dqy_data = np.append( |
---|
1052 | self.current_dataset.dqy_data, np.zeros([array_size])) |
---|
1053 | if not dqx_exists: |
---|
1054 | array_size = self.current_dataset.qx_data.size - 1 |
---|
1055 | self.current_dataset.dqx_data = np.append( |
---|
1056 | self.current_dataset.dqx_data, np.zeros([array_size])) |
---|
1057 | if not di_exists: |
---|
1058 | array_size = self.current_dataset.data.size - 1 |
---|
1059 | self.current_dataset.err_data = np.append( |
---|
1060 | self.current_dataset.err_data, np.zeros([array_size])) |
---|
1061 | if not mask_exists: |
---|
1062 | array_size = self.current_dataset.data.size - 1 |
---|
1063 | self.current_dataset.mask = np.append( |
---|
1064 | self.current_dataset.mask, |
---|
1065 | np.ones([array_size] ,dtype=bool)) |
---|
1066 | |
---|
1067 | ####### All methods below are for writing CanSAS XML files ####### |
---|
1068 | |
---|
1069 | def write(self, filename, datainfo): |
---|
1070 | """ |
---|
1071 | Write the content of a Data1D as a CanSAS XML file |
---|
1072 | |
---|
1073 | :param filename: name of the file to write |
---|
1074 | :param datainfo: Data1D object |
---|
1075 | """ |
---|
1076 | # Create XML document |
---|
1077 | doc, _ = self._to_xml_doc(datainfo) |
---|
1078 | # Write the file |
---|
1079 | file_ref = open(filename, 'w') |
---|
1080 | if self.encoding == None: |
---|
1081 | self.encoding = "UTF-8" |
---|
1082 | doc.write(file_ref, encoding=self.encoding, |
---|
1083 | pretty_print=True, xml_declaration=True) |
---|
1084 | file_ref.close() |
---|
1085 | |
---|
1086 | def _to_xml_doc(self, datainfo): |
---|
1087 | """ |
---|
1088 | Create an XML document to contain the content of a Data1D |
---|
1089 | |
---|
1090 | :param datainfo: Data1D object |
---|
1091 | """ |
---|
1092 | is_2d = False |
---|
1093 | if issubclass(datainfo.__class__, Data2D): |
---|
1094 | is_2d = True |
---|
1095 | |
---|
1096 | # Get PIs and create root element |
---|
1097 | pi_string = self._get_pi_string() |
---|
1098 | # Define namespaces and create SASroot object |
---|
1099 | main_node = self._create_main_node() |
---|
1100 | # Create ElementTree, append SASroot and apply processing instructions |
---|
1101 | base_string = pi_string + self.to_string(main_node) |
---|
1102 | base_element = self.create_element_from_string(base_string) |
---|
1103 | doc = self.create_tree(base_element) |
---|
1104 | # Create SASentry Element |
---|
1105 | entry_node = self.create_element("SASentry") |
---|
1106 | root = doc.getroot() |
---|
1107 | root.append(entry_node) |
---|
1108 | |
---|
1109 | # Add Title to SASentry |
---|
1110 | self.write_node(entry_node, "Title", datainfo.title) |
---|
1111 | # Add Run to SASentry |
---|
1112 | self._write_run_names(datainfo, entry_node) |
---|
1113 | # Add Data info to SASEntry |
---|
1114 | if is_2d: |
---|
1115 | self._write_data_2d(datainfo, entry_node) |
---|
1116 | else: |
---|
1117 | if self._check_root(): |
---|
1118 | self._write_data(datainfo, entry_node) |
---|
1119 | else: |
---|
1120 | self._write_data_linearized(datainfo, entry_node) |
---|
1121 | # Transmission Spectrum Info |
---|
1122 | # TODO: fix the writer to linearize all data, including T_spectrum |
---|
1123 | # self._write_trans_spectrum(datainfo, entry_node) |
---|
1124 | # Sample info |
---|
1125 | self._write_sample_info(datainfo, entry_node) |
---|
1126 | # Instrument info |
---|
1127 | instr = self._write_instrument(datainfo, entry_node) |
---|
1128 | # Source |
---|
1129 | self._write_source(datainfo, instr) |
---|
1130 | # Collimation |
---|
1131 | self._write_collimation(datainfo, instr) |
---|
1132 | # Detectors |
---|
1133 | self._write_detectors(datainfo, instr) |
---|
1134 | # Processes info |
---|
1135 | self._write_process_notes(datainfo, entry_node) |
---|
1136 | # Note info |
---|
1137 | self._write_notes(datainfo, entry_node) |
---|
1138 | # Return the document, and the SASentry node associated with |
---|
1139 | # the data we just wrote |
---|
1140 | # If the calling function was not the cansas reader, return a minidom |
---|
1141 | # object rather than an lxml object. |
---|
1142 | self.frm = inspect.stack()[1] |
---|
1143 | doc, entry_node = self._check_origin(entry_node, doc) |
---|
1144 | return doc, entry_node |
---|
1145 | |
---|
1146 | def write_node(self, parent, name, value, attr=None): |
---|
1147 | """ |
---|
1148 | :param doc: document DOM |
---|
1149 | :param parent: parent node |
---|
1150 | :param name: tag of the element |
---|
1151 | :param value: value of the child text node |
---|
1152 | :param attr: attribute dictionary |
---|
1153 | |
---|
1154 | :return: True if something was appended, otherwise False |
---|
1155 | """ |
---|
1156 | if value is not None: |
---|
1157 | parent = self.ebuilder(parent, name, value, attr) |
---|
1158 | return True |
---|
1159 | return False |
---|
1160 | |
---|
1161 | def _get_pi_string(self): |
---|
1162 | """ |
---|
1163 | Creates the processing instructions header for writing to file |
---|
1164 | """ |
---|
1165 | pis = self.return_processing_instructions() |
---|
1166 | if len(pis) > 0: |
---|
1167 | pi_tree = self.create_tree(pis[0]) |
---|
1168 | i = 1 |
---|
1169 | for i in range(1, len(pis) - 1): |
---|
1170 | pi_tree = self.append(pis[i], pi_tree) |
---|
1171 | pi_string = self.to_string(pi_tree) |
---|
1172 | else: |
---|
1173 | pi_string = "" |
---|
1174 | return pi_string |
---|
1175 | |
---|
1176 | def _create_main_node(self): |
---|
1177 | """ |
---|
1178 | Creates the primary xml header used when writing to file |
---|
1179 | """ |
---|
1180 | xsi = "http://www.w3.org/2001/XMLSchema-instance" |
---|
1181 | version = self.cansas_version |
---|
1182 | n_s = CANSAS_NS.get(version).get("ns") |
---|
1183 | if version == "1.1": |
---|
1184 | url = "http://www.cansas.org/formats/1.1/" |
---|
1185 | else: |
---|
1186 | url = "http://www.cansas.org/formats/1.0/" |
---|
1187 | schema_location = "{0} {1}cansas1d.xsd".format(n_s, url) |
---|
1188 | attrib = {"{" + xsi + "}schemaLocation" : schema_location, |
---|
1189 | "version" : version} |
---|
1190 | nsmap = {'xsi' : xsi, None: n_s} |
---|
1191 | |
---|
1192 | main_node = self.create_element("{" + n_s + "}SASroot", |
---|
1193 | attrib=attrib, nsmap=nsmap) |
---|
1194 | return main_node |
---|
1195 | |
---|
1196 | def _write_run_names(self, datainfo, entry_node): |
---|
1197 | """ |
---|
1198 | Writes the run names to the XML file |
---|
1199 | |
---|
1200 | :param datainfo: The Data1D object the information is coming from |
---|
1201 | :param entry_node: lxml node ElementTree object to be appended to |
---|
1202 | """ |
---|
1203 | if datainfo.run == None or datainfo.run == []: |
---|
1204 | datainfo.run.append(RUN_NAME_DEFAULT) |
---|
1205 | datainfo.run_name[RUN_NAME_DEFAULT] = RUN_NAME_DEFAULT |
---|
1206 | for item in datainfo.run: |
---|
1207 | runname = {} |
---|
1208 | if item in datainfo.run_name and \ |
---|
1209 | len(str(datainfo.run_name[item])) > 1: |
---|
1210 | runname = {'name': datainfo.run_name[item]} |
---|
1211 | self.write_node(entry_node, "Run", item, runname) |
---|
1212 | |
---|
1213 | def _write_data(self, datainfo, entry_node): |
---|
1214 | """ |
---|
1215 | Writes 1D I and Q data to the XML file |
---|
1216 | |
---|
1217 | :param datainfo: The Data1D object the information is coming from |
---|
1218 | :param entry_node: lxml node ElementTree object to be appended to |
---|
1219 | """ |
---|
1220 | node = self.create_element("SASdata") |
---|
1221 | self.append(node, entry_node) |
---|
1222 | |
---|
1223 | for i in range(len(datainfo.x)): |
---|
1224 | point = self.create_element("Idata") |
---|
1225 | node.append(point) |
---|
1226 | self.write_node(point, "Q", datainfo.x[i], |
---|
1227 | {'unit': datainfo._xaxis + " | " + datainfo._xunit}) |
---|
1228 | if len(datainfo.y) >= i: |
---|
1229 | self.write_node(point, "I", datainfo.y[i], |
---|
1230 | {'unit': datainfo._yaxis + " | " + datainfo._yunit}) |
---|
1231 | if datainfo.dy is not None and len(datainfo.dy) > i: |
---|
1232 | self.write_node(point, "Idev", datainfo.dy[i], |
---|
1233 | {'unit': datainfo._yaxis + " | " + datainfo._yunit}) |
---|
1234 | if datainfo.dx is not None and len(datainfo.dx) > i: |
---|
1235 | self.write_node(point, "Qdev", datainfo.dx[i], |
---|
1236 | {'unit': datainfo._xaxis + " | " + datainfo._xunit}) |
---|
1237 | if datainfo.dxw is not None and len(datainfo.dxw) > i: |
---|
1238 | self.write_node(point, "dQw", datainfo.dxw[i], |
---|
1239 | {'unit': datainfo._xaxis + " | " + datainfo._xunit}) |
---|
1240 | if datainfo.dxl is not None and len(datainfo.dxl) > i: |
---|
1241 | self.write_node(point, "dQl", datainfo.dxl[i], |
---|
1242 | {'unit': datainfo._xaxis + " | " + datainfo._xunit}) |
---|
1243 | if datainfo.isSesans: |
---|
1244 | sesans = self.create_element("Sesans") |
---|
1245 | sesans.text = str(datainfo.isSesans) |
---|
1246 | node.append(sesans) |
---|
1247 | self.write_node(node, "zacceptance", datainfo.sample.zacceptance[0], |
---|
1248 | {'unit': datainfo.sample.zacceptance[1]}) |
---|
1249 | |
---|
1250 | |
---|
1251 | def _write_data_2d(self, datainfo, entry_node): |
---|
1252 | """ |
---|
1253 | Writes 2D data to the XML file |
---|
1254 | |
---|
1255 | :param datainfo: The Data2D object the information is coming from |
---|
1256 | :param entry_node: lxml node ElementTree object to be appended to |
---|
1257 | """ |
---|
1258 | attr = {} |
---|
1259 | if datainfo.data.shape: |
---|
1260 | attr["x_bins"] = str(len(datainfo.x_bins)) |
---|
1261 | attr["y_bins"] = str(len(datainfo.y_bins)) |
---|
1262 | node = self.create_element("SASdata", attr) |
---|
1263 | self.append(node, entry_node) |
---|
1264 | |
---|
1265 | point = self.create_element("Idata") |
---|
1266 | node.append(point) |
---|
1267 | qx = ','.join([str(datainfo.qx_data[i]) for i in xrange(len(datainfo.qx_data))]) |
---|
1268 | qy = ','.join([str(datainfo.qy_data[i]) for i in xrange(len(datainfo.qy_data))]) |
---|
1269 | intensity = ','.join([str(datainfo.data[i]) for i in xrange(len(datainfo.data))]) |
---|
1270 | |
---|
1271 | self.write_node(point, "Qx", qx, |
---|
1272 | {'unit': datainfo._xunit}) |
---|
1273 | self.write_node(point, "Qy", qy, |
---|
1274 | {'unit': datainfo._yunit}) |
---|
1275 | self.write_node(point, "I", intensity, |
---|
1276 | {'unit': datainfo._zunit}) |
---|
1277 | if datainfo.err_data is not None: |
---|
1278 | err = ','.join([str(datainfo.err_data[i]) for i in |
---|
1279 | xrange(len(datainfo.err_data))]) |
---|
1280 | self.write_node(point, "Idev", err, |
---|
1281 | {'unit': datainfo._zunit}) |
---|
1282 | if datainfo.dqy_data is not None: |
---|
1283 | dqy = ','.join([str(datainfo.dqy_data[i]) for i in |
---|
1284 | xrange(len(datainfo.dqy_data))]) |
---|
1285 | self.write_node(point, "Qydev", dqy, |
---|
1286 | {'unit': datainfo._yunit}) |
---|
1287 | if datainfo.dqx_data is not None: |
---|
1288 | dqx = ','.join([str(datainfo.dqx_data[i]) for i in |
---|
1289 | xrange(len(datainfo.dqx_data))]) |
---|
1290 | self.write_node(point, "Qxdev", dqx, |
---|
1291 | {'unit': datainfo._xunit}) |
---|
1292 | if datainfo.mask is not None: |
---|
1293 | mask = ','.join( |
---|
1294 | ["1" if datainfo.mask[i] else "0" |
---|
1295 | for i in xrange(len(datainfo.mask))]) |
---|
1296 | self.write_node(point, "Mask", mask) |
---|
1297 | |
---|
1298 | def _write_trans_spectrum(self, datainfo, entry_node): |
---|
1299 | """ |
---|
1300 | Writes the transmission spectrum data to the XML file |
---|
1301 | |
---|
1302 | :param datainfo: The Data1D object the information is coming from |
---|
1303 | :param entry_node: lxml node ElementTree object to be appended to |
---|
1304 | """ |
---|
1305 | for i in range(len(datainfo.trans_spectrum)): |
---|
1306 | spectrum = datainfo.trans_spectrum[i] |
---|
1307 | node = self.create_element("SAStransmission_spectrum", |
---|
1308 | {"name" : spectrum.name}) |
---|
1309 | self.append(node, entry_node) |
---|
1310 | if isinstance(spectrum.timestamp, datetime.datetime): |
---|
1311 | node.setAttribute("timestamp", spectrum.timestamp) |
---|
1312 | for i in range(len(spectrum.wavelength)): |
---|
1313 | point = self.create_element("Tdata") |
---|
1314 | node.append(point) |
---|
1315 | self.write_node(point, "Lambda", spectrum.wavelength[i], |
---|
1316 | {'unit': spectrum.wavelength_unit}) |
---|
1317 | self.write_node(point, "T", spectrum.transmission[i], |
---|
1318 | {'unit': spectrum.transmission_unit}) |
---|
1319 | if spectrum.transmission_deviation != None \ |
---|
1320 | and len(spectrum.transmission_deviation) >= i: |
---|
1321 | self.write_node(point, "Tdev", |
---|
1322 | spectrum.transmission_deviation[i], |
---|
1323 | {'unit': |
---|
1324 | spectrum.transmission_deviation_unit}) |
---|
1325 | |
---|
1326 | def _write_sample_info(self, datainfo, entry_node): |
---|
1327 | """ |
---|
1328 | Writes the sample information to the XML file |
---|
1329 | |
---|
1330 | :param datainfo: The Data1D object the information is coming from |
---|
1331 | :param entry_node: lxml node ElementTree object to be appended to |
---|
1332 | """ |
---|
1333 | sample = self.create_element("SASsample") |
---|
1334 | if datainfo.sample.name is not None: |
---|
1335 | self.write_attribute(sample, "name", |
---|
1336 | str(datainfo.sample.name)) |
---|
1337 | self.append(sample, entry_node) |
---|
1338 | self.write_node(sample, "ID", str(datainfo.sample.ID)) |
---|
1339 | self.write_node(sample, "thickness", datainfo.sample.thickness, |
---|
1340 | {"unit": datainfo.sample.thickness_unit}) |
---|
1341 | self.write_node(sample, "transmission", datainfo.sample.transmission) |
---|
1342 | self.write_node(sample, "temperature", datainfo.sample.temperature, |
---|
1343 | {"unit": datainfo.sample.temperature_unit}) |
---|
1344 | |
---|
1345 | pos = self.create_element("position") |
---|
1346 | written = self.write_node(pos, |
---|
1347 | "x", |
---|
1348 | datainfo.sample.position.x, |
---|
1349 | {"unit": datainfo.sample.position_unit}) |
---|
1350 | written = written | self.write_node( \ |
---|
1351 | pos, "y", datainfo.sample.position.y, |
---|
1352 | {"unit": datainfo.sample.position_unit}) |
---|
1353 | written = written | self.write_node( \ |
---|
1354 | pos, "z", datainfo.sample.position.z, |
---|
1355 | {"unit": datainfo.sample.position_unit}) |
---|
1356 | if written == True: |
---|
1357 | self.append(pos, sample) |
---|
1358 | |
---|
1359 | ori = self.create_element("orientation") |
---|
1360 | written = self.write_node(ori, "roll", |
---|
1361 | datainfo.sample.orientation.x, |
---|
1362 | {"unit": datainfo.sample.orientation_unit}) |
---|
1363 | written = written | self.write_node( \ |
---|
1364 | ori, "pitch", datainfo.sample.orientation.y, |
---|
1365 | {"unit": datainfo.sample.orientation_unit}) |
---|
1366 | written = written | self.write_node( \ |
---|
1367 | ori, "yaw", datainfo.sample.orientation.z, |
---|
1368 | {"unit": datainfo.sample.orientation_unit}) |
---|
1369 | if written == True: |
---|
1370 | self.append(ori, sample) |
---|
1371 | |
---|
1372 | for item in datainfo.sample.details: |
---|
1373 | self.write_node(sample, "details", item) |
---|
1374 | |
---|
1375 | def _write_instrument(self, datainfo, entry_node): |
---|
1376 | """ |
---|
1377 | Writes the instrumental information to the XML file |
---|
1378 | |
---|
1379 | :param datainfo: The Data1D object the information is coming from |
---|
1380 | :param entry_node: lxml node ElementTree object to be appended to |
---|
1381 | """ |
---|
1382 | instr = self.create_element("SASinstrument") |
---|
1383 | self.append(instr, entry_node) |
---|
1384 | self.write_node(instr, "name", datainfo.instrument) |
---|
1385 | return instr |
---|
1386 | |
---|
1387 | def _write_source(self, datainfo, instr): |
---|
1388 | """ |
---|
1389 | Writes the source information to the XML file |
---|
1390 | |
---|
1391 | :param datainfo: The Data1D object the information is coming from |
---|
1392 | :param instr: instrument node to be appended to |
---|
1393 | """ |
---|
1394 | source = self.create_element("SASsource") |
---|
1395 | if datainfo.source.name is not None: |
---|
1396 | self.write_attribute(source, "name", |
---|
1397 | str(datainfo.source.name)) |
---|
1398 | self.append(source, instr) |
---|
1399 | if datainfo.source.radiation == None or datainfo.source.radiation == '': |
---|
1400 | datainfo.source.radiation = "neutron" |
---|
1401 | self.write_node(source, "radiation", datainfo.source.radiation) |
---|
1402 | |
---|
1403 | size = self.create_element("beam_size") |
---|
1404 | if datainfo.source.beam_size_name is not None: |
---|
1405 | self.write_attribute(size, "name", |
---|
1406 | str(datainfo.source.beam_size_name)) |
---|
1407 | written = self.write_node( \ |
---|
1408 | size, "x", datainfo.source.beam_size.x, |
---|
1409 | {"unit": datainfo.source.beam_size_unit}) |
---|
1410 | written = written | self.write_node( \ |
---|
1411 | size, "y", datainfo.source.beam_size.y, |
---|
1412 | {"unit": datainfo.source.beam_size_unit}) |
---|
1413 | written = written | self.write_node( \ |
---|
1414 | size, "z", datainfo.source.beam_size.z, |
---|
1415 | {"unit": datainfo.source.beam_size_unit}) |
---|
1416 | if written == True: |
---|
1417 | self.append(size, source) |
---|
1418 | |
---|
1419 | self.write_node(source, "beam_shape", datainfo.source.beam_shape) |
---|
1420 | self.write_node(source, "wavelength", |
---|
1421 | datainfo.source.wavelength, |
---|
1422 | {"unit": datainfo.source.wavelength_unit}) |
---|
1423 | self.write_node(source, "wavelength_min", |
---|
1424 | datainfo.source.wavelength_min, |
---|
1425 | {"unit": datainfo.source.wavelength_min_unit}) |
---|
1426 | self.write_node(source, "wavelength_max", |
---|
1427 | datainfo.source.wavelength_max, |
---|
1428 | {"unit": datainfo.source.wavelength_max_unit}) |
---|
1429 | self.write_node(source, "wavelength_spread", |
---|
1430 | datainfo.source.wavelength_spread, |
---|
1431 | {"unit": datainfo.source.wavelength_spread_unit}) |
---|
1432 | |
---|
1433 | def _write_collimation(self, datainfo, instr): |
---|
1434 | """ |
---|
1435 | Writes the collimation information to the XML file |
---|
1436 | |
---|
1437 | :param datainfo: The Data1D object the information is coming from |
---|
1438 | :param instr: lxml node ElementTree object to be appended to |
---|
1439 | """ |
---|
1440 | if datainfo.collimation == [] or datainfo.collimation == None: |
---|
1441 | coll = Collimation() |
---|
1442 | datainfo.collimation.append(coll) |
---|
1443 | for item in datainfo.collimation: |
---|
1444 | coll = self.create_element("SAScollimation") |
---|
1445 | if item.name is not None: |
---|
1446 | self.write_attribute(coll, "name", str(item.name)) |
---|
1447 | self.append(coll, instr) |
---|
1448 | |
---|
1449 | self.write_node(coll, "length", item.length, |
---|
1450 | {"unit": item.length_unit}) |
---|
1451 | |
---|
1452 | for aperture in item.aperture: |
---|
1453 | apert = self.create_element("aperture") |
---|
1454 | if aperture.name is not None: |
---|
1455 | self.write_attribute(apert, "name", str(aperture.name)) |
---|
1456 | if aperture.type is not None: |
---|
1457 | self.write_attribute(apert, "type", str(aperture.type)) |
---|
1458 | self.append(apert, coll) |
---|
1459 | |
---|
1460 | size = self.create_element("size") |
---|
1461 | if aperture.size_name is not None: |
---|
1462 | self.write_attribute(size, "name", |
---|
1463 | str(aperture.size_name)) |
---|
1464 | written = self.write_node(size, "x", aperture.size.x, |
---|
1465 | {"unit": aperture.size_unit}) |
---|
1466 | written = written | self.write_node( \ |
---|
1467 | size, "y", aperture.size.y, |
---|
1468 | {"unit": aperture.size_unit}) |
---|
1469 | written = written | self.write_node( \ |
---|
1470 | size, "z", aperture.size.z, |
---|
1471 | {"unit": aperture.size_unit}) |
---|
1472 | if written == True: |
---|
1473 | self.append(size, apert) |
---|
1474 | |
---|
1475 | self.write_node(apert, "distance", aperture.distance, |
---|
1476 | {"unit": aperture.distance_unit}) |
---|
1477 | |
---|
1478 | def _write_detectors(self, datainfo, instr): |
---|
1479 | """ |
---|
1480 | Writes the detector information to the XML file |
---|
1481 | |
---|
1482 | :param datainfo: The Data1D object the information is coming from |
---|
1483 | :param inst: lxml instrument node to be appended to |
---|
1484 | """ |
---|
1485 | if datainfo.detector == None or datainfo.detector == []: |
---|
1486 | det = Detector() |
---|
1487 | det.name = "" |
---|
1488 | datainfo.detector.append(det) |
---|
1489 | |
---|
1490 | for item in datainfo.detector: |
---|
1491 | det = self.create_element("SASdetector") |
---|
1492 | written = self.write_node(det, "name", item.name) |
---|
1493 | written = written | self.write_node(det, "SDD", item.distance, |
---|
1494 | {"unit": item.distance_unit}) |
---|
1495 | if written == True: |
---|
1496 | self.append(det, instr) |
---|
1497 | |
---|
1498 | off = self.create_element("offset") |
---|
1499 | written = self.write_node(off, "x", item.offset.x, |
---|
1500 | {"unit": item.offset_unit}) |
---|
1501 | written = written | self.write_node(off, "y", item.offset.y, |
---|
1502 | {"unit": item.offset_unit}) |
---|
1503 | written = written | self.write_node(off, "z", item.offset.z, |
---|
1504 | {"unit": item.offset_unit}) |
---|
1505 | if written == True: |
---|
1506 | self.append(off, det) |
---|
1507 | |
---|
1508 | ori = self.create_element("orientation") |
---|
1509 | written = self.write_node(ori, "roll", item.orientation.x, |
---|
1510 | {"unit": item.orientation_unit}) |
---|
1511 | written = written | self.write_node(ori, "pitch", |
---|
1512 | item.orientation.y, |
---|
1513 | {"unit": item.orientation_unit}) |
---|
1514 | written = written | self.write_node(ori, "yaw", |
---|
1515 | item.orientation.z, |
---|
1516 | {"unit": item.orientation_unit}) |
---|
1517 | if written == True: |
---|
1518 | self.append(ori, det) |
---|
1519 | |
---|
1520 | center = self.create_element("beam_center") |
---|
1521 | written = self.write_node(center, "x", item.beam_center.x, |
---|
1522 | {"unit": item.beam_center_unit}) |
---|
1523 | written = written | self.write_node(center, "y", |
---|
1524 | item.beam_center.y, |
---|
1525 | {"unit": item.beam_center_unit}) |
---|
1526 | written = written | self.write_node(center, "z", |
---|
1527 | item.beam_center.z, |
---|
1528 | {"unit": item.beam_center_unit}) |
---|
1529 | if written == True: |
---|
1530 | self.append(center, det) |
---|
1531 | |
---|
1532 | pix = self.create_element("pixel_size") |
---|
1533 | written = self.write_node(pix, "x", item.pixel_size.x, |
---|
1534 | {"unit": item.pixel_size_unit}) |
---|
1535 | written = written | self.write_node(pix, "y", item.pixel_size.y, |
---|
1536 | {"unit": item.pixel_size_unit}) |
---|
1537 | written = written | self.write_node(pix, "z", item.pixel_size.z, |
---|
1538 | {"unit": item.pixel_size_unit}) |
---|
1539 | if written == True: |
---|
1540 | self.append(pix, det) |
---|
1541 | self.write_node(det, "slit_length", item.slit_length, |
---|
1542 | {"unit": item.slit_length_unit}) |
---|
1543 | |
---|
1544 | def _write_process_notes(self, datainfo, entry_node): |
---|
1545 | """ |
---|
1546 | Writes the process notes to the XML file |
---|
1547 | |
---|
1548 | :param datainfo: The Data1D object the information is coming from |
---|
1549 | :param entry_node: lxml node ElementTree object to be appended to |
---|
1550 | |
---|
1551 | """ |
---|
1552 | for item in datainfo.process: |
---|
1553 | node = self.create_element("SASprocess") |
---|
1554 | self.append(node, entry_node) |
---|
1555 | self.write_node(node, "name", item.name) |
---|
1556 | self.write_node(node, "date", item.date) |
---|
1557 | self.write_node(node, "description", item.description) |
---|
1558 | for term in item.term: |
---|
1559 | if isinstance(term, list): |
---|
1560 | value = term['value'] |
---|
1561 | del term['value'] |
---|
1562 | elif isinstance(term, dict): |
---|
1563 | value = term.get("value") |
---|
1564 | del term['value'] |
---|
1565 | else: |
---|
1566 | value = term |
---|
1567 | self.write_node(node, "term", value, term) |
---|
1568 | for note in item.notes: |
---|
1569 | self.write_node(node, "SASprocessnote", note) |
---|
1570 | if len(item.notes) == 0: |
---|
1571 | self.write_node(node, "SASprocessnote", "") |
---|
1572 | |
---|
1573 | def _write_notes(self, datainfo, entry_node): |
---|
1574 | """ |
---|
1575 | Writes the notes to the XML file and creates an empty note if none |
---|
1576 | exist |
---|
1577 | |
---|
1578 | :param datainfo: The Data1D object the information is coming from |
---|
1579 | :param entry_node: lxml node ElementTree object to be appended to |
---|
1580 | |
---|
1581 | """ |
---|
1582 | if len(datainfo.notes) == 0: |
---|
1583 | node = self.create_element("SASnote") |
---|
1584 | self.append(node, entry_node) |
---|
1585 | else: |
---|
1586 | for item in datainfo.notes: |
---|
1587 | node = self.create_element("SASnote") |
---|
1588 | self.write_text(node, item) |
---|
1589 | self.append(node, entry_node) |
---|
1590 | |
---|
1591 | def _check_root(self): |
---|
1592 | """ |
---|
1593 | Return the document, and the SASentry node associated with |
---|
1594 | the data we just wrote. |
---|
1595 | If the calling function was not the cansas reader, return a minidom |
---|
1596 | object rather than an lxml object. |
---|
1597 | |
---|
1598 | :param entry_node: lxml node ElementTree object to be appended to |
---|
1599 | :param doc: entire xml tree |
---|
1600 | """ |
---|
1601 | if not self.frm: |
---|
1602 | self.frm = inspect.stack()[2] |
---|
1603 | mod_name = self.frm[1].replace("\\", "/").replace(".pyc", "") |
---|
1604 | mod_name = mod_name.replace(".py", "") |
---|
1605 | mod = mod_name.split("sas/") |
---|
1606 | mod_name = mod[1] |
---|
1607 | return mod_name == "sascalc/dataloader/readers/cansas_reader" |
---|
1608 | |
---|
1609 | def _check_origin(self, entry_node, doc): |
---|
1610 | """ |
---|
1611 | Return the document, and the SASentry node associated with |
---|
1612 | the data we just wrote. |
---|
1613 | If the calling function was not the cansas reader, return a minidom |
---|
1614 | object rather than an lxml object. |
---|
1615 | |
---|
1616 | :param entry_node: lxml node ElementTree object to be appended to |
---|
1617 | :param doc: entire xml tree |
---|
1618 | """ |
---|
1619 | if not self._check_root(): |
---|
1620 | string = self.to_string(doc, pretty_print=False) |
---|
1621 | doc = parseString(string) |
---|
1622 | node_name = entry_node.tag |
---|
1623 | node_list = doc.getElementsByTagName(node_name) |
---|
1624 | entry_node = node_list.item(0) |
---|
1625 | return doc, entry_node |
---|
1626 | |
---|
1627 | # DO NOT REMOVE - used in saving and loading panel states. |
---|
1628 | def _store_float(self, location, node, variable, storage, optional=True): |
---|
1629 | """ |
---|
1630 | Get the content of a xpath location and store |
---|
1631 | the result. Check that the units are compatible |
---|
1632 | with the destination. The value is expected to |
---|
1633 | be a float. |
---|
1634 | |
---|
1635 | The xpath location might or might not exist. |
---|
1636 | If it does not exist, nothing is done |
---|
1637 | |
---|
1638 | :param location: xpath location to fetch |
---|
1639 | :param node: node to read the data from |
---|
1640 | :param variable: name of the data member to store it in [string] |
---|
1641 | :param storage: data object that has the 'variable' data member |
---|
1642 | :param optional: if True, no exception will be raised |
---|
1643 | if unit conversion can't be done |
---|
1644 | |
---|
1645 | :raise ValueError: raised when the units are not recognized |
---|
1646 | """ |
---|
1647 | entry = get_content(location, node) |
---|
1648 | try: |
---|
1649 | value = float(entry.text) |
---|
1650 | except: |
---|
1651 | value = None |
---|
1652 | |
---|
1653 | if value is not None: |
---|
1654 | # If the entry has units, check to see that they are |
---|
1655 | # compatible with what we currently have in the data object |
---|
1656 | units = entry.get('unit') |
---|
1657 | if units is not None: |
---|
1658 | toks = variable.split('.') |
---|
1659 | local_unit = None |
---|
1660 | exec "local_unit = storage.%s_unit" % toks[0] |
---|
1661 | if local_unit != None and units.lower() != local_unit.lower(): |
---|
1662 | if HAS_CONVERTER == True: |
---|
1663 | try: |
---|
1664 | conv = Converter(units) |
---|
1665 | exec "storage.%s = %g" % \ |
---|
1666 | (variable, conv(value, units=local_unit)) |
---|
1667 | except: |
---|
1668 | _, exc_value, _ = sys.exc_info() |
---|
1669 | err_mess = "CanSAS reader: could not convert" |
---|
1670 | err_mess += " %s unit [%s]; expecting [%s]\n %s" \ |
---|
1671 | % (variable, units, local_unit, exc_value) |
---|
1672 | self.errors.add(err_mess) |
---|
1673 | if optional: |
---|
1674 | logging.info(err_mess) |
---|
1675 | else: |
---|
1676 | raise ValueError, err_mess |
---|
1677 | else: |
---|
1678 | err_mess = "CanSAS reader: unrecognized %s unit [%s];"\ |
---|
1679 | % (variable, units) |
---|
1680 | err_mess += " expecting [%s]" % local_unit |
---|
1681 | self.errors.add(err_mess) |
---|
1682 | if optional: |
---|
1683 | logging.info(err_mess) |
---|
1684 | else: |
---|
1685 | raise ValueError, err_mess |
---|
1686 | else: |
---|
1687 | exec "storage.%s = value" % variable |
---|
1688 | else: |
---|
1689 | exec "storage.%s = value" % variable |
---|
1690 | |
---|
1691 | # DO NOT REMOVE - used in saving and loading panel states. |
---|
1692 | def _store_content(self, location, node, variable, storage): |
---|
1693 | """ |
---|
1694 | Get the content of a xpath location and store |
---|
1695 | the result. The value is treated as a string. |
---|
1696 | |
---|
1697 | The xpath location might or might not exist. |
---|
1698 | If it does not exist, nothing is done |
---|
1699 | |
---|
1700 | :param location: xpath location to fetch |
---|
1701 | :param node: node to read the data from |
---|
1702 | :param variable: name of the data member to store it in [string] |
---|
1703 | :param storage: data object that has the 'variable' data member |
---|
1704 | |
---|
1705 | :return: return a list of errors |
---|
1706 | """ |
---|
1707 | entry = get_content(location, node) |
---|
1708 | if entry is not None and entry.text is not None: |
---|
1709 | exec "storage.%s = entry.text.strip()" % variable |
---|
1710 | |
---|
1711 | |
---|
1712 | # DO NOT REMOVE Called by outside packages: |
---|
1713 | # sas.sasgui.perspectives.invariant.invariant_state |
---|
1714 | # sas.sasgui.perspectives.fitting.pagestate |
---|
1715 | def get_content(location, node): |
---|
1716 | """ |
---|
1717 | Get the first instance of the content of a xpath location. |
---|
1718 | |
---|
1719 | :param location: xpath location |
---|
1720 | :param node: node to start at |
---|
1721 | |
---|
1722 | :return: Element, or None |
---|
1723 | """ |
---|
1724 | nodes = node.xpath(location, |
---|
1725 | namespaces={'ns': CANSAS_NS.get("1.0").get("ns")}) |
---|
1726 | if len(nodes) > 0: |
---|
1727 | return nodes[0] |
---|
1728 | else: |
---|
1729 | return None |
---|
1730 | |
---|
1731 | # DO NOT REMOVE Called by outside packages: |
---|
1732 | # sas.sasgui.perspectives.fitting.pagestate |
---|
1733 | def write_node(doc, parent, name, value, attr=None): |
---|
1734 | """ |
---|
1735 | :param doc: document DOM |
---|
1736 | :param parent: parent node |
---|
1737 | :param name: tag of the element |
---|
1738 | :param value: value of the child text node |
---|
1739 | :param attr: attribute dictionary |
---|
1740 | |
---|
1741 | :return: True if something was appended, otherwise False |
---|
1742 | """ |
---|
1743 | if attr is None: |
---|
1744 | attr = {} |
---|
1745 | if value is not None: |
---|
1746 | node = doc.createElement(name) |
---|
1747 | node.appendChild(doc.createTextNode(str(value))) |
---|
1748 | for item in attr: |
---|
1749 | node.setAttribute(item, attr[item]) |
---|
1750 | parent.appendChild(node) |
---|
1751 | return True |
---|
1752 | return False |
---|