Debian Codegraph @

nxs/napi.py

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