Last active
May 27, 2021 06:37
-
-
Save xinyazhang/bb539de9545433031a31e65321dfb38d to your computer and use it in GitHub Desktop.
Show What are Stored in an .NPZ File
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| ''' | |
| Copyright © 2020, 2021 Xinya Zhang <xinyazhang@utexas.edu> | |
| Permission is hereby granted, free of charge, to any person obtaining a copy | |
| of this software and associated documentation files (the "Software"), to deal | |
| in the Software without restriction, including without limitation the rights | |
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
| copies of the Software, and to permit persons to whom the Software is | |
| furnished to do so, subject to the following conditions: | |
| The above copyright notice and this permission notice shall be included in all | |
| copies or substantial portions of the Software. | |
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
| SOFTWARE. | |
| ''' | |
| import numpy as np | |
| import h5py | |
| import lzma | |
| import io | |
| from scipy.io import loadmat,savemat | |
| import pathlib | |
| import os | |
| import sys | |
| import argparse | |
| def _load_csv(fn): | |
| return np.loadtxt(fn, delimiter=','), False | |
| def _load_hdf5(fn): | |
| return h5py.File(fn, 'r'), True | |
| def _load_xz(fn): | |
| p = pathlib.PosixPath(fn) | |
| #memfile = io.BytesIO(lzma.open(fn, 'r').read()) | |
| memfile = io.BytesIO(lzma.open(fn, 'r').read()) | |
| nest_suffix = p.with_suffix('').suffix | |
| if nest_suffix not in _SUFFIX_TO_LOADER: | |
| raise NotImplementedError("Parser for {} file is not implemented".format(p.suffix)) | |
| return _SUFFIX_TO_LOADER[nest_suffix](memfile) | |
| def _load_np(fn): | |
| return np.load(fn, allow_pickle=True), False | |
| def _loadmat(fn): | |
| try: | |
| d = loadmat(fn, verify_compressed_data_integrity=False) | |
| return d, False | |
| except: | |
| return _load_hdf5(fn) | |
| def _load_npz(fn): | |
| return np.load(fn), False | |
| def _load_txt(fn): | |
| return np.loadtxt(fn), False | |
| _SUFFIX_TO_LOADER = { | |
| '.npz': _load_npz, | |
| '.txt': _load_txt, | |
| '.csv': _load_csv, | |
| '.mat': _loadmat, | |
| '.hdf5': _load_hdf5, | |
| '.xz': _load_xz | |
| } | |
| def h5py_dataset_iterator(g, prefix=''): | |
| for key in g.keys(): | |
| item = g[key] | |
| path = '{}/{}'.format(prefix, key) | |
| if isinstance(item, h5py.Dataset): # test for dataset | |
| yield (path, item) | |
| elif isinstance(item, h5py.Group): # test for group (go down) | |
| yield from h5py_dataset_iterator(item, path) | |
| def _kv_yielder(p): | |
| sfx = p.suffix | |
| d, is_hdf5 = _SUFFIX_TO_LOADER[p.suffix](str(p)) | |
| if not is_hdf5: | |
| for k,v in d.items(): # Python 3 syntax | |
| if k.startswith('__'): | |
| continue | |
| yield k, v | |
| else: | |
| for (k, v) in h5py_dataset_iterator(d): | |
| yield k, v | |
| def kv_yielder(p, args): | |
| for k, v in _kv_yielder(p): | |
| if args.showkey: | |
| if k in args.showkey: | |
| yield k, v | |
| else: | |
| yield k, v | |
| def head(args): | |
| fns = args.files | |
| for fn in fns: | |
| try: | |
| p = pathlib.PosixPath(fn) | |
| print("==> {} <==".format(fn)) | |
| for k, v in kv_yielder(p, args): | |
| print("{}: type {} shape {}".format(k, v.dtype, v.shape)) | |
| if args.row is not None: | |
| print("\tRow {}\n{}".format(args.row, v[args.row])) | |
| elif args.show: | |
| print("\t{}".format(v)) | |
| except Exception as e: | |
| print("Error in reading {}.\nDetails {}".format(fn, e), file=sys.stderr) | |
| def main(): | |
| parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) | |
| parser.add_argument('files', help='NPZ File', nargs='+') | |
| parser.add_argument('--show', help='Show values as well as of size', action='store_true') | |
| parser.add_argument('--showkey', help='Show values as well as of size', default=[], nargs='*') | |
| parser.add_argument('--row', help='Show specific row', type=int, default=None) | |
| args = parser.parse_args() | |
| head(args) | |
| if __name__ == '__main__': | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment