Debian Codegraph @

nxs/napi.py

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