Debian Codegraph @

nxs/napi.py

raw ◀ ▶
Source reconstructed at patch state 3 of 5 — not the installed (fully patched) source.
5 Debian patches touch this file
1 # This program is public domain
2 # Author: Paul Kienzle
3
4 """
5 Wrapper for the NeXus shared library.
6
7 Use this interface when converting code from other languages which
8 do not support the natural view of the hierarchy.
9
10 Library Location
11 ================
12
13 :py:mod:`nxs.napi` needs to know the location of the `libNeXus` C-library in
14 order to load it via :py:mod:`ctypes`. It looks in the following places in
15 order:
16
17
18 +-------------------------------------+-----------------+
19 | Environment | Platforms |
20 +=====================================+=================+
21 | ``os.environ['NEXUSLIB']`` | All |
22 +-------------------------------------+-----------------+
23 | directory containing nxs.py | All |
24 +-------------------------------------+-----------------+
25 | ``os.environ['NEXUSDIR']\\bin`` | Windows |
26 +-------------------------------------+-----------------+
27 | ``os.environ['LD_LIBRARY_PATH']`` | Unix |
28 +-------------------------------------+-----------------+
29 | ``os.environ['DYLD_LIBRARY_PATH']`` | Darwin |
30 +-------------------------------------+-----------------+
31 | ``LIBDIR`` | Unix and Darwin |
32 +-------------------------------------+-----------------+
33
34
35 * On Windows it looks for one of ``libNeXus.dll`` or ``libNeXus-0.dll``.
36 * On OS X it looks for ``libNeXus.0.dylib``
37 * On Unix it looks for ``libNeXus.so.1``
38 * ``NEXUSDIR`` defaults to ``C:\\Program Files\\NeXus Data Format``.
39 * ``LIBDIR`` defaults to ``/usr/local/lib``, but is replaced by the value of
40 ``--libdir`` during configure.
41
42 The import will raise an :py:exc:`OSError` exception if the library wasn't
43 found or couldn't be loaded. Note that on Windows in particular this may be
44 because the supporting HDF5 dlls were not available in the usual places.
45
46 If you are extracting the nexus library from a bundle at runtime, set
47 `os.environ['NEXUSLIB']` to the path where it is extracted before the
48 first import of nxs.
49
50 Example
51 =======
52 .. code-block:: python
53
54 import nxs
55 file = nxs.open('filename.nxs','rw')
56 file.opengroup('entry1')
57 file.opendata('definition')
58 print file.getdata()
59 file.close()
60
61
62 See @see nxstest.py for a more complete example.
63
64 Interface
65 =========
66
67 When converting code to python from other languages you do not necessarily want
68 to redo the file handling code. The nxs provides an interface which more
69 closely follows the NeXus application programming interface (NAPI_).
70
71 This wrapper differs from NAPI in several respects:
72
73 * Data values are loaded/stored directly from numpy arrays.
74 * Return codes are turned into exceptions.
75 * The file handle is stored in a file object
76 * Constants are handled somewhat differently (see below)
77 * Type checking on data/parameter storage
78 * Adds iterators file.entries() and file.attrs()
79 * Adds link() function to return the name of the linked to group, if any
80 * NXmalloc/NXfree are not needed.
81
82 File open modes can be constants or strings:
83
84 +--------------------------+--------------------------+
85 | Flag | Character representation |
86 +==========================+==========================+
87 | `nxs.napi.ACC_READ` | 'r' |
88 +--------------------------+--------------------------+
89 | `nxs.napi.ACC_RDWR` | 'rw' |
90 +--------------------------+--------------------------+
91 | `nxs.napi.ACC_CREATE` | 'w' |
92 +--------------------------+--------------------------+
93 | `nxs.napi.ACC_CREATE4` | 'w4' |
94 +--------------------------+--------------------------+
95 | `nxs.napi.ACC_CREATE5` | 'w5' |
96 +--------------------------+--------------------------+
97 | `nxs.napi.ACC_CREATEXML` | 'wx' |
98 +--------------------------+--------------------------+
99
100
101 Dimension constants:
102
103 +---------------+---------------------------------------+
104 | Constant | Description |
105 +===============+=======================================+
106 | nxs.UNLIMITED | for the extensible data dimension |
107 +---------------+---------------------------------------+
108 | nxs.MAXRANK | for the number of possible dimensions |
109 +---------------+---------------------------------------+
110
111 Data types are strings corresponding to the numpy data types:
112
113 +---------------+-----------------------------+
114 | Type string | Description |
115 +===============+=============================+
116 | ``'float32'`` | 32Bit floating point number |
117 +---------------+-----------------------------+
118 | ``'float64'`` | 64Bit floating point number |
119 +---------------+-----------------------------+
120 | ``'int8'`` | 8Bit singed integer |
121 +---------------+-----------------------------+
122 | ``'int16'`` | 16Bit signed integer |
123 +---------------+-----------------------------+
124 | ``'int32'`` | 32Bit signed integer |
125 +---------------+-----------------------------+
126 | ``'int64'`` | 64Bit signed integer |
127 +---------------+-----------------------------+
128 | ``'uint8'`` | 8Bit unsigned integer |
129 +---------------+-----------------------------+
130 | ``'uint16'`` | 16Bit unsigned integer |
131 +---------------+-----------------------------+
132 | ``'uint32'`` | 32Bit unsigned integer |
133 +---------------+-----------------------------+
134 | ``'uint64'`` | 64Bit unsigned integer |
135 +---------------+-----------------------------+
136 | ``'char'`` | used for string data |
137 +---------------+-----------------------------+
138
139
140 To retrieve the type of a :py:mod:`numpy` array one can use its
141 :py:attr:`dtype` attribute.
142
143 Dimensions are lists of integers or numpy arrays. You can use the
144 numpy A.shape attribute for the dimensions of array A.
145
146 Compression codes are::
147
148 'none' 'lzw' 'rle' 'huffman'
149
150 As of this writing NeXus only supports 'none' and 'lzw'.
151
152 Miscellaneous constants:
153
154 +----------------+--------------------------------------------------------------+
155 | Constant | Description |
156 +================+==============================================================+
157 | :py:const:`nxs | names must be shorter than this |
158 | .napi.MAXNAMEL | |
159 | EN` | |
160 +----------------+--------------------------------------------------------------+
161 | nxs.napi.MAXPA | total path length must be shorter than this |
162 | THLEN | |
163 +----------------+--------------------------------------------------------------+
164 | nxs.napi.H4SKI | class names that may appear in HDF4 files but can be ignored |
165 | P | |
166 +----------------+--------------------------------------------------------------+
167
168 Caveats
169 =======
170
171 @todo NOSTRIP constant is probably not handled properly,
172 @todo Embedded nulls in strings is not supported
173
174 @warning We have a memory leak. Calling open/close costs about 90k a pair.
175 This is an eigenbug:
176 - if I test ctypes on a simple library it does not leak
177 - if I use the leak_test1 code in the nexus distribution it doesn't leak
178 - if I remove the open/close call in the wrapper it doesn't leak.
179
180 """
181
182 from __future__ import print_function
183
184 ## @example nxstest.py
185 # Test program for NeXus python interface
186
187 __all__ = ['UNLIMITED', 'MAXRANK', 'MAXNAMELEN','MAXPATHLEN','H4SKIP',
188 'NeXus','NeXusError','open']
189
190 import sys, os, numpy, ctypes
191 import six
192
193 # Defined ctypes
194 from ctypes import c_void_p, c_int, c_int64, c_long, c_char, c_char_p
195 from ctypes import byref as _ref
196 c_void_pp = ctypes.POINTER(c_void_p)
197 c_int_p = ctypes.POINTER(c_int)
198 c_int64_p = ctypes.POINTER(c_int64)
199 class _NXlink(ctypes.Structure):
200 _fields_ = [("iTag", c_long),
201 ("iRef", c_long),
202 ("targetPath", c_char*1024),
203 ("linktype", c_int)]
204 _pack_ = False
205 c_NXlink_p = ctypes.POINTER(_NXlink)
206
207
208 # Open modes:
209 ACC_READ,ACC_RDWR,ACC_CREATE=1,2,3
210 ACC_CREATE4,ACC_CREATE5,ACC_CREATEXML=4,5,6
211 _nxopen_mode=dict(r=1,rw=2,w=3,w4=4,w5=5,wx=6)
212 NOSTRIP=128
213
214 # Status codes
215 OK,ERROR,EOD=1,0,-1
216
217 # Other constants
218 UNLIMITED=-1
219 MAXRANK=32
220 MAXNAMELEN=64
221 MAXPATHLEN=1024 # inferred from code
222
223 # bogus groups; these groups are ignored in HDFView from NCSA.
224 H4SKIP = ['CDF0.0','_HDF_CHK_TBL_','Attr0.0',
225 'RIG0.0','RI0.0', 'RIATTR0.0N','RIATTR0.0C']
226
227 # HDF data types from numpy types
228 _nxtype_code=dict(
229 char=4,
230 float32=5,float64=6,
231 int8=20,uint8=21,
232 int16=22,uint16=23,
233 int32=24,uint32=25,
234 int64=26,uint64=27,
235 )
236 # Python types from HDF data types
237 # Other than 'char' for the string type, the python types correspond to
238 # the numpy data types, and can be used directly to create numpy arrays.
239 # Note: put this in a lambda to hide v,k from the local namespace
240 _pytype_code=(lambda : dict([(v,k) for (k,v) in six.iteritems(_nxtype_code)]))()
241
242 # Compression to use when creating data blocks
243 _compression_code=dict(
244 none=100,
245 lzw=200,
246 rle=300,
247 huffman=400)
248
249 def _is_string_like(obj):
250 """
251 Return True if object acts like a string.
252 """
253 # From matplotlib cbook.py John D. Hunter
254 # Python 2.2 style licence. See license.py in matplotlib for details.
255 if hasattr(obj, 'shape'): return False
256 try: obj + ''
257 except (TypeError, ValueError): return False
258 return True
259
260 def _is_list_like(obj):
261 """
262 Return True if object acts like a list
263 """
264 try: obj + []
265 except TypeError: return False
266 return True
267
268 def _libnexus():
269 """
270 Load the NeXus library.
271 """
272 # this will get changed as part of the install process
273 # it should correspond to --libdir specified to ./configure
274 # NEXUSLIB takes precedence
275 file = 'libNeXus.so.1'
276 if 'NEXUSLIB' in os.environ:
277 file = os.environ['NEXUSLIB']
278 if not os.path.isfile(file):
279 raise OSError("File %s from environment variable NEXUSLIB does "
280 "exist" % file)
281
282 # Given a list of files, try loading the first one that is available.
283 try:
284 return ctypes.cdll[file]
285 except OSError:
286 pass
287 raise OSError("Set NEXUSLIB or put it in a standard location.")
288
289 def _init():
290 lib = _libnexus()
291 lib.NXMDisableErrorReporting()
292 return lib
293
294 # Define the interface to the dll
295 nxlib = _init()
296
297
298 def open(filename, mode='r'):
299 """
300 Returns a NeXus file object.
301 """
302 return NeXus(filename, mode)
303
304 class NeXusError(Exception):
305 """NeXus Error"""
306 pass
307
308 class NeXus(object):
309
310 # ==== File ====
311 nxlib.nxiopen_.restype = c_int
312 nxlib.nxiopen_.argtypes = [c_char_p, c_int, c_void_pp]
313 def __init__(self, filename, mode='r', encoding='UTF-8'):
314 """
315 Open the NeXus file returning a handle.
316
317 mode can be one of the following:
318 nxs.ACC_READ 'r' open a file read-only
319 nxs.ACC_RDWR 'rw' open a file read/write
320 nxs.ACC_CREATE 'w' open a file write
321 nxs.ACC_CREATE4 'w4' open a Nexus file with HDF4
322 nxs.ACC_CREATE5 'w5' open a Nexus file with HDF5
323 nxs.ACC_CREATEXML 'wx' open a Nexus file with XML
324
325 Raises ValueError if the open mode is invalid.
326
327 Raises NeXusError if the file could not be opened, with the
328 filename as part of the error message.
329
330 Corresponds to NXopen(filename,mode,&handle)
331 """
332 self.isopen = False
333
334 # Convert open mode from string to integer and check it is valid
335 if mode in _nxopen_mode: mode = _nxopen_mode[mode]
336 if mode not in _nxopen_mode.values():
337 raise ValueError("Invalid open mode %s" % str(mode))
338
339 self.encoding = encoding
340 self.filename = self._str2bytes(filename)
341 self.mode = mode
342 self.handle = c_void_p(None)
343 self._path = []
344 self._indata = False
345 status = nxlib.nxiopen_(self.filename,mode,_ref(self.handle))
346 if status == ERROR:
347 if mode in [ACC_READ, ACC_RDWR]:
348 op = 'open'
349 else:
350 op = 'create'
351 raise NeXusError("Could not %s %s" % (op,self.filename))
352 self.isopen = True
353
354 def _getpath(self):
355 mypath = [level[0] for level in self._path]
356 return '/'+'/'.join(mypath)
357 path = property(_getpath,doc="Unix-style path to node")
358
359 def _getlongpath(self):
360 mypath = [':'.join(level) for level in self._path]
361 return '/' + '/'.join(mypath)
362 longpath = property(_getlongpath, doc="Unix-style path including " \
363 + "nxclass to the node")
364
365 def _str2bytes(self, s):
366 if isinstance(s, str):
367 s = s.encode(self.encoding)
368 return s
369
370 def _bytes2str(self, b):
371 if isinstance(b, bytes):
372 b = b.decode(self.encoding)
373 return b
374
375 def __del__(self):
376 """
377 Be sure to close the file before deleting the last reference.
378 """
379 if self.isopen: self.close()
380
381
382 def __str__(self):
383 """
384 Return a string representation of the NeXus file handle.
385 """
386 return "NeXus('%s')"%self.filename
387
388
389 def open(self):
390 """
391 Opens the NeXus file handle if it is not already open.
392
393 Raises NeXusError if the file could not be opened.
394
395 Corresponds to NXopen(filename,mode,&handle)
396 """
397 if self.isopen: return
398 if self.mode==ACC_READ:
399 mode = ACC_READ
400 else:
401 mode = ACC_RDWR
402 status = nxlib.nxiopen_(self.filename,mode,_ref(self.handle))
403 if status == ERROR:
404 raise NeXusError("Could not open %s" % (self.filename))
405 self._path = []
406 self._indata = False
407
408 nxlib.nxiclose_.restype = c_int
409 nxlib.nxiclose_.argtypes = [c_void_pp]
410 def close(self):
411 """
412 Close the NeXus file associated with handle.
413
414 Raises NeXusError if file could not be closed.
415
416 Corresponds to NXclose(&handle)
417 """
418 if self.isopen:
419 self.isopen = False
420 status = nxlib.nxiclose_(_ref(self.handle))
421 if status == ERROR:
422 raise NeXusError("Could not close NeXus file %s" %
423 (self.filename))
424 self._path = []
425 self._indata = False
426
427 nxlib.nxiflush_.restype = c_int
428 nxlib.nxiflush_.argtypes = [c_void_pp]
429 def flush(self):
430 """
431 Flush all data to the NeXus file.
432
433 Raises NeXusError if this fails.
434
435 Corresponds to NXflush(&handle)
436 """
437 status = nxlib.nxiflush_(_ref(self.handle))
438 if status == ERROR:
439 raise NeXusError("Could not flush NeXus file %s" % (self.filename))
440
441 nxlib.nxisetnumberformat_.restype = c_int
442 nxlib.nxisetnumberformat_.argtypes = [c_void_p, c_int, c_char_p]
443 def setnumberformat(self,type,format):
444 """
445 Set the output format for the numbers of the given type (only
446 applies to XML).
447
448 Raises ValueError if the number format is incorrect.
449
450 Corresponds to NXsetnumberformat(&handle,type,format)
451 """
452 type = _nxtype_code[type]
453 status = nxlib.nxisetnumberformat_(self.handle,type,self._str2bytes(format))
454 if status == ERROR:
455 raise ValueError("Could not set %s to %s in %s" %
456 (type, format, self.filename))
457
458 # ==== Group ====
459 nxlib.nximakegroup_.restype = c_int
460 nxlib.nximakegroup_.argtypes = [c_void_p, c_char_p, c_char_p]
461 def makegroup(self, name, nxclass):
462 """
463 Create the group nxclass:name.
464
465 Raises NeXusError if the group could not be created.
466
467 Corresponds to NXmakegroup(handle, name, nxclass)
468 """
469 # print("makegroup", self._loc(), name, nxclass)
470 status = nxlib.nximakegroup_(self.handle, self._str2bytes(name),
471 self._str2bytes(nxclass))
472 if status == ERROR:
473 raise NeXusError("Could not create %s:%s in %s" %
474 (nxclass, name, self._loc()))
475
476 nxlib.nxiopenpath_.restype = c_int
477 nxlib.nxiopenpath_.argtypes = [c_void_p, c_char_p]
478 def openpath(self, path):
479 """
480 Open a particular group '/path/to/group'. Paths can be
481 absolute or relative to the currently open group. If openpath
482 fails, then currently open path may not be different from the
483 starting path. For better performation the types can be
484 specified as well using '/path:type1/to:type2/group:type3'
485 which will prevent searching the file for the types associated
486 with the supplied names.
487
488 Raises ValueError.
489
490 Corresponds to NXopenpath(handle, path)
491 """
492 self._openpath(self._str2bytes(path), opendata=True)
493
494 def _openpath(self, path, opendata=True):
495 """helper function: open relative path and maybe data"""
496 # Determine target node as sequence of group names
497 if path == '/':
498 target = []
499 else:
500 if path.endswith("/"):
501 path = path[:-1]
502 if path.startswith('/'):
503 target = path[1:].split('/')
504 else:
505 target = self._path + path.split('/')
506
507 # Remove relative path indicators from target
508 L = []
509 for t in target:
510 if t == '.':
511 # Skip current node
512 pass
513 elif t == '..':
514 if L == []:
515 raise ValueError("too many '..' in path")
516 L.pop()
517 else:
518 L.append(t)
519 target = L
520
521 # split out nxclass from each level if available
522 L = []
523 for t in target:
524 try:
525 item = t.split(":")
526 if len(item) == 1:
527 L.append((item[0], None))
528 else:
529 L.append(tuple(item))
530 except AttributeError:
531 L.append(t)
532 target = L
533
534 # print("current path", self._path)
535 # print("%s" % path, target)
536
537 # Find which groups need to be closed and opened
538 up = []
539 down = []
540 for (i, (name, nxclass)) in enumerate(target):
541 if i == len(self._path):
542 # print("target longer than current")
543 up = []
544 down = target[i:]
545 break
546 elif self._path[i] != name:
547 # print("target and current differ at", name)
548 up = self._path[i:]
549 down = target[i:]
550 break
551 else:
552 # print("target shorter than current")
553 up = self._path[len(target):]
554 down = []
555
556 # add more information to the down path
557 for i in xrange(len(down)):
558 try:
559 (name, nxclass) = down[i]
560 except ValueError:
561 down[i] = (down[i], None)
562 # print("close,open", up, down)
563
564 # Close groups on the way up
565 if self._indata and up != []:
566 self.closedata()
567 up.pop()
568 for target in up:
569 self.closegroup()
570
571 # Open groups on the way down
572 for target in down:
573 (name, nxclass) = target
574 if nxclass is None:
575 nxclass = self.__getnxclass(name)
576 if nxclass != "SDS":
577 self.opengroup(name, nxclass)
578 elif opendata:
579 self.opendata(name)
580 else:
581 raise ValueError("node %s not in %s" % (name, self.path))
582
583 nxlib.nxiopengrouppath_.restype = c_int
584 nxlib.nxiopengrouppath_.argtypes = [c_void_p, c_char_p]
585 def opengrouppath(self, path):
586 """
587 Open a particular group '/path/to/group', or the dataset containing
588 the group if the path refers to a dataset. Paths can be relative to
589 the currently open group.
590
591 Raises ValueError.
592
593 Corresponds to NXopengrouppath(handle, path)
594 """
595 self._openpath(self._str2bytes(path),opendata=False)
596
597 nxlib.nxiopengroup_.restype = c_int
598 nxlib.nxiopengroup_.argtypes = [c_void_p, c_char_p, c_char_p]
599 def opengroup(self, name, nxclass=None):
600 """
601 Open the group nxclass:name. If the nxclass is not specified
602 this will search for it.
603
604 Raises NeXusError if the group could not be opened.
605
606 Corresponds to NXopengroup(handle, name, nxclass)
607 """
608 # print("opengroup", self._loc(), name, nxclass)
609 if nxclass is None:
610 nxclass = self.__getnxclass(name)
611 status = nxlib.nxiopengroup_(self.handle, self._str2bytes(name),
612 self._str2bytes(nxclass))
613 if status == ERROR:
614 raise ValueError("Could not open %s:%s in %s" %
615 (nxclass, name, self._loc()))
616 self._path.append((name,nxclass))
617
618 nxlib.nxiclosegroup_.restype = c_int
619 nxlib.nxiclosegroup_.argtypes = [c_void_p]
620 def closegroup(self):
621 """
622 Close the currently open group.
623
624 Raises NeXusError if the group could not be closed.
625
626 Corresponds to NXclosegroup(handle)
627 """
628 # print("closegroup")
629 if self._indata:
630 raise NeXusError("Close data before group at %s" % (self._loc()))
631 status = nxlib.nxiclosegroup_(self.handle)
632 if status == ERROR:
633 raise NeXusError("Could not close group at %s" % (self._loc()))
634 self._path.pop()
635
636 nxlib.nxigetgroupinfo_.restype = c_int
637 nxlib.nxigetgroupinfo_.argtypes = [c_void_p, c_int_p, c_char_p, c_char_p]
638 def getgroupinfo(self):
639 """
640 Query the currently open group returning the tuple
641 numentries, name, nxclass.
642
643 Raises ValueError if the group could not be opened.
644
645 Corresponds to NXgetgroupinfo(handle)
646
647 Note: corrects error in HDF5 where getgroupinfo returns the entire
648 path rather than the group name. Use the path attribute to get
649 a sensible value of path.
650 """
651 # Space for the returned strings
652 path = ctypes.create_string_buffer(MAXPATHLEN)
653 nxclass = ctypes.create_string_buffer(MAXNAMELEN)
654 n = c_int(0)
655 status = nxlib.nxigetgroupinfo_(self.handle,_ref(n),path,nxclass)
656 path = self._bytes2str(path)
657 nxclass = self._bytes2str(nxclass)
658 if status == ERROR:
659 raise ValueError("Could not get group info: %s" % (self._loc()))
660 # print("getgroupinfo", self._loc(), nxclass.value, name.value, n.value)
661 name = path.value.split('/')[-1] # Protect against HDF5 returning path
662 return n.value,name,nxclass.value
663
664 nxlib.nxiinitgroupdir_.restype = c_int
665 nxlib.nxiinitgroupdir_.argtypes = [c_void_p]
666 def initgroupdir(self):
667 """
668 Reset getnextentry to return the first entry in the group.
669
670 Raises NeXusError if this fails.
671
672 Corresponds to NXinitgroupdir(handle)
673 """
674 status = nxlib.nxiinitgroupdir_(self.handle)
675 if status == ERROR:
676 raise NeXusError("Could not reset group scan: %s" % (self._loc()))
677
678 nxlib.nxigetnextentry_.restype = c_int
679 nxlib.nxigetnextentry_.argtypes = [c_void_p, c_char_p, c_char_p, c_int_p]
680 def getnextentry(self):
681 """
682 Return the next entry in the group as name,nxclass tuple. If
683 end of data is reached this returns the tuple (None, None)
684
685 Raises NeXusError if this fails.
686
687 Corresponds to NXgetnextentry(handle,name,nxclass,&storage).
688
689 This function doesn't return the storage class for data entries
690 since getinfo returns shape and storage, both of which are required
691 to read the data.
692
693 Note that HDF4 files can have entries in the file with classes
694 that don't need to be processed. If the file follows the standard
695 NeXus DTDs then skip any entry for which nxclass.startswith('NX')
696 is False. For non-conforming files, skip those entries with
697 nxclass in nxs.H4SKIP.
698 """
699 name = ctypes.create_string_buffer(MAXNAMELEN)
700 nxclass = ctypes.create_string_buffer(MAXNAMELEN)
701 storage = c_int(0)
702 status = nxlib.nxigetnextentry_(self.handle,name,nxclass,_ref(storage))
703 if status == EOD:
704 return (None, None)
705 if status == ERROR:
706 raise NeXusError("Could not get next entry: %s" % (self._loc()))
707 ## Note: ignoring storage --- it is useless without dimensions
708 # if nxclass == 'SDS':
709 # dtype = _pytype_code(storage.value)
710 # print("nextentry", nxclass.value, name.value, storage.value)
711 return self._bytes2str(name.value), self._bytes2str(nxclass.value)
712
713 def getentries(self):
714 """
715 Return a dictionary of the groups[name]=type below the
716 existing open one.
717
718 Raises NeXusError if this fails.
719 """
720 self.initgroupdir()
721 result = {}
722 (name, nxclass) = self.getnextentry()
723 if (name, nxclass) != (None, None):
724 result[name] = nxclass
725 while (name, nxclass) != (None, None):
726 result[name] = nxclass
727 (name, nxclass) = self.getnextentry()
728 return result
729
730 def __getnxclass(self, target):
731 """
732 Return the nxclass of the supplied name.
733 """
734 self.initgroupdir()
735 while True:
736 (nxname, nxclass) = self.getnextentry()
737 if nxname == target:
738 return nxclass
739 if nxname is None:
740 break
741 raise NeXusError("Failed to find entry with name \"%s\" at %s" %
742 (target, self.path))
743
744 def entries(self):
745 """
746 Iterator of entries.
747
748 for name,nxclass in nxs.entries():
749 process(name,nxclass)
750
751 This automatically opens the corresponding group/data for you,
752 and closes it when you are done. Do not rely on any paths
753 remaining open between entries as we restore the current
754 path each time.
755
756 This does not correspond to an existing NeXus API function,
757 but instead combines the work of initgroupdir/getnextentry
758 and open/close on data and group. Entries in nxs.H4SKIP are
759 ignored.
760 """
761 # To preserve the semantics we must read in the whole list
762 # first, then process the entries one by one. Keep track
763 # of the path so we can restore it between entries.
764 path = self.path
765
766 # Read list of entries
767 self.initgroupdir()
768 n,_,_ = self.getgroupinfo()
769 L = []
770 for dummy in range(n):
771 name,nxclass = self.getnextentry()
772 if nxclass not in H4SKIP:
773 L.append((name,nxclass))
774 for name,nxclass in L:
775 self.openpath(path) # Reset the file cursor
776 if nxclass == "SDS":
777 self.opendata(name)
778 else:
779 self.opengroup(name,nxclass)
780 yield name,nxclass
781
782 # ==== Data ====
783 nxlib.nxigetrawinfo64_.restype = c_int
784 nxlib.nxigetrawinfo64_.argtypes = [c_void_p, c_int_p, c_void_p, c_int_p]
785 def getrawinfo(self):
786 """
787 Returns the tuple dimensions,type for the currently open dataset.
788 Dimensions is an integer array whose length corresponds to the rank
789 of the dataset and whose elements are the size of the individual
790 dimensions. Storage type is returned as a string, with 'char' for
791 a stored string, '[u]int[8|16|32]' for various integer values or
792 'float[32|64]' for floating point values. No support for
793 complex values.
794
795 Unlike getinfo(), the size of the string storage area is
796 returned rather than the length of the stored string.
797
798 Raises NeXusError if this fails.
799
800 Corresponds to NXgetrawinfo(handle, &rank, dims, &storage),
801 but with storage converted from HDF values to numpy compatible
802 strings, and rank implicit in the length of the returned dimensions.
803 """
804 rank = c_int(0)
805 shape = numpy.zeros(MAXRANK, 'int64')
806 storage = c_int(0)
807 status = nxlib.nxigetrawinfo64_(self.handle, _ref(rank),
808 shape.ctypes.data, _ref(storage))
809 if status == ERROR:
810 raise NeXusError("Could not get data info: %s" % (self._loc()))
811 shape = shape[:rank.value]+0
812 dtype = _pytype_code[storage.value]
813 # print("getrawinfo", self._loc(), "->", shape, dtype)
814 return shape,dtype
815
816 nxlib.nxigetinfo64_.restype = c_int
817 nxlib.nxigetinfo64_.argtypes = [c_void_p, c_int_p, c_void_p, c_int_p]
818 def getinfo(self):
819 """
820 Returns the tuple dimensions,type for the currently open dataset.
821 Dimensions is an integer array whose length corresponds to the rank
822 of the dataset and whose elements are the size of the individual
823 dimensions. Storage type is returned as a string, with 'char' for
824 a stored string, '[u]int[8|16|32]' for various integer values or
825 'float[32|64]' for floating point values. No support for
826 complex values.
827
828 Unlike getrawinfo(), the length of the stored string is
829 returned rather than the size of the string storage area.
830
831 Raises NeXusError if this fails.
832
833 Note that this is the recommended way to establish if you have
834 a dataset open.
835
836 Corresponds to NXgetinfo(handle, &rank, dims, &storage),
837 but with storage converted from HDF values to numpy compatible
838 strings, and rank implicit in the length of the returned dimensions.
839 """
840 rank = c_int(0)
841 shape = numpy.zeros(MAXRANK, 'int64')
842 storage = c_int(0)
843 status = nxlib.nxigetinfo64_(self.handle, _ref(rank),
844 shape.ctypes.data,
845 _ref(storage))
846 if status == ERROR:
847 raise NeXusError("Could not get data info: %s" % (self._loc()))
848 shape = shape[:rank.value]+0
849 dtype = _pytype_code[storage.value]
850 # print("getinfo", self._loc(), "->", shape, dtype)
851 return shape,dtype
852
853 nxlib.nxiopendata_.restype = c_int
854 nxlib.nxiopendata_.argtypes = [c_void_p, c_char_p]
855 def opendata(self, name):
856 """
857 Open the named data set within the current group.
858
859 Raises ValueError if could not open the dataset.
860
861 Corresponds to NXopendata(handle, name)
862 """
863 # print("opendata", self._loc(), name)
864 if self._indata:
865 status = ERROR
866 else:
867 status = nxlib.nxiopendata_(self.handle, self._str2bytes(name))
868 if status == ERROR:
869 raise ValueError("Could not open data %s: %s" % (name, self._loc()))
870 self._path.append((name,"SDS"))
871 self._indata = True
872
873 nxlib.nxiclosedata_.restype = c_int
874 nxlib.nxiclosedata_.argtypes = [c_void_p]
875 def closedata(self):
876 """
877 Close the currently open data set.
878
879 Raises NeXusError if this fails (e.g., because no
880 dataset is open).
881
882 Corresponds to NXclosedata(handle)
883 """
884 # print("closedata")
885 status = nxlib.nxiclosedata_(self.handle)
886 if status == ERROR:
887 raise NeXusError("Could not close data at %s" % (self._loc()))
888 self._path.pop()
889 self._indata = False
890
891 nxlib.nximakedata64_.restype = c_int
892 nxlib.nximakedata64_.argtypes = [c_void_p, c_char_p, c_int, c_int, c_int64_p]
893 def makedata(self, name, dtype=None, shape=None):
894 """
895 Create a data element of the given type and shape. See getinfo
896 for details on types. This does not open the data for writing.
897
898 Set the first dimension to nxs.UNLIMITED, for extensible data sets,
899 and use putslab to write individual slabs.
900
901 Raises ValueError if it fails.
902
903 Corresponds to NXmakedata(handle,name,type,rank,dims)
904 """
905 # TODO: With keywords for compression and chunks, this can act as
906 # TODO: compmakedata.
907 # TODO: With keywords for value and attr, this can be used for
908 # TODO: makedata, opendata, putdata, putattr, putattr, ..., closedata
909 # print("makedata", self._loc(), name, shape, dtype)
910 storage = _nxtype_code[str(dtype)]
911 shape = numpy.asarray(shape,'int64')
912 status = nxlib.nximakedata64_(self.handle,self._str2bytes(name),storage,len(shape),
913 shape.ctypes.data_as(c_int64_p))
914 if status == ERROR:
915 raise ValueError("Could not create data %s: %s" %
916 (name,self._loc()))
917
918 nxlib.nxicompmakedata64_.restype = c_int
919 nxlib.nxicompmakedata64_.argtypes = [c_void_p, c_char_p, c_int, c_int, c_int64_p,
920 c_int, c_int64_p]
921 def compmakedata(self, name, dtype=None, shape=None, mode='lzw',
922 chunks=None):
923 """
924 Create a data element of the given dimensions and type. See
925 getinfo for details on types. Compression mode is one of
926 'none', 'lzw', 'rle' or 'huffman'. chunks gives the alignment
927 of the compressed chunks in the data file. There should be one
928 chunk size for each dimension in the data.
929
930 Defaults to mode='lzw' with chunk size set to the length of the
931 fastest varying dimension.
932
933 Raises ValueError if it fails.
934
935 Corresponds to NXmakedata(handle,name,type,rank,dims).
936 """
937 storage = _nxtype_code[str(dtype)]
938 # Make sure shape/chunk_shape are integers; hope that 32/64 bit issues
939 # with the c int type sort themselves out.
940 dims = numpy.asarray(shape,'int64')
941 if chunks is None:
942 chunks = numpy.ones(dims.shape,'int64')
943 chunks[-1] = shape[-1]
944 else:
945 chunks = numpy.array(chunks,'int64')
946 status = nxlib.nxicompmakedata64_(self.handle,
947 self._str2bytes(name),
948 storage,len(dims),
949 dims.ctypes.data_as(c_int64_p),
950 _compression_code[mode],
951 chunks.ctypes.data_as(c_int64_p))
952 if status == ERROR:
953 raise ValueError("Could not create compressed data %s: %s" %
954 (name, self._loc()))
955
956 nxlib.nxigetdata_.restype = c_int
957 nxlib.nxigetdata_.argtypes = [c_void_p, c_void_p]
958 def getdata(self):
959 """
960 Return the data. If data is a string (1-D char array), a python
961 string is returned. If data is a scalar (1-D numeric array of
962 length 1), a python scalar is returned. If data is a string
963 array, a numpy array of type 'S#' where # is the maximum string
964 length is returned. If data is a numeric array, a numpy array
965 is returned.
966
967 Raises ValueError if this fails.
968
969 Corresponds to NXgetdata(handle, data)
970 """
971 # TODO: consider accepting preallocated data so we don't thrash memory
972 shape,dtype = self.getinfo()
973 dummy_data,pdata,dummy_size,datafn = self._poutput(dtype,shape)
974 status = nxlib.nxigetdata_(self.handle,pdata)
975 if status == ERROR:
976 raise ValueError("Could not read data: %s" % (self._loc()))
977 # print("getdata", self._loc(), shape, dtype)
978 return datafn()
979
980 nxlib.nxigetslab64_.restype = c_int
981 nxlib.nxigetslab64_.argtypes = [c_void_p, c_void_p, c_int64_p, c_int64_p]
982 def getslab(self, slab_offset, slab_shape):
983 """
984 Get a slab from the data array.
985
986 Offsets are 0-origin. Shape can be inferred from the data.
987 Offset and shape must each have one entry per dimension.
988
989 Raises ValueError if this fails.
990
991 Corresponds to NXgetslab(handle,data,offset,shape)
992 """
993 # TODO: consider accepting preallocated data so we don't thrash memory
994 dummy_shape,dtype = self.getrawinfo()
995 dummy_data,pdata,dummy_size,datafn = self._poutput(dtype,slab_shape)
996 slab_offset = numpy.asarray(slab_offset,'int64')
997 slab_shape = numpy.asarray(slab_shape,'int64')
998 status = nxlib.nxigetslab64_(self.handle,pdata,
999 slab_offset.ctypes.data_as(c_int64_p),
1000 slab_shape.ctypes.data_as(c_int64_p))
1001 # print("slab", offset, size, data)
1002 if status == ERROR:
1003 raise ValueError("Could not read slab: %s" % (self._loc()))
1004 return datafn()
1005
1006 nxlib.nxiputdata_.restype = c_int
1007 nxlib.nxiputdata_.argtypes = [c_void_p, c_void_p]
1008 def putdata(self, data):
1009 """
1010 Write data into the currently open data block.
1011
1012 Raises ValueError if this fails.
1013
1014 Corresponds to NXputdata(handle, data)
1015 """
1016 shape,dtype = self.getrawinfo()
1017 # print("putdata", self._loc(), shape, dtype)
1018 data,pdata = self._pinput(data,dtype,shape)
1019 status = nxlib.nxiputdata_(self.handle,pdata)
1020 if status == ERROR:
1021 raise ValueError("Could not write data: %s" % (self._loc()))
1022
1023 nxlib.nxiputslab64_.restype = c_int
1024 nxlib.nxiputslab64_.argtypes = [c_void_p, c_void_p, c_int64_p, c_int64_p]
1025 def putslab(self, data, slab_offset, slab_shape):
1026 """
1027 Put a slab into the data array.
1028
1029 Offsets are 0-origin. Shape can be inferred from the data.
1030 Offset and shape must each have one entry per dimension.
1031
1032 Raises ValueError if this fails.
1033
1034 Corresponds to NXputslab(handle,data,offset,shape)
1035 """
1036 dummy_shape,dtype = self.getrawinfo()
1037 data,pdata = self._pinput(data,dtype,slab_shape)
1038 slab_offset = numpy.asarray(slab_offset,'int64')
1039 slab_shape = numpy.asarray(slab_shape,'int64')
1040 # print("slab", offset, size, data)
1041 status = nxlib.nxiputslab64_(self.handle,pdata,
1042 slab_offset.ctypes.data_as(c_int64_p),
1043 slab_shape.ctypes.data_as(c_int64_p))
1044 if status == ERROR:
1045 raise ValueError("Could not write slab: %s" % (self._loc()))
1046
1047
1048
1049 # ==== Attributes ====
1050 nxlib.nxiinitattrdir_.restype = c_int
1051 nxlib.nxiinitattrdir_.argtypes = [c_void_p]
1052 def initattrdir(self):
1053 """
1054 Reset the getnextattr list to the first attribute.
1055
1056 Raises NeXusError if this fails.
1057
1058 Corresponds to NXinitattrdir(handle)
1059 """
1060 status = nxlib.nxiinitattrdir_(self.handle)
1061 if status == ERROR:
1062 raise NeXusError("Could not reset attribute list: %s" %
1063 (self._loc()))
1064
1065 nxlib.nxigetattrinfo_.restype = c_int
1066 nxlib.nxigetattrinfo_.argtypes = [c_void_p, c_int_p]
1067 def getattrinfo(self):
1068 """
1069 Returns the number of attributes for the currently open
1070 group/data object. Do not call getnextattr() more than
1071 this number of times.
1072
1073 Raises NeXusError if this fails.
1074
1075 Corresponds to NXgetattrinfo(handl, &n)
1076 """
1077 n = c_int(0)
1078 status = nxlib.nxigetattrinfo_(self.handle,_ref(n))
1079 if status == ERROR:
1080 raise NeXusError("Could not get attr info: %s" % (self._loc()))
1081 # print("num attrs", n.value)
1082 return n.value
1083
1084 nxlib.nxigetnextattr_.restype = c_int
1085 nxlib.nxigetnextattr_.argtypes = [c_void_p, c_char_p, c_int_p, c_int_p]
1086 def getnextattr(self):
1087 """
1088 Returns the name, length, and data type for the next attribute.
1089 Call getattrinfo to determine the number of attributes before
1090 calling getnextattr. Data type is returned as a string. See
1091 getinfo for details. Length is the number of elements in the
1092 attribute.
1093
1094 Raises NeXusError if NeXus returns ERROR or EOD.
1095
1096 Corresponds to NXgetnextattr(handle,name,&length,&storage)
1097 but with storage converted from HDF values to numpy compatible
1098 strings.
1099
1100 Note: NeXus API documentation seems to say that length is the number
1101 of bytes required to store the entire attribute.
1102 """
1103 name = ctypes.create_string_buffer(MAXNAMELEN)
1104 length = c_int(0)
1105 storage = c_int(0)
1106 status = nxlib.nxigetnextattr_(self.handle,name,_ref(length),_ref(storage))
1107 if status == EOD:
1108 return (None, None, None)
1109 if status == ERROR or status == EOD:
1110 raise NeXusError("Could not get next attr: %s" % (self._loc()))
1111 dtype = _pytype_code[storage.value]
1112 # print("getnextattr", name.value, length.value, dtype)
1113 return self._bytes2str(name.value), length.value, dtype
1114
1115 # TODO: Resolve discrepency between NeXus API documentation and
1116 # TODO: apparent behaviour for getattr/putattr length.
1117 nxlib.nxigetattr_.restype = c_int
1118 nxlib.nxigetattr_.argtypes = [c_void_p, c_char_p, c_void_p, c_int_p, c_int_p]
1119 def getattr(self, name, length, dtype):
1120 """
1121 Returns the value of the named attribute. Requires length and
1122 data type from getnextattr to allocate the appropriate amount of
1123 space for the attribute.
1124
1125 Corresponds to NXgetattr(handle,name,data,&length,&storage)
1126 """
1127 if dtype == 'char': length += 1 # HDF4 needs zero-terminator
1128 dummy_data,pdata,size,datafn = self._poutput(str(dtype),[length])
1129 storage = c_int(_nxtype_code[str(dtype)])
1130 # print("getattr", self._loc(), name, length, size, dtype)
1131 size = c_int(size)
1132 status = nxlib.nxigetattr_(self.handle,self._str2bytes(name),
1133 pdata,_ref(size),_ref(storage))
1134 if status == ERROR:
1135 raise ValueError("Could not read attr %s: %s" % (name, self._loc()))
1136 # print("getattr", self._loc(), name, datafn())
1137 return datafn()
1138
1139 nxlib.nxiputattr_.restype = c_int
1140 nxlib.nxiputattr_.argtypes = [c_void_p, c_char_p, c_void_p, c_int, c_int]
1141 def putattr(self, name, value, dtype = None):
1142 """
1143 Saves the named attribute. The attribute value is a string
1144 or a scalar.
1145
1146 Raises TypeError if the value type is incorrect.
1147 Raises NeXusError if the attribute could not be saved.
1148
1149 Corresponds to NXputattr(handle,name,data,length,storage)
1150
1151 Note length is the number of elements to write rather
1152 than the number of bytes to write.
1153 """
1154 # Establish attribute type
1155 if dtype == None:
1156 # Type is inferred from value
1157 if hasattr(value,'dtype'):
1158 dtype = str(value.dtype)
1159 elif _is_string_like(value):
1160 dtype = 'char'
1161 else:
1162 value = numpy.array(value)
1163 dtype = str(value.dtype)
1164 else:
1165 # Set value to type
1166 dtype = str(dtype)
1167 if dtype == 'char' and not _is_string_like(value):
1168 raise TypeError("Expected string for 'char' attribute value")
1169 if dtype != 'char':
1170 value = numpy.array(value,dtype=dtype)
1171
1172 # Determine shape
1173 if dtype == 'char':
1174 length = len(value)
1175 data = value
1176 elif numpy.prod(value.shape) != 1:
1177 # NAPI silently ignores attribute arrays
1178 raise TypeError("Attribute value must be scalar or string")
1179 else:
1180 length = 1
1181 data = value.ctypes.data
1182
1183 # Perform the call
1184 storage = c_int(_nxtype_code[dtype])
1185 status = nxlib.nxiputattr_(self.handle,self._str2bytes(name),
1186 data,length,storage)
1187 if status == ERROR:
1188 raise NeXusError("Could not write attr %s: %s" %
1189 (name, self._loc()))
1190
1191 def getattrs(self):
1192 """
1193 Returns a dicitonary of the attributes on the current node.
1194
1195 This is a second form of attrs(self).
1196 """
1197 result = {}
1198 for (name, value) in self.attrs():
1199 result[name] = value
1200 return result
1201
1202 def attrs(self):
1203 """
1204 Iterate over attributes.
1205
1206 for name,value in file.attrs():
1207 process(name,value)
1208
1209 This automatically reads the attributes of the group/data. Do not
1210 change the active group/data while processing the list.
1211
1212 This does not correspond to an existing NeXus API function, but
1213 combines the work of attrinfo/initattrdir/getnextattr/getattr.
1214 """
1215 self.initattrdir()
1216 n = self.getattrinfo()
1217 for dummy in range(n):
1218 name,length,dtype = self.getnextattr()
1219 value = self.getattr(name,length,dtype)
1220 yield name,value
1221
1222 # ==== Linking ====
1223 nxlib.nxigetgroupid_.restype = c_int
1224 nxlib.nxigetgroupid_.argtypes = [c_void_p, c_NXlink_p]
1225 def getgroupID(self):
1226 """
1227 Return the id of the current group so we can link to it later.
1228
1229 Raises NeXusError
1230
1231 Corresponds to NXgetgroupID(handle, &ID)
1232 """
1233 ID = _NXlink()
1234 status = nxlib.nxigetgroupid_(self.handle,_ref(ID))
1235 if status == ERROR:
1236 raise NeXusError("Could not link to group: %s" % (self._loc()))
1237 return ID
1238
1239 nxlib.nxigetdataid_.restype = c_int
1240 nxlib.nxigetdataid_.argtypes = [c_void_p, c_NXlink_p]
1241 def getdataID(self):
1242 """
1243 Return the id of the current data so we can link to it later.
1244
1245 Raises NeXusError
1246
1247 Corresponds to NXgetdataID(handle, &ID)
1248 """
1249 ID = _NXlink()
1250 status = nxlib.nxigetdataid_(self.handle,_ref(ID))
1251 if status == ERROR:
1252 raise NeXusError("Could not link to data: %s" % (self._loc()))
1253 return ID
1254
1255 nxlib.nximakelink_.restype = c_int
1256 nxlib.nximakelink_.argtypes = [c_void_p, c_NXlink_p]
1257 def makelink(self, ID):
1258 """
1259 Link the previously captured group/data ID into the currently
1260 open group.
1261
1262 Raises NeXusError
1263
1264 Corresponds to NXmakelink(handle, &ID)
1265 """
1266 status = nxlib.nximakelink_(self.handle,_ref(ID))
1267 if status == ERROR:
1268 raise NeXusError("Could not make link: %s" % (self._loc()))
1269
1270 nxlib.nximakenamedlink_.restype = c_int
1271 nxlib.nximakenamedlink_.argtypes = [c_void_p, c_char_p, c_NXlink_p]
1272 def makenamedlink(self,name,ID):
1273 """
1274 Link the previously captured group/data ID into the currently
1275 open group, but under a different name.
1276
1277 Raises NeXusError
1278
1279 Corresponds to NXmakenamedlink(handle,name,&ID)
1280 """
1281 status = nxlib.nximakenamedlink_(self.handle,self._str2bytes(name),
1282 _ref(ID))
1283 if status == ERROR:
1284 raise NeXusError("Could not make link %s: %s" % (name, self._loc()))
1285
1286 nxlib.nxisameid_.restype = c_int
1287 nxlib.nxisameid_.argtypes = [c_void_p, c_NXlink_p, c_NXlink_p]
1288 def sameID(self, ID1, ID2):
1289 """
1290 Return True of ID1 and ID2 point to the same group/data.
1291
1292 This should not raise any errors.
1293
1294 Corresponds to NXsameID(handle,&ID1,&ID2)
1295 """
1296 status = nxlib.nxisameid_(self.handle, _ref(ID1), _ref(ID2))
1297 return status == OK
1298
1299 nxlib.nxiopensourcegroup_.restype = c_int
1300 nxlib.nxiopensourcegroup_.argtyps = [c_void_p]
1301 def opensourcegroup(self):
1302 """
1303 If the current node is a linked to another group or data, then
1304 open the group or data that it is linked to.
1305
1306 Note: it is unclear how can we tell if we are linked, other than
1307 perhaps the existence of a 'target' attribute in the current item.
1308
1309 Raises NeXusError.
1310
1311 Corresponds to NXopensourcegroup(handle)
1312 """
1313 status = nxlib.nxiopensourcegroup_(self.handle)
1314 if status == ERROR:
1315 raise NeXusError("Could not open source group: %s" % (self._loc()))
1316
1317 def link(self):
1318 """
1319 Returns the item which the current item links to, or None if the
1320 current item is not linked. This is equivalent to scanning the
1321 attributes for target and returning it if target is not equal
1322 to self.
1323
1324 This does not correspond to an existing NeXus API function, but
1325 combines the work of attrinfo/initattrdir/getnextattr/getattr.
1326 """
1327 n = self.getattrinfo()
1328 self.initattrdir()
1329 for dummy in range(n):
1330 name,length,dtype = self.getnextattr()
1331 if name == "target":
1332 target = self.getattr(name,length,dtype)
1333 # print("target %s, path %s" % (target,self.path))
1334 if target != self.path:
1335 return target
1336 else:
1337 return None
1338 return None
1339
1340 # ==== External linking ====
1341 nxlib.nxiinquirefile_.restype = c_int
1342 nxlib.nxiinquirefile_.argtypes = [c_void_p, c_char_p, c_int]
1343 def inquirefile(self, maxnamelen=MAXPATHLEN):
1344 """
1345 Return the filename for the current file. This may be different
1346 from the file that was opened (file.filename) if the current
1347 group is an external link to another file.
1348
1349 Raises NeXusError if this fails.
1350
1351 Corresponds to NXinquirefile(&handle,file,len)
1352 """
1353 filename = ctypes.create_string_buffer(maxnamelen)
1354 status = nxlib.nxiinquirefile_(self.handle,filename,maxnamelen)
1355 if status == ERROR:
1356 raise NeXusError("Could not determine filename: %s" % (self._loc()))
1357 return self._bytes2str(filename.value)
1358
1359 nxlib.nxilinkexternal_.restype = c_int
1360 nxlib.nxilinkexternal_.argtyps = [c_void_p, c_char_p,
1361 c_char_p, c_char_p]
1362 def linkexternal(self, name, nxclass, url):
1363 """
1364 Return the filename for the external link if there is one,
1365 otherwise return None.
1366
1367 Raises NeXusError if link fails.
1368
1369 Corresponds to NXisexternalgroup(&handle,name,nxclass,file,len)
1370 """
1371 status = nxlib.nxilinkexternal_(self.handle,
1372 self._str2bytes(name),
1373 self._str2bytes(nxclass),
1374 self._str2bytes(url))
1375 if status == ERROR:
1376 raise NeXusError("Could not link %s to %s: %s" %
1377 (name, url, self._loc()))
1378
1379 nxlib.nxiisexternalgroup_.restype = c_int
1380 nxlib.nxiisexternalgroup_.argtyps = [c_void_p, c_char_p,
1381 c_char_p, c_char_p, c_int]
1382 def isexternalgroup(self, name, nxclass, maxnamelen=MAXPATHLEN):
1383 """
1384 Return the filename for the external link if there is one,
1385 otherwise return None.
1386
1387 Corresponds to NXisexternalgroup(&handle,name,nxclass,file,len)
1388 """
1389 url = ctypes.create_string_buffer(maxnamelen)
1390 status = nxlib.nxiisexternalgroup_(self.handle,
1391 self._str2bytes(name),
1392 self._str2bytes(nxclass),
1393 url,
1394 maxnamelen)
1395 if status == ERROR:
1396 return None
1397 else:
1398 return self._bytes2str(url.value)
1399
1400 # ==== Utility functions ====
1401 def _loc(self):
1402 """
1403 Return file location as string filename(path)
1404
1405 This is an extension to the NeXus API.
1406 """
1407 return "%s(%s)"%(self.filename,self.path)
1408
1409 def _poutput(self, dtype, shape):
1410 """
1411 Build space to collect a nexus data element.
1412 Returns data,pdata,size,datafn where
1413 - data is a python type to hold the returned data
1414 - pdata is the pointer to the start of the data
1415 - size is the number of bytes in the data block
1416 - datafn is a lamba expression to extract the return value from data
1417 Note that datafn can return a string, a scalar or an array depending
1418 on the data type and shape of the data group.
1419 """
1420 if isinstance(shape, int):
1421 shape = [shape]
1422 if len(shape) == 1 and dtype == 'char':
1423 # string - use ctypes allocator
1424 size = int(shape[0])
1425 data = ctypes.create_string_buffer(size)
1426 pdata = data
1427 datafn = lambda: data.value
1428 else:
1429 # scalar, array or string list - use numpy array
1430 if dtype=='char':
1431 data = numpy.zeros(shape[:-1], dtype='S%i'%shape[-1])
1432 else:
1433 data = numpy.zeros(shape, dtype)
1434 if len(shape) == 1 and shape[0] == 1:
1435 datafn = lambda: data[0]
1436 else:
1437 datafn = lambda: data
1438 pdata = data.ctypes.data
1439 size = data.nbytes
1440 return data,pdata,size,datafn
1441
1442 def _pinput(self, data, dtype, shape):
1443 """
1444 Convert an input array to a C pointer to a dense array.
1445
1446 Returns data, pdata where
1447 - data is a possibly new copy of the array
1448 - pdata is a pointer to the beginning of the array.
1449 Note that you must hold a reference to data for as long
1450 as you need pdata to keep the memory from being released to the heap.
1451 """
1452 if isinstance(shape, int):
1453 shape = [shape]
1454 if dtype == "char":
1455 data = numpy.asarray(data, dtype='S%d'%(shape[-1]))
1456 else:
1457 # Convert scalars to vectors of length one
1458 if numpy.prod(shape) == 1 and not hasattr(data,'shape'):
1459 data = numpy.array([data], dtype=dtype)
1460 # Check that dimensions match
1461 # Ick! need to exclude dimensions of length 1 in order to catch
1462 # array slices such as a[:,1], which only report one dimension
1463 input_shape = numpy.array([i for i in data.shape if i != 1])
1464 target_shape = numpy.array([i for i in shape if i != 1])
1465 if len(input_shape) != len(target_shape) \
1466 or (input_shape != target_shape).any():
1467 raise ValueError("Shape mismatch %s!=%s: %s" %
1468 (data.shape, shape, self._loc()))
1469 # Check data type
1470 if str(data.dtype) != dtype:
1471 raise ValueError("Type mismatch %s!=%s: %s" %
1472 (dtype, data.dtype, self._loc()))
1473
1474 data = numpy.ascontiguousarray(data)
1475 pdata = data.ctypes.data
1476
1477 return data,pdata
1478
1479 def show(self, path=None, indent=0):
1480 """
1481 Print the structure of a NeXus file from the current node.
1482
1483 TODO: Break this into a tree walker and a visitor.
1484 """
1485 oldpath = self.path
1486 self.openpath(path)
1487
1488 print("=== File", self.inquirefile(), path)
1489 self._show(indent=indent)
1490 self.openpath(oldpath)
1491
1492 def _show(self, indent=0):
1493 """
1494 Print the structure of a NeXus file from the current node.
1495
1496 TODO: Break this into a tree walker and a visitor.
1497 """
1498 prefix = ' '*indent
1499 link = self.link()
1500 if link:
1501 print("%(prefix)s-> %(link)s" % locals())
1502 return
1503 for attr,value in self.attrs():
1504 print("%(prefix)s@%(attr)s: %(value)s" % locals())
1505 for name,nxclass in self.entries():
1506 if nxclass == "SDS":
1507 shape,dtype = self.getinfo()
1508 dims = "x".join([str(x) for x in shape])
1509 print("%(prefix)s%(name)s %(dtype)s %(dims)s" % locals())
1510 link = self.link()
1511 if link:
1512 print(" %(prefix)s-> %(link)s" % locals())
1513 else:
1514 for attr,value in self.attrs():
1515 print(" %(prefix)s@%(attr)s: %(value)s" % locals())
1516 if numpy.prod(shape) < 8:
1517 value = self.getdata()
1518 print(" %s%s"%(prefix,str(value)))
1519 else:
1520 print("%(prefix)s%(name)s %(nxclass)s" % locals())
1521 self._show(indent=indent+2)
1522
1523
1524 __id__ = "$ID$"