Debian Codegraph @

nxs/napi.py

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