How to use the h5py.SoftLink function in h5py

To help you get started, we’ve selected a few h5py examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github cctbx / cctbx_project / xfel / euxfel / agipd_cxigeom2nexus.py View on Github external
quad_slow = slow // self.n_quads
      module_fast = quad_fast
      module_slow = quad_slow // self.n_modules
      asic_fast = module_fast
      asic_slow = module_slow // self.n_asics

    detector = instrument.create_group('ELE_D0')
    detector.attrs['NX_class']  = 'NXdetector'
    if 'mask' in h5py.File(self.params.cxi_file, 'r')['entry_1/data_1']:
      detector.create_dataset('pixel_mask_applied', (1,), data=[True], dtype='uint32')
      detector['pixel_mask'] = h5py.ExternalLink(self.params.cxi_file, "entry_1/data_1/mask")
    array_name = 'ARRAY_D0'

    alias = 'data'
    data_name = 'data'
    detector[alias] = h5py.SoftLink('/entry/data/%s'%data_name)

    for quad in range(self.n_quads):
      q_key = "q%d"%quad
      q_name = 'AXIS_D0Q%d'%quad
      quad_vector = self.hierarchy[q_key].local_origin.elems
      self.create_vector(transformations, q_name, 0.0, depends_on='AXIS_D0', equipment='detector', equipment_component='detector_quad',transformation_type='rotation', units='degrees', vector=(0., 0., -1.), offset = quad_vector, offset_units = 'mm')
      for module_num in range(self.n_modules):
        m_key = "p%d"%((quad*self.n_modules)+module_num)
        m_name = 'AXIS_D0Q%dM%d'%(quad, module_num)
        module_vector = self.hierarchy[q_key][m_key].local_origin.elems
        self.create_vector(transformations, m_name, 0.0, depends_on=q_name, equipment='detector', equipment_component='detector_module',transformation_type='rotation', units='degrees', vector=(0., 0., -1.), offset = module_vector, offset_units = 'mm')

        for asic_num in range(self.n_asics):
          a_key = "p%da%d"%((quad*self.n_modules)+module_num, asic_num)
          a_name = 'AXIS_D0Q%dM%dA%d'%(quad, module_num, asic_num)
          asic_vector = self.hierarchy[q_key][m_key][a_key]['local_origin'].elems
github HDFGroup / hdf5-json / h5json / hdf5db.py View on Github external
def createSoftLink(self, parentUUID, linkPath, link_name):
        self.initFile()
        if self.readonly:
            msg = "Unable to create link (Updates are not allowed)"
            self.log.info(msg)
            raise IOError(errno.EPERM, msg)
        parentObj = self.getGroupObjByUuid(parentUUID)
        if parentObj is None:
            msg = "Unable to create link, parent UUID: " + parentUUID + " not found"
            self.log.info(msg)
            raise IOError(errno.ENXIO, msg)
        if link_name in parentObj:
            # link already exists
            self.log.info("linkname already exists, deleting")
            del parentObj[link_name]  # delete old link
        parentObj[link_name] = h5py.SoftLink(linkPath)

        now = time.time()
        self.setCreateTime(parentUUID, objType="link", name=link_name, timestamp=now)
        self.setModifiedTime(parentUUID, objType="link", name=link_name, timestamp=now)

        return True
github silx-kit / silx / silx / gui / hdf5widget.py View on Github external
attrs = {}
        if issubclass(class_, h5py.Dataset):
            attrs = dict(self.obj.attrs)
            if self.obj.shape == ():
                attrs["shape"] = "scalar"
            else:
                attrs["shape"] = self.obj.shape
            attrs["dtype"] = self.obj.dtype
            if self.obj.shape == ():
                attrs["value"] = self.obj.value
            else:
                attrs["value"] = "..."
        elif isinstance(self.obj, h5py.ExternalLink):
            attrs["linked path"] = self.obj.path
            attrs["linked file"] = self.obj.filename
        elif isinstance(self.obj, h5py.SoftLink):
            attrs["linked path"] = self.obj.path

        if len(attrs) > 0:
            tooltip = htmlFromDict(attrs)
        else:
            tooltip = ""

        return tooltip
github silx-kit / silx / silx / io / spectoh5.py View on Github external
"""
    if link_name not in h5f:
        _logger.debug("Creating link " + link_name + " -> " + target_name)
    elif overwrite_data:
        _logger.warn("Overwriting " + link_name + " with link to" +
                     target_name)
        del h5f[link_name]
    else:
        _logger.warn(link_name + " already exist. Can't create link to " +
                     target_name)
        return None

    if link_type == "hard":
        h5f[link_name] = h5f[target_name]
    elif link_type == "soft":
        h5f[link_name] = h5py.SoftLink(target_name)
    else:
        raise ValueError("link_type  must be 'hard' or 'soft'")
github FXIhub / hummingbird / examples / ptychography / write2cxi.py View on Github external
detector_1   = f['entry_1']['instrument_1']['detector_1']
        sample_1     = f['entry_1']['sample_1']
        geometry_1   = f['entry_1']['sample_1']['geometry_1']

        # Add new data fields
        f.create_dataset("cxi_version",data=140)
        source_1 = instrument_1.create_group("source_1")
        source_1.create_dataset("energy", data=photon_energy_J) # in J
        detector_1.create_dataset("distance", data=det_distance) 
        detector_1.create_dataset("x_pixel_size", data=det_pixelsize)
        detector_1.create_dataset("y_pixel_size", data=det_pixelsize)
        detector_1["translation"] = h5py.SoftLink('/entry_1/sample_1/geometry_1/translation')
        detector_1.create_dataset("corner_position", data=corner_position) 
        data_1 = entry_1.create_group("data_1")
        data_1["data"] = h5py.SoftLink('/entry_1/instrument_1/detector_1/data')
        data_1["translation"] = h5py.SoftLink('/entry_1/sample_1/geometry_1/translation')

        # These are optional data that should be provided (if known)
        # ----------------------------------------------------------
        source_1.create_dataset("illumination", data=sim.get_illumination())
        #detector_1.create_dataset("Fillumination_mask", data=illumination_intensities_mask)
        #detector_1.create_dataset("solution", data=sim.obj)
        #detector_1.create_dataset("initial_image",data=initial_image)
        
        # Close CXI file and exit
        f.close()
github HDFGroup / h5pyd / h5pyd / _apps / utillib.py View on Github external
if src_obj_id_hash in srcid_desobj_map:
                    des_obj = srcid_desobj_map[src_obj_id_hash]
                    logging.debug("creating hardlink to {}".format(des_obj.id.id))
                    gdes[title] = des_obj
                else:
                    msg = "could not find map item to src id: {}".format(src_obj_id_hash)
                    logging.warn(msg)
                    if ctx["verbose"]:
                        print("WARNING: " + msg)
        elif link_classname == "SoftLink":
            msg = "creating SoftLink({}) with title: {}".format(lnk.path, title)
            if ctx["verbose"]:
                print(msg)
            logging.info(msg)
            if is_h5py(gdes):
                soft_link = h5py.SoftLink(lnk.path)
            else:
                soft_link = h5pyd.SoftLink(lnk.path)
            gdes[title] = soft_link
        elif link_classname == "ExternalLink":
            msg = "creating ExternalLink({}, {}) with title: {}".format(lnk.filename, lnk.path, title)
            if ctx["verbose"]:
                print(msg)
            logging.info(msg)
            if is_h5py(gdes):
                ext_link = h5py.ExternalLink(lnk.filename, lnk.path)
            else:
                ext_link = h5pyd.ExternalLink(lnk.filename, lnk.path)
            gdes[title] = ext_link
        else:
            msg = "Unexpected link type: {}".format(lnk.__class__.__name__)
            logging.warning(msg)
github vasole / pymca / PyMca5 / PyMcaCore / McaStackExport.py View on Github external
dim1.attrs["long_name"] = dim1_long_name
                dim2.attrs["long_name"] = dim2_long_name
            else:
                # spectrum stack -> n_rows, n_columns, n_channels
                dim0_long_name = "y" 
                dim1_long_name = "x"
                dim2_long_name = "channels"
                dim1 = map_.require_dataset(dim1_name,
                                  shape=(data.shape[1],),
                                  dtype=numpy.float32)
                dim0 = map_.require_dataset(dim0_name,
                                  shape=(data.shape[0],),
                                  dtype=numpy.float32)
                dim0[:] = xScale[0] + xScale[1] * len(dim0)
                dim1[:] = yScale[0] + yScale[1] * len(dim1)
                map_[dim2_name] = h5py.SoftLink(h5g["channels"].name)
                dim2 = map_[dim2_name]
                dim0.attrs["long_name"] = dim0_long_name
                dim1.attrs["long_name"] = dim1_long_name
            axes = [dim0_name, dim1_name, dim2_name]
            map_.attrs["axes"] = numpy.array(axes, dtype=strdtype)

            # set the default detector plot
            att = "default"
            if att not in h5g.attrs:
                h5g.attrs[att] = u"map"
    
            # should make use of standard HDF5 scales and labeling
            # instead of (or in addition to) the NeXus approach?
            USE_HDF5_SCALES = False
            if USE_HDF5_SCALES:
                dim0.make_scale(dim0_long_name)
github vasole / pymca / PyMca5 / PyMcaIO / NexusUtils.py View on Github external
:param h5py.Group data:
    :param list(3-tuple) axes: name(str), value(None,h5py.Dataset,numpy.ndarray), attrs(dict)
    :param bool append:
    """
    raiseIsNotNxClass(data, u'NXdata')
    if append:
        newaxes = data.attrs.get('axes', [])
    else:
        newaxes = []
    for name, value, attrs in axes:
        if value is None:
            pass  # is or will be created elsewhere
        elif isinstance(value, h5py.Dataset):
            if value.parent != data:
                data[name] = h5py.SoftLink(value.name)
        elif isinstance(value, dict):
            data.create_dataset(name, **value)
        else:
            data[name] = value
        if attrs:
            data[name].attrs.update(attrs)
        newaxes.append(name)
    if newaxes:
        data.attrs['axes'] = asNxChar(newaxes)
        updated(data)