Load an object from an HDF5 file.

        Requires ``h5py``.

        Parameters
        ----------
        f : str, :class:`h5py.File`
            Either the filename or an open HDF5 file.
176180
def from_hdf5(cls, f):
        
        # TODO: this is duplicated code from PhaseSpacePosition
        if isinstance(f, str):
            import h5py
            f = h5py.File(f)

        pos = quantity_from_hdf5(f['pos'])
        vel = quantity_from_hdf5(f['vel'])

        time = None
        if 'time' in f:
            time = quantity_from_hdf5(f['time'])

        frame = None
        if 'frame' in f:
            g = f['frame']

            frame_mod = g.attrs['module']
            frame_cls = g.attrs['class']
            frame_units = [u.Unit(x.decode('utf-8')) for x in g['units']]

            if u.dimensionless_unscaled in frame_units:
                units = DimensionlessUnitSystem()
            else:
                units = UnitSystem(*frame_units)

            pars = dict()
            for k in g['parameters']:
                pars[k] = quantity_from_hdf5(g['parameters/'+k])

            exec("from {0} import {1}".format(frame_mod, frame_cls))
            frame_cls = eval(frame_cls)

            frame = frame_cls(units=units, **pars)

        potential = None
        if 'potential' in f:
            import yaml
            from ..potential.potential.io import from_dict
            _dict = yaml.load(f['potential'][()].decode('utf-8'))
            potential = from_dict(_dict)

        return cls(pos=pos, vel=vel, t=time,
                   frame=frame, potential=potential)
352899
def load(cls, filename, format=None):
        
        if format is None:
            # try to derive protocol from file extension
            format = format_from_extension(filename)
        with file(filename, 'rbU') as fp:
            obj = cls.load_from_file_object(fp, format)
            obj.filename = filename
            return obj
817096
def h5ToDict(h5, readH5pyDataset=True):
    
    h = h5py.File(h5, "r")
    ret = unwrapArray(h, recursive=True, readH5pyDataset=readH5pyDataset)
    if readH5pyDataset: h.close()
    return ret
512191
def load(self, fn_):
        '''
        
        '''
        data = fn_.read()
        fn_.close()
        if data:
            if six.PY3:
                return self.loads(data, encoding='utf-8')
            else:
                return self.loads(data)
1334760
def load(self):
        
        hdf_filename = os.path.join(self._dump_dirname, 'result.h5')
        if os.path.isfile(hdf_filename):
            store = pd.HDFStore(hdf_filename, mode='r')
            keys = store.keys()
            if keys == ['/df']:
                self.result = store['df']
            else:
                if set(keys) == set(map(lambda i: '/%s' % i, range(len(keys)))):
                    # keys are not necessarily ordered
                    self.result = [store[str(k)] for k in range(len(keys))]
                else:
                    self.result = {k[1:]: store[k] for k in keys}

        else:
            self.result = joblib.load(
                    os.path.join(self._output_dirname, 'dump', 'result.pkl'))
314104
def from_file(cls, f):
        

        with open_file_like(f, 'r') as fp:
            return cls(json.load(fp))
714061
def load(cls, folder):
        
        popset = PopulationSet.load_hdf(os.path.join(folder,'popset.h5'))
        sigfile = os.path.join(folder,'trsig.pkl')
        with open(sigfile, 'rb') as f:
            trsig = pickle.load(f)
        return cls(trsig, popset, folder=folder)
730656
def load_file_or_hdu(filename):
    
    if isinstance(filename, fits.HDUList):
        hdulist = filename
    else:
        hdulist = fits.open(filename, ignore_missing_end=True)
    return hdulist
834379
def read_hdf(filename: PathLike, key: str) -> AnnData:
    
    with h5py.File(filename, 'r') as f:
        # the following is necessary in Python 3, because only
        # a view and not a list is returned
        keys = [k for k in f.keys()]
        if key == '':
            raise ValueError((
                'The file {} stores the following sheets:\n{}\n'
                'Call read/read_hdf5 with one of them.'
            ).format(filename, keys))
        # read array
        X = f[key][()]
        # try to find row and column names
        rows_cols = [{}, {}]
        for iname, name in enumerate(['row_names', 'col_names']):
            if name in keys:
                rows_cols[iname][name] = f[name][()]
    adata = AnnData(X, rows_cols[0], rows_cols[1], dtype=X.dtype.name)
    return adata
856057
def load_data(fpath, **kwargs):
    
    ext = splitext(fpath)[1]
    if ext in ['.pickle', '.cPkl', '.pkl']:
        return load_cPkl(fpath, **kwargs)
    elif ext in ['.json']:
        return load_json(fpath, **kwargs)
    elif ext in ['.hdf5']:
        return load_hdf5(fpath, **kwargs)
    elif ext in ['.txt']:
        return load_text(fpath, **kwargs)
    elif HAS_NUMPY and ext in ['.npz', '.npy']:
        return load_numpy(fpath, **kwargs)
    else:
        assert False, 'unknown ext=%r for fpath=%r' % (ext, fpath)
204094
def from_file(cls, h5_file):
        
        return cls({
            country: HDF5DailyBarReader.from_file(h5_file, country)
            for country in h5_file.keys()
        })
1256964
def to_hdf5(self, f):
        

        f = super(Orbit, self).to_hdf5(f)

        if self.potential is not None:
            import yaml
            from ..potential.potential.io import to_dict
            f['potential'] = yaml.dump(to_dict(self.potential)).encode('utf-8')

        if self.t:
            quantity_to_hdf5(f, 'time', self.t)

        return f
1368251
def setupimgh5(f: Union[Path, h5py.File],
               Nframetotal: int, Nrow: int, Ncol: int, dtype=np.uint16,
               writemode='r+', key='/rawimg', cmdlog: str=None):
    
    if isinstance(f, (str, Path)):  # assume new HDF5 file wanted
        f = Path(f).expanduser()
        if f.is_dir():
            raise IOError(
                'must provide specific HDF5 filename, not just a directory')

        print('creating', f)
        with h5py.File(f, writemode) as F:
            setupimgh5(F, Nframetotal, Nrow, Ncol, dtype, writemode, key)

    elif isinstance(f, h5py.File):
        h = f.create_dataset(key,
                             shape=(Nframetotal, Nrow, Ncol),
                             dtype=dtype,
                             chunks=(1, Nrow, Ncol),  # each image is a chunk
                             compression='gzip',
                             # no difference in filesize from 1 to 5, except much faster to use lower numbers!
                             compression_opts=1,
                             shuffle=True,
                             fletcher32=True,
                             track_times=True)
        h.attrs["CLASS"] = np.string_("IMAGE")
        h.attrs["IMAGE_VERSION"] = np.string_("1.2")
        h.attrs["IMAGE_SUBCLASS"] = np.string_("IMAGE_GRAYSCALE")
        h.attrs["DISPLAY_ORIGIN"] = np.string_("LL")
        h.attrs['IMAGE_WHITE_IS_ZERO'] = np.uint8(0)

        if cmdlog and isinstance(cmdlog, str):
            f['/cmdlog'] = cmdlog
    else:
        raise TypeError(
            f'{type(f)} is not correct, must be filename or h5py.File HDF5 file handle')
857308
def h5fmem(**kwargs):
    """"""

    # need a file name even tho nothing is ever written
    fn = tempfile.mktemp()

    # file creation args
    kwargs['mode'] = 'w'
    kwargs['driver'] = 'core'
    kwargs['backing_store'] = False

    # open HDF5 file
    h5f = h5py.File(fn, **kwargs)

    return h5f
909726
def load_from_file(self, fname):
        
        with open(fname, 'r') as f:
            for line in f:
                k,v = line.split(' = ')
                self._parse_char_line_to_self(k,v)
50335
def from_file(cls, fn, *args, **kwargs):
        
        return AmiraHeader(get_parsed_data(fn, *args, **kwargs))
54259
def dict_to_hdf5(dict_like, h5group):
    
    # Write attributes
    for key, value in dict_like.items():
        if value is not None:
            h5group.attrs[str(key)] = value