1 | |
---|
2 | |
---|
3 | ############################################################################ |
---|
4 | #This software was developed by the University of Tennessee as part of the |
---|
5 | #Distributed Data Analysis of Neutron Scattering Experiments (DANSE) |
---|
6 | #project funded by the US National Science Foundation. |
---|
7 | #If you use DANSE applications to do scientific research that leads to |
---|
8 | #publication, we ask that you acknowledge the use of the software with the |
---|
9 | #following sentence: |
---|
10 | #This work benefited from DANSE software developed under NSF award DMR-0520547. |
---|
11 | #copyright 2008,2009 University of Tennessee |
---|
12 | ############################################################################# |
---|
13 | |
---|
14 | # Known issue: reader not compatible with multiple SASdata entries |
---|
15 | # within a single SASentry. Will raise a runtime error. |
---|
16 | |
---|
17 | #TODO: check that all vectors are written only if they have at |
---|
18 | # least one non-empty value |
---|
19 | #TODO: Writing only allows one SASentry per file. |
---|
20 | # Would be best to allow multiple entries. |
---|
21 | #TODO: Store error list |
---|
22 | #TODO: Allow for additional meta data for each section |
---|
23 | #TODO: Notes need to be implemented. They can be any XML |
---|
24 | # structure in version 1.0 |
---|
25 | # Process notes have the same problem. |
---|
26 | #TODO: Unit conversion is not complete (temperature units are missing) |
---|
27 | |
---|
28 | |
---|
29 | import logging |
---|
30 | import numpy |
---|
31 | import os |
---|
32 | import sys |
---|
33 | from DataLoader.data_info import Data1D |
---|
34 | from DataLoader.data_info import Collimation |
---|
35 | from DataLoader.data_info import Detector |
---|
36 | from DataLoader.data_info import Process |
---|
37 | from DataLoader.data_info import Aperture |
---|
38 | from lxml import etree |
---|
39 | import xml.dom.minidom |
---|
40 | |
---|
41 | has_converter = True |
---|
42 | try: |
---|
43 | from data_util.nxsunit import Converter |
---|
44 | except: |
---|
45 | has_converter = False |
---|
46 | |
---|
47 | CANSAS_NS = "cansas1d/1.0" |
---|
48 | |
---|
49 | def write_node(doc, parent, name, value, attr={}): |
---|
50 | """ |
---|
51 | :param doc: document DOM |
---|
52 | :param parent: parent node |
---|
53 | :param name: tag of the element |
---|
54 | :param value: value of the child text node |
---|
55 | :param attr: attribute dictionary |
---|
56 | |
---|
57 | :return: True if something was appended, otherwise False |
---|
58 | """ |
---|
59 | if value is not None: |
---|
60 | node = doc.createElement(name) |
---|
61 | node.appendChild(doc.createTextNode(str(value))) |
---|
62 | for item in attr: |
---|
63 | node.setAttribute(item, attr[item]) |
---|
64 | parent.appendChild(node) |
---|
65 | return True |
---|
66 | return False |
---|
67 | |
---|
68 | def get_content(location, node): |
---|
69 | """ |
---|
70 | Get the first instance of the content of a xpath location. |
---|
71 | |
---|
72 | :param location: xpath location |
---|
73 | :param node: node to start at |
---|
74 | |
---|
75 | :return: Element, or None |
---|
76 | """ |
---|
77 | nodes = node.xpath(location, namespaces={'ns': CANSAS_NS}) |
---|
78 | |
---|
79 | if len(nodes)>0: |
---|
80 | return nodes[0] |
---|
81 | else: |
---|
82 | return None |
---|
83 | |
---|
84 | def get_float(location, node): |
---|
85 | """ |
---|
86 | Get the content of a node as a float |
---|
87 | |
---|
88 | :param location: xpath location |
---|
89 | :param node: node to start at |
---|
90 | """ |
---|
91 | nodes = node.xpath(location, namespaces={'ns': CANSAS_NS}) |
---|
92 | |
---|
93 | value = None |
---|
94 | attr = {} |
---|
95 | if len(nodes) > 0: |
---|
96 | try: |
---|
97 | value = float(nodes[0].text) |
---|
98 | except: |
---|
99 | # Could not pass, skip and return None |
---|
100 | msg = "cansas_reader.get_float: could not " |
---|
101 | msg += " convert '%s' to float" % nodes[0].text |
---|
102 | logging.error(msg) |
---|
103 | if nodes[0].get('unit') is not None: |
---|
104 | attr['unit'] = nodes[0].get('unit') |
---|
105 | return value, attr |
---|
106 | |
---|
107 | |
---|
108 | class Reader: |
---|
109 | """ |
---|
110 | Class to load cansas 1D XML files |
---|
111 | |
---|
112 | :Dependencies: |
---|
113 | The CanSas reader requires PyXML 0.8.4 or later. |
---|
114 | """ |
---|
115 | ## CanSAS version |
---|
116 | version = '1.0' |
---|
117 | ## File type |
---|
118 | type_name = "CanSAS 1D" |
---|
119 | ## Wildcards |
---|
120 | type = ["CanSAS 1D files (*.xml)|*.xml", |
---|
121 | "CanSAS 1D AVE files (*.AVEx)|*.AVEx", |
---|
122 | "CanSAS 1D AVE files (*.ABSx)|*.ABSx"] |
---|
123 | |
---|
124 | ## List of allowed extensions |
---|
125 | ext = ['.xml', '.XML','.avex', '.AVEx', '.absx', 'ABSx'] |
---|
126 | |
---|
127 | def __init__(self): |
---|
128 | ## List of errors |
---|
129 | self.errors = [] |
---|
130 | |
---|
131 | def read(self, path): |
---|
132 | """ |
---|
133 | Load data file |
---|
134 | |
---|
135 | :param path: file path |
---|
136 | |
---|
137 | :return: Data1D object if a single SASentry was found, |
---|
138 | or a list of Data1D objects if multiple entries were found, |
---|
139 | or None of nothing was found |
---|
140 | |
---|
141 | :raise RuntimeError: when the file can't be opened |
---|
142 | :raise ValueError: when the length of the data vectors are inconsistent |
---|
143 | """ |
---|
144 | output = [] |
---|
145 | if os.path.isfile(path): |
---|
146 | basename = os.path.basename(path) |
---|
147 | root, extension = os.path.splitext(basename) |
---|
148 | if extension.lower() in self.ext: |
---|
149 | |
---|
150 | tree = etree.parse(path, parser=etree.ETCompatXMLParser()) |
---|
151 | # Check the format version number |
---|
152 | # Specifying the namespace will take care of the file |
---|
153 | # format version |
---|
154 | root = tree.getroot() |
---|
155 | |
---|
156 | entry_list = root.xpath('/ns:SASroot/ns:SASentry', |
---|
157 | namespaces={'ns': CANSAS_NS}) |
---|
158 | |
---|
159 | for entry in entry_list: |
---|
160 | self.errors = [] |
---|
161 | sas_entry = self._parse_entry(entry) |
---|
162 | sas_entry.filename = basename |
---|
163 | |
---|
164 | # Store loading process information |
---|
165 | sas_entry.errors = self.errors |
---|
166 | sas_entry.meta_data['loader'] = self.type_name |
---|
167 | output.append(sas_entry) |
---|
168 | |
---|
169 | else: |
---|
170 | raise RuntimeError, "%s is not a file" % path |
---|
171 | # Return output consistent with the loader's api |
---|
172 | if len(output)==0: |
---|
173 | return None |
---|
174 | elif len(output)==1: |
---|
175 | return output[0] |
---|
176 | else: |
---|
177 | return output |
---|
178 | |
---|
179 | def _parse_entry(self, dom): |
---|
180 | """ |
---|
181 | Parse a SASentry |
---|
182 | |
---|
183 | :param node: SASentry node |
---|
184 | |
---|
185 | :return: Data1D object |
---|
186 | """ |
---|
187 | x = numpy.zeros(0) |
---|
188 | y = numpy.zeros(0) |
---|
189 | |
---|
190 | data_info = Data1D(x, y) |
---|
191 | |
---|
192 | # Look up title |
---|
193 | self._store_content('ns:Title', dom, 'title', data_info) |
---|
194 | |
---|
195 | # Look up run number |
---|
196 | nodes = dom.xpath('ns:Run', namespaces={'ns': CANSAS_NS}) |
---|
197 | for item in nodes: |
---|
198 | if item.text is not None: |
---|
199 | value = item.text.strip() |
---|
200 | if len(value) > 0: |
---|
201 | data_info.run.append(value) |
---|
202 | if item.get('name') is not None: |
---|
203 | data_info.run_name[value] = item.get('name') |
---|
204 | |
---|
205 | # Look up instrument name |
---|
206 | self._store_content('ns:SASinstrument/ns:name', dom, 'instrument', |
---|
207 | data_info) |
---|
208 | |
---|
209 | # Notes |
---|
210 | note_list = dom.xpath('ns:SASnote', namespaces={'ns': CANSAS_NS}) |
---|
211 | for note in note_list: |
---|
212 | try: |
---|
213 | if note.text is not None: |
---|
214 | note_value = note.text.strip() |
---|
215 | if len(note_value) > 0: |
---|
216 | data_info.notes.append(note_value) |
---|
217 | except: |
---|
218 | err_mess = "cansas_reader.read: error processing" |
---|
219 | err_mess += " entry notes\n %s" % sys.exc_value |
---|
220 | self.errors.append(err_mess) |
---|
221 | logging.error(err_mess) |
---|
222 | |
---|
223 | # Sample info ################### |
---|
224 | entry = get_content('ns:SASsample', dom) |
---|
225 | if entry is not None: |
---|
226 | data_info.sample.name = entry.get('name') |
---|
227 | |
---|
228 | self._store_content('ns:SASsample/ns:ID', |
---|
229 | dom, 'ID', data_info.sample) |
---|
230 | self._store_float('ns:SASsample/ns:thickness', |
---|
231 | dom, 'thickness', data_info.sample) |
---|
232 | self._store_float('ns:SASsample/ns:transmission', |
---|
233 | dom, 'transmission', data_info.sample) |
---|
234 | self._store_float('ns:SASsample/ns:temperature', |
---|
235 | dom, 'temperature', data_info.sample) |
---|
236 | |
---|
237 | nodes = dom.xpath('ns:SASsample/ns:details', |
---|
238 | namespaces={'ns': CANSAS_NS}) |
---|
239 | for item in nodes: |
---|
240 | try: |
---|
241 | if item.text is not None: |
---|
242 | detail_value = item.text.strip() |
---|
243 | if len(detail_value) > 0: |
---|
244 | data_info.sample.details.append(detail_value) |
---|
245 | except: |
---|
246 | err_mess = "cansas_reader.read: error processing " |
---|
247 | err_mess += " sample details\n %s" % sys.exc_value |
---|
248 | self.errors.append(err_mess) |
---|
249 | logging.error(err_mess) |
---|
250 | |
---|
251 | # Position (as a vector) |
---|
252 | self._store_float('ns:SASsample/ns:position/ns:x', |
---|
253 | dom, 'position.x', data_info.sample) |
---|
254 | self._store_float('ns:SASsample/ns:position/ns:y', |
---|
255 | dom, 'position.y', data_info.sample) |
---|
256 | self._store_float('ns:SASsample/ns:position/ns:z', |
---|
257 | dom, 'position.z', data_info.sample) |
---|
258 | |
---|
259 | # Orientation (as a vector) |
---|
260 | self._store_float('ns:SASsample/ns:orientation/ns:roll', |
---|
261 | dom, 'orientation.x', data_info.sample) |
---|
262 | self._store_float('ns:SASsample/ns:orientation/ns:pitch', |
---|
263 | dom, 'orientation.y', data_info.sample) |
---|
264 | self._store_float('ns:SASsample/ns:orientation/ns:yaw', |
---|
265 | dom, 'orientation.z', data_info.sample) |
---|
266 | |
---|
267 | # Source info ################### |
---|
268 | entry = get_content('ns:SASinstrument/ns:SASsource', dom) |
---|
269 | if entry is not None: |
---|
270 | data_info.source.name = entry.get('name') |
---|
271 | |
---|
272 | self._store_content('ns:SASinstrument/ns:SASsource/ns:radiation', |
---|
273 | dom, 'radiation', data_info.source) |
---|
274 | self._store_content('ns:SASinstrument/ns:SASsource/ns:beam_shape', |
---|
275 | dom, 'beam_shape', data_info.source) |
---|
276 | self._store_float('ns:SASinstrument/ns:SASsource/ns:wavelength', |
---|
277 | dom, 'wavelength', data_info.source) |
---|
278 | self._store_float('ns:SASinstrument/ns:SASsource/ns:wavelength_min', |
---|
279 | dom, 'wavelength_min', data_info.source) |
---|
280 | self._store_float('ns:SASinstrument/ns:SASsource/ns:wavelength_max', |
---|
281 | dom, 'wavelength_max', data_info.source) |
---|
282 | self._store_float('ns:SASinstrument/ns:SASsource/ns:wavelength_spread', |
---|
283 | dom, 'wavelength_spread', data_info.source) |
---|
284 | |
---|
285 | # Beam size (as a vector) |
---|
286 | entry = get_content('ns:SASinstrument/ns:SASsource/ns:beam_size', dom) |
---|
287 | if entry is not None: |
---|
288 | data_info.source.beam_size_name = entry.get('name') |
---|
289 | |
---|
290 | self._store_float('ns:SASinstrument/ns:SASsource/ns:beam_size/ns:x', |
---|
291 | dom, 'beam_size.x', data_info.source) |
---|
292 | self._store_float('ns:SASinstrument/ns:SASsource/ns:beam_size/ns:y', |
---|
293 | dom, 'beam_size.y', data_info.source) |
---|
294 | self._store_float('ns:SASinstrument/ns:SASsource/ns:beam_size/ns:z', |
---|
295 | dom, 'beam_size.z', data_info.source) |
---|
296 | |
---|
297 | # Collimation info ################### |
---|
298 | nodes = dom.xpath('ns:SASinstrument/ns:SAScollimation', |
---|
299 | namespaces={'ns': CANSAS_NS}) |
---|
300 | for item in nodes: |
---|
301 | collim = Collimation() |
---|
302 | if item.get('name') is not None: |
---|
303 | collim.name = item.get('name') |
---|
304 | self._store_float('ns:length', item, 'length', collim) |
---|
305 | |
---|
306 | # Look for apertures |
---|
307 | apert_list = item.xpath('ns:aperture', namespaces={'ns': CANSAS_NS}) |
---|
308 | for apert in apert_list: |
---|
309 | aperture = Aperture() |
---|
310 | |
---|
311 | # Get the name and type of the aperture |
---|
312 | aperture.name = apert.get('name') |
---|
313 | aperture.type = apert.get('type') |
---|
314 | |
---|
315 | self._store_float('ns:distance', apert, 'distance', aperture) |
---|
316 | |
---|
317 | entry = get_content('ns:size', apert) |
---|
318 | if entry is not None: |
---|
319 | aperture.size_name = entry.get('name') |
---|
320 | |
---|
321 | self._store_float('ns:size/ns:x', apert, 'size.x', aperture) |
---|
322 | self._store_float('ns:size/ns:y', apert, 'size.y', aperture) |
---|
323 | self._store_float('ns:size/ns:z', apert, 'size.z', aperture) |
---|
324 | |
---|
325 | collim.aperture.append(aperture) |
---|
326 | |
---|
327 | data_info.collimation.append(collim) |
---|
328 | |
---|
329 | # Detector info ###################### |
---|
330 | nodes = dom.xpath('ns:SASinstrument/ns:SASdetector', |
---|
331 | namespaces={'ns': CANSAS_NS}) |
---|
332 | for item in nodes: |
---|
333 | |
---|
334 | detector = Detector() |
---|
335 | |
---|
336 | self._store_content('ns:name', item, 'name', detector) |
---|
337 | self._store_float('ns:SDD', item, 'distance', detector) |
---|
338 | |
---|
339 | # Detector offset (as a vector) |
---|
340 | self._store_float('ns:offset/ns:x', item, 'offset.x', detector) |
---|
341 | self._store_float('ns:offset/ns:y', item, 'offset.y', detector) |
---|
342 | self._store_float('ns:offset/ns:z', item, 'offset.z', detector) |
---|
343 | |
---|
344 | # Detector orientation (as a vector) |
---|
345 | self._store_float('ns:orientation/ns:roll', item, 'orientation.x', |
---|
346 | detector) |
---|
347 | self._store_float('ns:orientation/ns:pitch', item, 'orientation.y', |
---|
348 | detector) |
---|
349 | self._store_float('ns:orientation/ns:yaw', item, 'orientation.z', |
---|
350 | detector) |
---|
351 | |
---|
352 | # Beam center (as a vector) |
---|
353 | self._store_float('ns:beam_center/ns:x', item, 'beam_center.x', |
---|
354 | detector) |
---|
355 | self._store_float('ns:beam_center/ns:y', item, 'beam_center.y', |
---|
356 | detector) |
---|
357 | self._store_float('ns:beam_center/ns:z', item, 'beam_center.z', |
---|
358 | detector) |
---|
359 | |
---|
360 | # Pixel size (as a vector) |
---|
361 | self._store_float('ns:pixel_size/ns:x', item, 'pixel_size.x', |
---|
362 | detector) |
---|
363 | self._store_float('ns:pixel_size/ns:y', item, 'pixel_size.y', |
---|
364 | detector) |
---|
365 | self._store_float('ns:pixel_size/ns:z', item, 'pixel_size.z', |
---|
366 | detector) |
---|
367 | |
---|
368 | self._store_float('ns:slit_length', item, 'slit_length', detector) |
---|
369 | |
---|
370 | data_info.detector.append(detector) |
---|
371 | |
---|
372 | # Processes info ###################### |
---|
373 | nodes = dom.xpath('ns:SASprocess', namespaces={'ns': CANSAS_NS}) |
---|
374 | for item in nodes: |
---|
375 | process = Process() |
---|
376 | self._store_content('ns:name', item, 'name', process) |
---|
377 | self._store_content('ns:date', item, 'date', process) |
---|
378 | self._store_content('ns:description', item, 'description', process) |
---|
379 | |
---|
380 | term_list = item.xpath('ns:term', namespaces={'ns': CANSAS_NS}) |
---|
381 | for term in term_list: |
---|
382 | try: |
---|
383 | term_attr = {} |
---|
384 | for attr in term.keys(): |
---|
385 | term_attr[attr] = term.get(attr).strip() |
---|
386 | if term.text is not None: |
---|
387 | term_attr['value'] = term.text.strip() |
---|
388 | process.term.append(term_attr) |
---|
389 | except: |
---|
390 | err_mess = "cansas_reader.read: error processing " |
---|
391 | err_mess += " process term\n %s" % sys.exc_value |
---|
392 | self.errors.append(err_mess) |
---|
393 | logging.error(err_mess) |
---|
394 | |
---|
395 | note_list = item.xpath('ns:SASprocessnote', |
---|
396 | namespaces={'ns': CANSAS_NS}) |
---|
397 | for note in note_list: |
---|
398 | if note.text is not None: |
---|
399 | process.notes.append(note.text.strip()) |
---|
400 | |
---|
401 | data_info.process.append(process) |
---|
402 | |
---|
403 | |
---|
404 | # Data info ###################### |
---|
405 | nodes = dom.xpath('ns:SASdata', namespaces={'ns': CANSAS_NS}) |
---|
406 | if len(nodes) > 1: |
---|
407 | msg = "CanSAS reader is not compatible with multiple" |
---|
408 | msg += " SASdata entries" |
---|
409 | raise RuntimeError, msg |
---|
410 | |
---|
411 | nodes = dom.xpath('ns:SASdata/ns:Idata', namespaces={'ns': CANSAS_NS}) |
---|
412 | |
---|
413 | x = numpy.zeros(0) |
---|
414 | y = numpy.zeros(0) |
---|
415 | dx = numpy.zeros(0) |
---|
416 | dy = numpy.zeros(0) |
---|
417 | dxw = numpy.zeros(0) |
---|
418 | dxl = numpy.zeros(0) |
---|
419 | |
---|
420 | for item in nodes: |
---|
421 | _x, attr = get_float('ns:Q', item) |
---|
422 | _dx, attr_d = get_float('ns:Qdev', item) |
---|
423 | _dxl, attr_l = get_float('ns:dQl', item) |
---|
424 | _dxw, attr_w = get_float('ns:dQw', item) |
---|
425 | if _dx == None: |
---|
426 | _dx = 0.0 |
---|
427 | if _dxl == None: |
---|
428 | _dxl = 0.0 |
---|
429 | if _dxw == None: |
---|
430 | _dxw = 0.0 |
---|
431 | |
---|
432 | if attr.has_key('unit') and \ |
---|
433 | attr['unit'].lower() != data_info.x_unit.lower(): |
---|
434 | if has_converter==True: |
---|
435 | try: |
---|
436 | data_conv_q = Converter(attr['unit']) |
---|
437 | _x = data_conv_q(_x, units=data_info.x_unit) |
---|
438 | except: |
---|
439 | msg = "CanSAS reader: could not convert " |
---|
440 | msg += "Q unit [%s]; " |
---|
441 | msg += "expecting [%s]\n %s" % (attr['unit'], |
---|
442 | data_info.x_unit, sys.exc_value) |
---|
443 | raise ValueError, msg |
---|
444 | |
---|
445 | else: |
---|
446 | msg = "CanSAS reader: unrecognized Q unit [%s]; " |
---|
447 | msg += "expecting [%s]" % (attr['unit'], data_info.x_unit) |
---|
448 | raise ValueError, msg |
---|
449 | |
---|
450 | # Error in Q |
---|
451 | if attr_d.has_key('unit') and \ |
---|
452 | attr_d['unit'].lower() != data_info.x_unit.lower(): |
---|
453 | if has_converter==True: |
---|
454 | try: |
---|
455 | data_conv_q = Converter(attr_d['unit']) |
---|
456 | _dx = data_conv_q(_dx, units=data_info.x_unit) |
---|
457 | except: |
---|
458 | msg = "CanSAS reader: could not convert dQ unit [%s];" |
---|
459 | msg += " expecting " |
---|
460 | msg += "[%s]\n %s" % (attr['unit'], |
---|
461 | data_info.x_unit, sys.exc_value) |
---|
462 | raise ValueError, msg |
---|
463 | |
---|
464 | else: |
---|
465 | msg = "CanSAS reader: unrecognized dQ unit [%s]; " |
---|
466 | msg += "expecting [%s]" % (attr['unit'], data_info.x_unit) |
---|
467 | raise ValueError, msg |
---|
468 | |
---|
469 | # Slit length |
---|
470 | if attr_l.has_key('unit') and \ |
---|
471 | attr_l['unit'].lower() != data_info.x_unit.lower(): |
---|
472 | if has_converter == True: |
---|
473 | try: |
---|
474 | data_conv_q = Converter(attr_l['unit']) |
---|
475 | _dxl = data_conv_q(_dxl, units=data_info.x_unit) |
---|
476 | except: |
---|
477 | msg = "CanSAS reader: could not convert dQl unit [%s];" |
---|
478 | msg += " expecting [%s]\n %s" % (attr['unit'], |
---|
479 | data_info.x_unit, sys.exc_value) |
---|
480 | raise ValueError, msg |
---|
481 | |
---|
482 | else: |
---|
483 | msg = "CanSAS reader: unrecognized dQl unit [%s];" |
---|
484 | msg += " expecting [%s]" % (attr['unit'], data_info.x_unit) |
---|
485 | raise ValueError, msg |
---|
486 | |
---|
487 | # Slit width |
---|
488 | if attr_w.has_key('unit') and \ |
---|
489 | attr_w['unit'].lower() != data_info.x_unit.lower(): |
---|
490 | if has_converter == True: |
---|
491 | try: |
---|
492 | data_conv_q = Converter(attr_w['unit']) |
---|
493 | _dxw = data_conv_q(_dxw, units=data_info.x_unit) |
---|
494 | except: |
---|
495 | msg = "CanSAS reader: could not convert dQw unit [%s];" |
---|
496 | msg += " expecting [%s]\n %s" % (attr['unit'], |
---|
497 | data_info.x_unit, sys.exc_value) |
---|
498 | raise ValueError, msg |
---|
499 | |
---|
500 | else: |
---|
501 | msg = "CanSAS reader: unrecognized dQw unit [%s];" |
---|
502 | msg += " expecting [%s]" % (attr['unit'], data_info.x_unit) |
---|
503 | raise ValueError, msg |
---|
504 | _y, attr = get_float('ns:I', item) |
---|
505 | _dy, attr_d = get_float('ns:Idev', item) |
---|
506 | if _dy == None: |
---|
507 | _dy = 0.0 |
---|
508 | if attr.has_key('unit') and \ |
---|
509 | attr['unit'].lower() != data_info.y_unit.lower(): |
---|
510 | if has_converter==True: |
---|
511 | try: |
---|
512 | data_conv_i = Converter(attr['unit']) |
---|
513 | _y = data_conv_i(_y, units=data_info.y_unit) |
---|
514 | except: |
---|
515 | msg = "CanSAS reader: could not convert I(q) unit [%s];" |
---|
516 | msg += " expecting [%s]\n %s" % (attr['unit'], |
---|
517 | data_info.y_unit, sys.exc_value) |
---|
518 | raise ValueError, msg |
---|
519 | else: |
---|
520 | msg = "CanSAS reader: unrecognized I(q) unit [%s];" |
---|
521 | msg += " expecting [%s]" % (attr['unit'], data_info.y_unit) |
---|
522 | raise ValueError, msg |
---|
523 | |
---|
524 | if attr_d.has_key('unit') and \ |
---|
525 | attr_d['unit'].lower() != data_info.y_unit.lower(): |
---|
526 | if has_converter==True: |
---|
527 | try: |
---|
528 | data_conv_i = Converter(attr_d['unit']) |
---|
529 | _dy = data_conv_i(_dy, units=data_info.y_unit) |
---|
530 | except: |
---|
531 | msg = "CanSAS reader: could not convert dI(q) unit " |
---|
532 | msg += "[%s]; expecting [%s]\n %s" % (attr_d['unit'], |
---|
533 | data_info.y_unit, sys.exc_value) |
---|
534 | raise ValueError, msg |
---|
535 | else: |
---|
536 | msg = "CanSAS reader: unrecognized dI(q) unit [%s]; " |
---|
537 | msg += "expecting [%s]" % (attr_d['unit'], data_info.y_unit) |
---|
538 | raise ValueError, msg |
---|
539 | |
---|
540 | if _x is not None and _y is not None: |
---|
541 | x = numpy.append(x, _x) |
---|
542 | y = numpy.append(y, _y) |
---|
543 | dx = numpy.append(dx, _dx) |
---|
544 | dy = numpy.append(dy, _dy) |
---|
545 | dxl = numpy.append(dxl, _dxl) |
---|
546 | dxw = numpy.append(dxw, _dxw) |
---|
547 | |
---|
548 | data_info.x = x |
---|
549 | data_info.y = y |
---|
550 | data_info.dx = dx |
---|
551 | data_info.dy = dy |
---|
552 | data_info.dxl = dxl |
---|
553 | data_info.dxw = dxw |
---|
554 | |
---|
555 | data_conv_q = None |
---|
556 | data_conv_i = None |
---|
557 | |
---|
558 | if has_converter == True and data_info.x_unit != '1/A': |
---|
559 | data_conv_q = Converter('1/A') |
---|
560 | # Test it |
---|
561 | data_conv_q(1.0, output.Q_unit) |
---|
562 | |
---|
563 | if has_converter == True and data_info.y_unit != '1/cm': |
---|
564 | data_conv_i = Converter('1/cm') |
---|
565 | # Test it |
---|
566 | data_conv_i(1.0, output.I_unit) |
---|
567 | |
---|
568 | if data_conv_q is not None: |
---|
569 | data_info.xaxis("\\rm{Q}", data_info.x_unit) |
---|
570 | else: |
---|
571 | data_info.xaxis("\\rm{Q}", 'A^{-1}') |
---|
572 | if data_conv_i is not None: |
---|
573 | data_info.yaxis("\\rm{Intensity}", data_info.y_unit) |
---|
574 | else: |
---|
575 | data_info.yaxis("\\rm{Intensity}","cm^{-1}") |
---|
576 | |
---|
577 | return data_info |
---|
578 | |
---|
579 | def _to_xml_doc(self, datainfo): |
---|
580 | """ |
---|
581 | Create an XML document to contain the content of a Data1D |
---|
582 | |
---|
583 | :param datainfo: Data1D object |
---|
584 | """ |
---|
585 | |
---|
586 | if not issubclass(datainfo.__class__, Data1D): |
---|
587 | raise RuntimeError, "The cansas writer expects a Data1D instance" |
---|
588 | |
---|
589 | doc = xml.dom.minidom.Document() |
---|
590 | main_node = doc.createElement("SASroot") |
---|
591 | main_node.setAttribute("version", self.version) |
---|
592 | main_node.setAttribute("xmlns", "cansas1d/%s" % self.version) |
---|
593 | main_node.setAttribute("xmlns:xsi", |
---|
594 | "http://www.w3.org/2001/XMLSchema-instance") |
---|
595 | main_node.setAttribute("xsi:schemaLocation", |
---|
596 | "cansas1d/%s http://svn.smallangles.net/svn/canSAS/1dwg/trunk/cansas1d.xsd" % self.version) |
---|
597 | |
---|
598 | doc.appendChild(main_node) |
---|
599 | |
---|
600 | entry_node = doc.createElement("SASentry") |
---|
601 | main_node.appendChild(entry_node) |
---|
602 | |
---|
603 | write_node(doc, entry_node, "Title", datainfo.title) |
---|
604 | for item in datainfo.run: |
---|
605 | runname = {} |
---|
606 | if datainfo.run_name.has_key(item) and \ |
---|
607 | len(str(datainfo.run_name[item]))>1: |
---|
608 | runname = {'name': datainfo.run_name[item] } |
---|
609 | write_node(doc, entry_node, "Run", item, runname) |
---|
610 | |
---|
611 | # Data info |
---|
612 | node = doc.createElement("SASdata") |
---|
613 | entry_node.appendChild(node) |
---|
614 | |
---|
615 | for i in range(len(datainfo.x)): |
---|
616 | pt = doc.createElement("Idata") |
---|
617 | node.appendChild(pt) |
---|
618 | write_node(doc, pt, "Q", datainfo.x[i], {'unit':datainfo.x_unit}) |
---|
619 | if len(datainfo.y)>=i: |
---|
620 | write_node(doc, pt, "I", datainfo.y[i], |
---|
621 | {'unit':datainfo.y_unit}) |
---|
622 | if datainfo.dx !=None and len(datainfo.dx)>=i: |
---|
623 | write_node(doc, pt, "Qdev", datainfo.dx[i], |
---|
624 | {'unit':datainfo.x_unit}) |
---|
625 | if datainfo.dy !=None and len(datainfo.dy)>=i: |
---|
626 | write_node(doc, pt, "Idev", datainfo.dy[i], |
---|
627 | {'unit':datainfo.y_unit}) |
---|
628 | |
---|
629 | |
---|
630 | # Sample info |
---|
631 | sample = doc.createElement("SASsample") |
---|
632 | if datainfo.sample.name is not None: |
---|
633 | sample.setAttribute("name", str(datainfo.sample.name)) |
---|
634 | entry_node.appendChild(sample) |
---|
635 | write_node(doc, sample, "ID", str(datainfo.sample.ID)) |
---|
636 | write_node(doc, sample, "thickness", datainfo.sample.thickness, |
---|
637 | {"unit":datainfo.sample.thickness_unit}) |
---|
638 | write_node(doc, sample, "transmission", datainfo.sample.transmission) |
---|
639 | write_node(doc, sample, "temperature", datainfo.sample.temperature, |
---|
640 | {"unit":datainfo.sample.temperature_unit}) |
---|
641 | |
---|
642 | for item in datainfo.sample.details: |
---|
643 | write_node(doc, sample, "details", item) |
---|
644 | |
---|
645 | pos = doc.createElement("position") |
---|
646 | written = write_node(doc, pos, "x", datainfo.sample.position.x, |
---|
647 | {"unit":datainfo.sample.position_unit}) |
---|
648 | written = written | write_node(doc, pos, "y", |
---|
649 | datainfo.sample.position.y, |
---|
650 | {"unit":datainfo.sample.position_unit}) |
---|
651 | written = written | write_node(doc, pos, "z", |
---|
652 | datainfo.sample.position.z, |
---|
653 | {"unit":datainfo.sample.position_unit}) |
---|
654 | if written == True: |
---|
655 | sample.appendChild(pos) |
---|
656 | |
---|
657 | ori = doc.createElement("orientation") |
---|
658 | written = write_node(doc, ori, "roll", |
---|
659 | datainfo.sample.orientation.x, |
---|
660 | {"unit":datainfo.sample.orientation_unit}) |
---|
661 | written = written | write_node(doc, ori, "pitch", |
---|
662 | datainfo.sample.orientation.y, |
---|
663 | {"unit":datainfo.sample.orientation_unit}) |
---|
664 | written = written | write_node(doc, ori, "yaw", |
---|
665 | datainfo.sample.orientation.z, |
---|
666 | {"unit":datainfo.sample.orientation_unit}) |
---|
667 | if written == True: |
---|
668 | sample.appendChild(ori) |
---|
669 | |
---|
670 | # Instrument info |
---|
671 | instr = doc.createElement("SASinstrument") |
---|
672 | entry_node.appendChild(instr) |
---|
673 | |
---|
674 | write_node(doc, instr, "name", datainfo.instrument) |
---|
675 | |
---|
676 | # Source |
---|
677 | source = doc.createElement("SASsource") |
---|
678 | if datainfo.source.name is not None: |
---|
679 | source.setAttribute("name", str(datainfo.source.name)) |
---|
680 | instr.appendChild(source) |
---|
681 | |
---|
682 | write_node(doc, source, "radiation", datainfo.source.radiation) |
---|
683 | write_node(doc, source, "beam_shape", datainfo.source.beam_shape) |
---|
684 | size = doc.createElement("beam_size") |
---|
685 | if datainfo.source.beam_size_name is not None: |
---|
686 | size.setAttribute("name", str(datainfo.source.beam_size_name)) |
---|
687 | written = write_node(doc, size, "x", datainfo.source.beam_size.x, |
---|
688 | {"unit":datainfo.source.beam_size_unit}) |
---|
689 | written = written | write_node(doc, size, "y", |
---|
690 | datainfo.source.beam_size.y, |
---|
691 | {"unit":datainfo.source.beam_size_unit}) |
---|
692 | written = written | write_node(doc, size, "z", |
---|
693 | datainfo.source.beam_size.z, |
---|
694 | {"unit":datainfo.source.beam_size_unit}) |
---|
695 | if written == True: |
---|
696 | source.appendChild(size) |
---|
697 | |
---|
698 | write_node(doc, source, "wavelength", |
---|
699 | datainfo.source.wavelength, |
---|
700 | {"unit":datainfo.source.wavelength_unit}) |
---|
701 | write_node(doc, source, "wavelength_min", |
---|
702 | datainfo.source.wavelength_min, |
---|
703 | {"unit":datainfo.source.wavelength_min_unit}) |
---|
704 | write_node(doc, source, "wavelength_max", |
---|
705 | datainfo.source.wavelength_max, |
---|
706 | {"unit":datainfo.source.wavelength_max_unit}) |
---|
707 | write_node(doc, source, "wavelength_spread", |
---|
708 | datainfo.source.wavelength_spread, |
---|
709 | {"unit":datainfo.source.wavelength_spread_unit}) |
---|
710 | |
---|
711 | # Collimation |
---|
712 | for item in datainfo.collimation: |
---|
713 | coll = doc.createElement("SAScollimation") |
---|
714 | if item.name is not None: |
---|
715 | coll.setAttribute("name", str(item.name)) |
---|
716 | instr.appendChild(coll) |
---|
717 | |
---|
718 | write_node(doc, coll, "length", item.length, |
---|
719 | {"unit":item.length_unit}) |
---|
720 | |
---|
721 | for apert in item.aperture: |
---|
722 | ap = doc.createElement("aperture") |
---|
723 | if apert.name is not None: |
---|
724 | ap.setAttribute("name", str(apert.name)) |
---|
725 | if apert.type is not None: |
---|
726 | ap.setAttribute("type", str(apert.type)) |
---|
727 | coll.appendChild(ap) |
---|
728 | |
---|
729 | write_node(doc, ap, "distance", apert.distance, |
---|
730 | {"unit":apert.distance_unit}) |
---|
731 | |
---|
732 | size = doc.createElement("size") |
---|
733 | if apert.size_name is not None: |
---|
734 | size.setAttribute("name", str(apert.size_name)) |
---|
735 | written = write_node(doc, size, "x", apert.size.x, |
---|
736 | {"unit":apert.size_unit}) |
---|
737 | written = written | write_node(doc, size, "y", apert.size.y, |
---|
738 | {"unit":apert.size_unit}) |
---|
739 | written = written | write_node(doc, size, "z", apert.size.z, |
---|
740 | {"unit":apert.size_unit}) |
---|
741 | if written == True: |
---|
742 | ap.appendChild(size) |
---|
743 | |
---|
744 | # Detectors |
---|
745 | for item in datainfo.detector: |
---|
746 | det = doc.createElement("SASdetector") |
---|
747 | written = write_node(doc, det, "name", item.name) |
---|
748 | written = written | write_node(doc, det, "SDD", item.distance, |
---|
749 | {"unit":item.distance_unit}) |
---|
750 | written = written | write_node(doc, det, "slit_length", |
---|
751 | item.slit_length, |
---|
752 | {"unit":item.slit_length_unit}) |
---|
753 | if written == True: |
---|
754 | instr.appendChild(det) |
---|
755 | |
---|
756 | off = doc.createElement("offset") |
---|
757 | written = write_node(doc, off, "x", item.offset.x, |
---|
758 | {"unit":item.offset_unit}) |
---|
759 | written = written | write_node(doc, off, "y", item.offset.y, |
---|
760 | {"unit":item.offset_unit}) |
---|
761 | written = written | write_node(doc, off, "z", item.offset.z, |
---|
762 | {"unit":item.offset_unit}) |
---|
763 | if written == True: |
---|
764 | det.appendChild(off) |
---|
765 | |
---|
766 | center = doc.createElement("beam_center") |
---|
767 | written = write_node(doc, center, "x", item.beam_center.x, |
---|
768 | {"unit":item.beam_center_unit}) |
---|
769 | written = written | write_node(doc, center, "y", |
---|
770 | item.beam_center.y, |
---|
771 | {"unit":item.beam_center_unit}) |
---|
772 | written = written | write_node(doc, center, "z", |
---|
773 | item.beam_center.z, |
---|
774 | {"unit":item.beam_center_unit}) |
---|
775 | if written == True: |
---|
776 | det.appendChild(center) |
---|
777 | |
---|
778 | pix = doc.createElement("pixel_size") |
---|
779 | written = write_node(doc, pix, "x", item.pixel_size.x, |
---|
780 | {"unit":item.pixel_size_unit}) |
---|
781 | written = written | write_node(doc, pix, "y", item.pixel_size.y, |
---|
782 | {"unit":item.pixel_size_unit}) |
---|
783 | written = written | write_node(doc, pix, "z", item.pixel_size.z, |
---|
784 | {"unit":item.pixel_size_unit}) |
---|
785 | if written == True: |
---|
786 | det.appendChild(pix) |
---|
787 | |
---|
788 | ori = doc.createElement("orientation") |
---|
789 | written = write_node(doc, ori, "roll", item.orientation.x, |
---|
790 | {"unit":item.orientation_unit}) |
---|
791 | written = written | write_node(doc, ori, "pitch", |
---|
792 | item.orientation.y, |
---|
793 | {"unit":item.orientation_unit}) |
---|
794 | written = written | write_node(doc, ori, "yaw", |
---|
795 | item.orientation.z, |
---|
796 | {"unit":item.orientation_unit}) |
---|
797 | if written == True: |
---|
798 | det.appendChild(ori) |
---|
799 | |
---|
800 | |
---|
801 | # Processes info |
---|
802 | for item in datainfo.process: |
---|
803 | node = doc.createElement("SASprocess") |
---|
804 | entry_node.appendChild(node) |
---|
805 | |
---|
806 | write_node(doc, node, "name", item.name) |
---|
807 | write_node(doc, node, "date", item.date) |
---|
808 | write_node(doc, node, "description", item.description) |
---|
809 | for term in item.term: |
---|
810 | value = term['value'] |
---|
811 | del term['value'] |
---|
812 | write_node(doc, node, "term", value, term) |
---|
813 | for note in item.notes: |
---|
814 | write_node(doc, node, "SASprocessnote", note) |
---|
815 | |
---|
816 | # Return the document, and the SASentry node associated with |
---|
817 | # the data we just wrote |
---|
818 | return doc, entry_node |
---|
819 | |
---|
820 | def write(self, filename, datainfo): |
---|
821 | """ |
---|
822 | Write the content of a Data1D as a CanSAS XML file |
---|
823 | |
---|
824 | :param filename: name of the file to write |
---|
825 | :param datainfo: Data1D object |
---|
826 | """ |
---|
827 | # Create XML document |
---|
828 | doc, sasentry = self._to_xml_doc(datainfo) |
---|
829 | # Write the file |
---|
830 | fd = open(filename, 'w') |
---|
831 | fd.write(doc.toprettyxml()) |
---|
832 | fd.close() |
---|
833 | |
---|
834 | def _store_float(self, location, node, variable, storage, optional=True): |
---|
835 | """ |
---|
836 | Get the content of a xpath location and store |
---|
837 | the result. Check that the units are compatible |
---|
838 | with the destination. The value is expected to |
---|
839 | be a float. |
---|
840 | |
---|
841 | The xpath location might or might not exist. |
---|
842 | If it does not exist, nothing is done |
---|
843 | |
---|
844 | :param location: xpath location to fetch |
---|
845 | :param node: node to read the data from |
---|
846 | :param variable: name of the data member to store it in [string] |
---|
847 | :param storage: data object that has the 'variable' data member |
---|
848 | :param optional: if True, no exception will be raised |
---|
849 | if unit conversion can't be done |
---|
850 | |
---|
851 | :raise ValueError: raised when the units are not recognized |
---|
852 | """ |
---|
853 | entry = get_content(location, node) |
---|
854 | try: |
---|
855 | value = float(entry.text) |
---|
856 | except: |
---|
857 | value = None |
---|
858 | |
---|
859 | if value is not None: |
---|
860 | # If the entry has units, check to see that they are |
---|
861 | # compatible with what we currently have in the data object |
---|
862 | units = entry.get('unit') |
---|
863 | if units is not None: |
---|
864 | toks = variable.split('.') |
---|
865 | exec "local_unit = storage.%s_unit" % toks[0] |
---|
866 | if units.lower()!=local_unit.lower(): |
---|
867 | if has_converter==True: |
---|
868 | try: |
---|
869 | conv = Converter(units) |
---|
870 | exec "storage.%s = %g" % (variable, |
---|
871 | conv(value, units=local_unit)) |
---|
872 | except: |
---|
873 | err_mess = "CanSAS reader: could not convert" |
---|
874 | err_mess += " %s unit [%s]; expecting [%s]\n %s" \ |
---|
875 | % (variable, units, local_unit, sys.exc_value) |
---|
876 | self.errors.append(err_mess) |
---|
877 | if optional: |
---|
878 | logging.info(err_mess) |
---|
879 | else: |
---|
880 | raise ValueError, err_mess |
---|
881 | else: |
---|
882 | err_mess = "CanSAS reader: unrecognized %s unit [%s];" |
---|
883 | err_mess += " expecting [%s]" % (variable, |
---|
884 | units, local_unit) |
---|
885 | self.errors.append(err_mess) |
---|
886 | if optional: |
---|
887 | logging.info(err_mess) |
---|
888 | else: |
---|
889 | raise ValueError, err_mess |
---|
890 | else: |
---|
891 | exec "storage.%s = value" % variable |
---|
892 | else: |
---|
893 | exec "storage.%s = value" % variable |
---|
894 | |
---|
895 | def _store_content(self, location, node, variable, storage): |
---|
896 | """ |
---|
897 | Get the content of a xpath location and store |
---|
898 | the result. The value is treated as a string. |
---|
899 | |
---|
900 | The xpath location might or might not exist. |
---|
901 | If it does not exist, nothing is done |
---|
902 | |
---|
903 | :param location: xpath location to fetch |
---|
904 | :param node: node to read the data from |
---|
905 | :param variable: name of the data member to store it in [string] |
---|
906 | :param storage: data object that has the 'variable' data member |
---|
907 | |
---|
908 | :return: return a list of errors |
---|
909 | """ |
---|
910 | entry = get_content(location, node) |
---|
911 | if entry is not None and entry.text is not None: |
---|
912 | exec "storage.%s = entry.text.strip()" % variable |
---|
913 | |
---|
914 | |
---|
915 | |
---|
916 | if __name__ == "__main__": |
---|
917 | logging.basicConfig(level=logging.ERROR, |
---|
918 | format='%(asctime)s %(levelname)s %(message)s', |
---|
919 | filename='cansas_reader.log', |
---|
920 | filemode='w') |
---|
921 | reader = Reader() |
---|
922 | print reader.read("../test/cansas1d.xml") |
---|
923 | #print reader.read("../test/latex_smeared.xml") |
---|
924 | |
---|
925 | |
---|
926 | |
---|