Debian Codegraph @

nxs/napi.py

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