Parameters
    ----------
    h5file:
        h5py file to be written to
    path:
        path within h5py file to saved dictionary
    dic:
        python dictionary to be converted to hdf5 format
966006
def recursively_save_dict_contents_to_group(h5file, path, dic):
    
    for key, item in dic.items():
        if isinstance(item, (np.ndarray, np.int64, np.float64, str, bytes, tuple, list)):
            h5file[path + str(key)] = item
        elif isinstance(item, dict):
            recursively_save_dict_contents_to_group(h5file, path + key + '/', item)
        else:
            raise ValueError('Cannot save %s type' % type(item))
1273076
def to_dict(self, info_filename, tree_filename, dash_f_e=False):
        
        logger.debug('info_filename: {} {}'
                     .format(info_filename, '(FOUND)' if os.path.exists(info_filename) else '(NOT FOUND)'))
        logger.debug('tree_filename: {} {}'
                     .format(tree_filename, '(FOUND)' if os.path.exists(tree_filename) else '(NOT FOUND)'))
        if dash_f_e:
            return self._dash_f_e_to_dict(info_filename, tree_filename)
        else:
            return self._to_dict(info_filename, tree_filename)
868647
def hdf5_read_in(self):
        

        with h5py.File(self.WORKING_DIRECTORY + '/' + self.file_name) as f:

            # read in
            data = f['data']

            # find number of distinct x and y points.
            num_x_pts = len(np.unique(data[self.x_column_label][:]))
            num_y_pts = len(np.unique(data[self.y_column_label][:]))

            # create 2D arrays of x,y,z
            self.xvals = np.reshape(data[self.x_column_label][:], (num_y_pts, num_x_pts))
            self.yvals = np.reshape(data[self.y_column_label][:], (num_y_pts, num_x_pts))
            self.zvals = np.reshape(data[self.z_column_label][:], (num_y_pts, num_x_pts))
        return
1228024
def save(yaml_dict, filepath):
    '''
    
    '''
    yamldict.dump(yaml_dict, open(filepath, 'w'), default_flow_style=False)
200580
def smartDumpDictHdf5(RV,o):
    
    for key in list(RV.keys()):
        if type(RV[key])==dict:
            g = o.create_group(key)
            smartDumpDictHdf5(RV[key],g)
        else:
            o.create_dataset(name=key,data=SP.array(RV[key]),chunks=True,compression='gzip')
469866
def write_to_file(self,
                      data_dict,
                      output_file_path):
        

        log.info("saving={}".format(output_file_path))
        with open(output_file_path, "w") as output_file:
            output_file.write(str(ppj(data_dict)))
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')
851282
def export(self, file_path=None, export_format=None):
        
        with io.open(file_path, mode='w', encoding="utf-8") as export_file:
            if export_format == 'yaml':
                import yaml
                yaml.safe_dump(self.to_dict(), export_file, default_flow_style=False)
            elif export_format == 'json':
                export_file.write(text_type(json.dumps(self.to_dict(), ensure_ascii=False)))
            return True
493339
def load_configuration(self, configuration_file):
        '''
        '''
        if os.path.isfile(configuration_file):
            if not isinstance(configuration_file, tb.file.File) and os.path.splitext(configuration_file)[1].strip().lower() != ".h5":
                load_configuration_from_text_file(self, configuration_file)
            else:
                load_configuration_from_hdf5(self, configuration_file)
        else:
            raise ValueError('Cannot find configuration file specified: %s' % configuration_file)
873918
def h5features_convert(self, infile):
        """"""
        with h5py.File(infile, 'r') as f:
            groups = list(f.keys())
        for group in groups:
            self._writer.write(
                Reader(infile, group).read(),
                self.groupname, append=True)
397144
def save_data(fpath, data, **kwargs):
    
    ext = splitext(fpath)[1]
    if ext in ['.pickle', '.cPkl', '.pkl']:
        return save_cPkl(fpath, data, **kwargs)
    elif ext in ['.json']:
        return save_json(fpath, data, **kwargs)
    elif ext in ['.hdf5']:
        return save_hdf5(fpath, data, **kwargs)
    elif ext in ['.txt']:
        return save_text(fpath, **kwargs)
    elif HAS_NUMPY and ext in ['.npz', '.npy']:
        return save_numpy(fpath, data, **kwargs)
    else:
        assert False, 'unknown ext=%r for fpath=%r' % (ext, fpath)
840762
def parse_config(h5path):
        """"""
        with h5py.File(h5path, mode="r") as fh5:
            h5attrs = dict(fh5.attrs)

        # Convert byte strings to unicode strings
        # https://github.com/h5py/h5py/issues/379
        for key in h5attrs:
            if isinstance(h5attrs[key], bytes):
                h5attrs[key] = h5attrs[key].decode("utf-8")

        config = Configuration()
        for key in h5attrs:
            section, pname = key.split(":")
            if pname not in dfn.config_funcs[section]:
                # Add the value as a string but issue a warning
                config[section][pname] = h5attrs[key]
                msg = "Unknown key '{}' in section [{}]!".format(
                    pname, section)
                warnings.warn(msg, UnknownKeyWarning)
            else:
                typ = dfn.config_funcs[section][pname]
                config[section][pname] = typ(h5attrs[key])
        return config
783503
def write_injections(self, injection_file):
        
        try:
            with h5py.File(injection_file, "r") as fp:
                super(BaseInferenceFile, self).copy(fp, self.injections_group)
        except IOError:
            logging.warn("Could not read %s as an HDF file", injection_file)
423470
def load_dict_from_yaml(path):
    
    f = file(path, 'r')
    dictionary = yaml.load(f)
    f.close()
    return dictionary
975505
def read_hdf5_dict(h5f, names=None, path=None, on_missing='error', **kwargs):
    
    if path:
        h5f = h5f[path]

    # allow alternative keyword argument name (FIXME)
    if names is None:
        names = kwargs.pop('flags', None)

    # try and get list of names automatically
    if names is None:
        try:
            names = find_flag_groups(h5f, strict=True)
        except KeyError:
            names = None
        if not names:
            raise ValueError("Failed to automatically parse available flag "
                             "names from HDF5, please give a list of names "
                             "to read via the ``names=`` keyword")

    # read data
    out = DataQualityDict()
    for name in names:
        try:
            out[name] = read_hdf5_flag(h5f, name, **kwargs)
        except KeyError as exc:
            if on_missing == 'ignore':
                pass
            elif on_missing == 'warn':
                warnings.warn(str(exc))
            else:
                raise ValueError('no H5Group found for flag '
                                 '{0!r}'.format(name))

    return out
1307286
def load(path, variable='Datamat'):
    
    f = h5py.File(path,'r')
    try:
        dm = fromhdf5(f[variable])
    finally:
        f.close()
    return dm
295716
def _guess_format(path):
    
    if os.path.isdir(path):
        return 'dir-npy'

    if path.endswith('.h5') or path.endswith('.hdf5'):
        # TODO: Check for mdtraj .h5 file
        return 'hdf5'

    # TODO: What about a list of trajectories, e.g. from command line nargs='+'
    return 'mdtraj'