B
    dk                 @   s   d Z ddlmZ ddlZddlZddlmZmZ ddl	m
Z
mZmZmZmZmZmZmZ ddl	mZ dd	lmZmZmZmZ dd
l	mZ ddl	mZ ddlmZ G dd deeZG dd dZG dd dZG dd dZdS )z>
    Implements support for high-level access to HDF5 groups.
    )contextmanagerN   )filename_decodefilename_encode   )h5h5gh5ih5oh5rh5th5lh5p)base)HLObjectMutableMappingHDF5phil	with_phil)dataset)datatype)vds_supportc                   s"  e Zd ZdZ fddZeejZe	ej
ejB  eej
ejB  d.ddZd/ddZerxd0d	d
Zed1ddZd2ddZdd Zdd Zedd Zd3ddZdd Zedd Zedd Zedd Zed d! Zed"d# Zd4d$d%Zd&d' Z d(d) Z!d*d+ Z"ed,d- Z#  Z$S )5Groupz Represents an HDF5 group.
    c          	      s8   t * t|tjstd| t | W dQ R X dS )zF Create a new Group object by binding to a low-level GroupID.
        z%s is not a GroupIDN)r   
isinstancer   ZGroupID
ValueErrorsuper__init__)selfbind)	__class__ @/var/www/html/venv/lib/python3.7/site-packages/h5py/_hl/group.pyr   "   s    zGroup.__init__Nc          	   C   s^   |dkrt  j}t> | j|dd\}}|r4tjnd}tj| j	|||d}t|S Q R X dS )a4   Create and return a new subgroup.

        Name may be absolute or relative.  Fails if the target name already
        exists.

        track_order
            Track dataset/group/attribute creation order under this group
            if True. If None use global default h5.get_config().track_order.
        NT)lcpl)r!   gcpl)
r   
get_configtrack_orderr   _er   _gcpl_crt_orderr   createid)r   namer$   r!   r"   gidr   r   r    create_group0   s    

zGroup.create_groupc       
   	   K   s   d|krt  j|d< d|kr0| |d |d< d|krJ| |d |d< t` | }|r| |}d|dkr|dd\}}| |}tj	|||||f|}t
|}	|	S Q R X dS )a9   Create a new HDF5 dataset

        name
            Name of the dataset (absolute or relative).  Provide None to make
            an anonymous dataset.
        shape
            Dataset shape.  Use "()" for scalar datasets.  Required if "data"
            isn't provided.
        dtype
            Numpy dtype or string.  If omitted, dtype('f') will be used.
            Required if "data" isn't provided; otherwise, overrides data
            array's dtype.
        data
            Provide data to initialize the dataset.  If used, you can omit
            shape and dtype arguments.

        Keyword-only arguments:

        chunks
            (Tuple or int) Chunk shape, or True to enable auto-chunking. Integers can
            be used for 1D shape.

        maxshape
            (Tuple or int) Make the dataset resizable up to this shape. Use None for
            axes you want to be unlimited. Integers can be used for 1D shape.
        compression
            (String or int) Compression strategy.  Legal values are 'gzip',
            'szip', 'lzf'.  If an integer in range(10), this indicates gzip
            compression level. Otherwise, an integer indicates the number of a
            dynamically loaded compression filter.
        compression_opts
            Compression settings.  This is an integer for gzip, 2-tuple for
            szip, etc. If specifying a dynamically loaded compression filter
            number, this must be a tuple of values.
        scaleoffset
            (Integer) Enable scale/offset filter for (usually) lossy
            compression of integer or floating-point data. For integer
            data, the value of scaleoffset is the number of bits to
            retain (pass 0 to let HDF5 determine the minimum number of
            bits necessary for lossless compression). For floating point
            data, scaleoffset is the number of digits after the decimal
            place to retain; stored values thus have absolute error
            less than 0.5*10**(-scaleoffset).
        shuffle
            (T/F) Enable shuffle filter.
        fletcher32
            (T/F) Enable fletcher32 error detection. Not permitted in
            conjunction with the scale/offset filter.
        fillvalue
            (Scalar) Use this value for uninitialized parts of the dataset.
        track_times
            (T/F) Enable dataset creation timestamps.
        track_order
            (T/F) Track attribute creation order if True. If omitted use
            global default h5.get_config().track_order.
        external
            (Iterable of tuples) Sets the external storage property, thus
            designating that the dataset will be stored in one or more
            non-HDF5 files external to the HDF5 file.  Adds each tuple
            of (name, offset, size) to the dataset's list of external files.
            Each name must be a str, bytes, or os.PathLike; each offset and
            size, an integer.  If only a name is given instead of an iterable
            of tuples, it is equivalent to [(name, 0, h5py.h5f.UNLIMITED)].
        efile_prefix
            (String) External dataset file prefix for dataset access property
            list. Does not persist in the file.
        virtual_prefix
            (String) Virtual dataset file prefix for dataset access property
            list. Does not persist in the file.
        allow_unknown_filter
            (T/F) Do not check that the requested filter is available for use.
            This should only be used with ``write_direct_chunk``, where the caller
            compresses the data before handing it to h5py.
        rdcc_nbytes
            Total size of the dataset's chunk cache in bytes. The default size
            is 1024**2 (1 MiB).
        rdcc_w0
            The chunk preemption policy for this dataset.  This must be
            between 0 and 1 inclusive and indicates the weighting according to
            which chunks which have been fully read or written are penalized
            when determining which chunks to flush from cache.  A value of 0
            means fully read or written chunks are treated no differently than
            other chunks (the preemption is strictly LRU) while a value of 1
            means fully read or written chunks are always preempted before
            other chunks.  If your application only reads or writes data once,
            this can be safely set to 1.  Otherwise, this should be set lower
            depending on how often you re-read or re-write the same data.  The
            default value is 0.75.
        rdcc_nslots
            The number of chunk slots in the dataset's chunk cache. Increasing
            this value reduces the number of cache collisions, but slightly
            increases the memory used. Due to the hashing strategy, this value
            should ideally be a prime number. As a rule of thumb, this value
            should be at least 10 times the number of chunks that can fit in
            rdcc_nbytes bytes. For maximum performance, this value should be set
            approximately 100 times that number of chunks. The default value is
            521.
        r$   efile_prefixvirtual_prefix   /r   N)r   r#   r$   r%   r   lstriprsplitrequire_groupr   Zmake_new_dsetDataset)
r   r)   shapedtypedatakwdsgroupparent_pathdsiddsetr   r   r    create_datasetC   s     c


zGroup.create_datasetc          	   C   sh   t Z | }|r@| |}d|dkr@|dd\}}| |}|j|||d}t|}W dQ R X |S )am  Create a new virtual dataset in this group.

            See virtual datasets in the docs for more information.

            name
                (str) Name of the new dataset

            layout
                (VirtualLayout) Defines the sources for the virtual dataset

            fillvalue
                The value to use where there is no data.

            r.   r   )r)   	fillvalueN)r   r%   r/   r0   r1   Zmake_datasetr   r2   )r   r)   layoutr<   r7   r8   r9   r:   r   r   r    create_virtual_dataset   s    

zGroup.create_virtual_datasetc             c   s6   ddl m} ||||| jj}|V  | ||| dS )a  Assemble a virtual dataset in this group.

            This is used as a context manager::

                with f.build_virtual_dataset('virt', (10, 1000), np.uint32) as layout:
                    layout[0] = h5py.VirtualSource('foo.h5', 'data', (1000,))

            name
                (str) Name of the new dataset
            shape
                (tuple) Shape of the dataset
            dtype
                A numpy dtype for data read from the virtual dataset
            maxshape
                (tuple, optional) Maximum dimensions if the dataset can grow.
                Use None for unlimited dimensions.
            fillvalue
                The value used where no data is available.
            r   )VirtualLayoutN)vdsr?   filefilenamer>   )r   r)   r3   r4   maxshaper<   r?   r=   r   r   r    build_virtual_dataset   s    zGroup.build_virtual_datasetFc          	   K   s`  d|kr|  |d |d< d|kr4|  |d |d< t || krZ| j|f||f|S t|trj|f}y$tj| |  |f|}t|}W n, tk
r   | | }t	d|j
j Y nX ||jkr
d|krt	d|j|f n&|d |jkr
t	d|j|d f |r0||jkrRt	d|j|f n"t||jsRt	d|j|f |S Q R X d	S )
a   Open a dataset, creating it if it doesn't exist.

        If keyword "exact" is False (default), an existing dataset must have
        the same shape and a conversion-compatible dtype to be returned.  If
        True, the shape and dtype must match exactly.

        If keyword "maxshape" is given, the maxshape and dtype must match
        instead.

        If any of the keywords "rdcc_nslots", "rdcc_nbytes", or "rdcc_w0" are
        given, they will be used to configure the dataset's chunk cache.

        Other dataset keywords (see create_dataset) may be provided, but are
        only used if a new dataset is to be created.

        Raises TypeError if an incompatible object already exists, or if the
        shape, maxshape or dtype don't match according to the above rules.
        r,   r-   z'Incompatible object (%s) already existsrC   z+Shapes do not match (existing %s vs new %s)z/Max shapes do not match (existing %s vs new %s)z6Datatypes do not exactly match (existing %s vs new %s)z7Datatypes cannot be safely cast (existing %s vs new %s)N)r%   r   r;   r   intr   Z	open_dsetr2   KeyError	TypeErrorr   __name__r3   rC   r4   numpyZcan_cast)r   r)   r3   r4   exactr6   r9   r:   r   r   r    require_dataset   s4    
zGroup.require_datasetc             K   sv   xdD ]}| |t|| qW |j }| d|  | d| dk |j|jkrh| d|j | j|f|S )a?   Create a dataset similar to `other`.

        name
            Name of the dataset (absolute or relative).  Provide None to make
            an anonymous dataset.
        other
            The dataset which the new dataset should mimic. All properties, such
            as shape, dtype, chunking, ... will be taken from it, but no data
            or attributes are being copied.

        Any dataset keywords (see create_dataset) may be provided, including
        shape and dtype, in which case the provided values take precedence over
        those from `other`.
        )	r3   r4   chunkscompressionZcompression_optsZscaleoffsetshuffleZ
fletcher32r<   Ztrack_timesr$   r   rC   )	
setdefaultgetattrr(   Zget_create_plistZget_obj_track_timesZget_attr_creation_orderrC   r3   r;   )r   r)   otherZkwupdatekZdcplr   r   r    create_dataset_like-  s    

zGroup.create_dataset_likec          	   C   sH   t : || kr| |S | | }t|ts:td|jj |S Q R X dS )zReturn a group, creating it if it doesn't exist.

        TypeError is raised if something with that name already exists that
        isn't a group.
        z'Incompatible object (%s) already existsN)r   r+   r   r   rG   r   rH   )r   r)   grpr   r   r    r1   M  s    

zGroup.require_groupc             C   s   t |tjr,t|| j}|dkrhtdn<t |ttfrVtj	| j| 
|| jd}ntdt|t|}|tjkrt|S |tjkrtj|| jjdkdS |tjkrt|S tddS )z Open an object in the file NzInvalid HDF5 object reference)laplz3Accessing a group is done with bytes or str, not {}r)readonlyzUnknown object type)r   r   Z	Referencedereferencer(   r   bytesstrr
   openr%   _laplrG   formattyper	   get_typeZGROUPr   ZDATASETr   r2   rA   modeZDATATYPEr   Datatype)r   r)   oidotyper   r   r    __getitem__\  s     





zGroup.__getitem__c          	   C   sZ  t J |s.|s.y| | S  tk
r,   |S X || kr:|S |r|st| j| |j}ytjttj	t
jtjtji| S  tk
r   tdY nX n|rL| jj| |j}|tjkr|rtS | jj| |}t| |S |tjkr(| rtS | jj| |\}}tt|| |S |tjkrD|r>tS t S tdW dQ R X dS )a   Retrieve an item or other information.

        "name" given only:
            Return the item, or "default" if it doesn't exist

        "getclass" is True:
            Return the class of object (Group, Dataset, etc.), or "default"
            if nothing with that name exists

        "getlink" is True:
            Return HardLink, SoftLink or ExternalLink instances.  Return
            "default" if nothing with that name exists.

        "getlink" and "getclass" are True:
            Return HardLink, SoftLink and ExternalLink classes.  Return
            "default" if nothing with that name exists.

        Example:

        >>> cls = group.get('foo', getclass=True)
        >>> if cls == SoftLink:
        zUnknown object typezUnknown link typeN)r   rF   r
   get_infor(   r%   r^   Z
TYPE_GROUPr   ZTYPE_DATASETr   r2   ZTYPE_NAMED_DATATYPEr   ra   rG   linksr   Z	TYPE_SOFTSoftLinkZget_val_dZTYPE_EXTERNALExternalLinkr   Z	TYPE_HARDHardLink)r   r)   defaultZgetclassZgetlinktypecodeZ	linkbytesZ	filebytesr   r   r    gett  s@    
z	Group.getc          	   C   s  t  | j|dd\}}t|tr>tj|j| j||| jd nt|trj| jj	j
|| |j|| jd nt|trt|j}| jj	j||| |j|| jd nRt|tjrtj|dd}|j| j||d n$| jd|d}tj|j| j||d W dQ R X dS )a6   Add an object to the group.  The name must not already be in use.

        The action taken depends on the type of object assigned:

        Named HDF5 object (Dataset, Group, Datatype)
            A hard link is created at "name" which points to the
            given object.

        SoftLink or ExternalLink
            Create the corresponding link.

        Numpy ndarray
            The array is converted to a dataset object, with default
            settings (contiguous storage, etc.).

        Numpy dtype
            Commit a copy of the datatype as a named datatype in the file.

        Anything else
            Attempt to convert it to an ndarray and store it.  Scalar
            values are stored as scalar datasets. Raise ValueError if we
            can't understand the resulting array dtype.
        T)r!   )r!   rU   )ZlogicalN)r5   )r   r%   r   r   r
   linkr(   r\   rg   rf   Zcreate_softpathri   r   rB   Zcreate_externalrI   r4   r   Z	py_createcommitr;   )r   r)   objr!   fnZhtypeZdsr   r   r    __setitem__  s    

"

zGroup.__setitem__c             C   s   | j | | dS )z* Delete (unlink) an item from this group. N)r(   unlinkr%   )r   r)   r   r   r    __delitem__  s    zGroup.__delitem__c             C   s
   | j  S )z* Number of members attached to this group )r(   Zget_num_objs)r   r   r   r    __len__  s    zGroup.__len__c             c   s$   x| j  D ]}| |V  qW dS )z Iterate over member names N)r(   __iter__rh   )r   xr   r   r    rw     s    zGroup.__iter__c             c   s$   x| j  D ]}| |V  qW dS )z- Iterate over member names in reverse order. N)r(   __reversed__rh   )r   rx   r   r   r    ry     s    zGroup.__reversed__c             C   s   |  || jkS )z Test if a member name exists )r%   r(   )r   r)   r   r   r    __contains__  s    zGroup.__contains__c	          	   C   s&  t  t|trd}	n|}	| }t|trl|dk	r8|}
q|	dkrTtt|j}
qtt||	 j}
nt|trt	dn|}
| }d}|r|t
jO }|r|t
jO }|r|t
jO }|r|t
jO }|r|t
jO }|rttj}|| nd}t
|j| |	|j| |
|tj W dQ R X dS )a  Copy an object or group.

        The source can be a path, Group, Dataset, or Datatype object.  The
        destination can be either a path or a Group object.  The source and
        destinations need not be in the same file.

        If the source is a Group object, all objects contained in that group
        will be copied recursively.

        When the destination is a Group object, by default the target will
        be created in that group with its current name (basename of obj.name).
        You can override that by setting "name" to a string.

        There are various options which all default to "False":

         - shallow: copy only immediate members of a group.

         - expand_soft: expand soft links into new objects.

         - expand_external: expand external links into new objects.

         - expand_refs: copy objects that are pointed to by references.

         - without_attrs: copy object without copying attributes.

       Example:

        >>> f = File('myfile.hdf5', 'w')
        >>> f.create_group("MyGroup")
        >>> list(f.keys())
        ['MyGroup']
        >>> f.copy('MyGroup', 'MyCopy')
        >>> list(f.keys())
        ['MyGroup', 'MyCopy']

        .Nz(Destination must be path or Group objectr   )r   r   r   r   ppbasenamer	   get_namer(   rG   r
   ZCOPY_SHALLOW_HIERARCHY_FLAGZCOPY_EXPAND_SOFT_LINK_FLAGZCOPY_EXPAND_EXT_LINK_FLAGZCOPY_EXPAND_REFERENCE_FLAGZCOPY_WITHOUT_ATTR_FLAGr   r'   ZOBJECT_COPYZset_copy_objectcopyr%   r   Zdlcpl)r   sourcedestr)   ZshallowZexpand_softZexpand_externalZexpand_refsZwithout_attrssource_path	dest_pathflagsZcopyplr   r   r    r     s@    '








z
Group.copyc          	   C   sJ   t < ||krdS | jjj| || j| || j| jd W dQ R X dS )z Move a link to a new location in the file.

        If "source" is a hard link, this effectively renames the object.  If
        "source" is a soft or external link, the link itself is moved, with its
        value unmodified.
        N)rU   r!   )r   r(   rf   mover%   r\   Z_lcpl)r   r   r   r   r   r    r   T  s
    z
Group.movec          	      s,   t   fdd}tj|S Q R X dS )a   Recursively visit all names in this group and subgroups (HDF5 1.8).

        You supply a callable (function, method or callable object); it
        will be called exactly once for each link in this group and every
        group below it. Your callable must conform to the signature:

            func(<member name>) => <None or return value>

        Returning None continues iteration, returning anything else stops
        and immediately returns that value from the visit method.  No
        particular order of iteration within groups is guaranteed.

        Example:

        >>> # List the entire contents of the file
        >>> f = File("foo.hdf5")
        >>> list_of_names = []
        >>> f.visit(list_of_names.append)
        c                s     | S )z1 Call the function with the text name, not bytes )rh   )r)   )funcr   r   r    proxyv  s    zGroup.visit.<locals>.proxyN)r   r
   visitr(   )r   r   r   r   )r   r   r    r   a  s    zGroup.visitc          	      s,   t   fdd}tj|S Q R X dS )aV   Recursively visit names and objects in this group (HDF5 1.8).

        You supply a callable (function, method or callable object); it
        will be called exactly once for each link in this group and every
        group below it. Your callable must conform to the signature:

            func(<member name>, <object>) => <None or return value>

        Returning None continues iteration, returning anything else stops
        and immediately returns that value from the visit method.  No
        particular order of iteration within groups is guaranteed.

        Example:

        # Get a list of all datasets in the file
        >>> mylist = []
        >>> def func(name, obj):
        ...     if isinstance(obj, Dataset):
        ...         mylist.append(name)
        ...
        >>> f = File('foo.hdf5')
        >>> f.visititems(func)
        c                s    | }  | |  S )z, Use the text name of the object, not bytes )rh   )r)   )r   r   r   r    r     s    
zGroup.visititems.<locals>.proxyN)r   r
   r   r(   )r   r   r   r   )r   r   r    
visititems{  s    zGroup.visititemsc             C   s6   | s
d}n(| j d k	rd| j  nd}d|t| f }|S )Nz<Closed HDF5 group>z"%s"z(anonymous)z<HDF5 group %s (%d members)>)r)   len)r   rV   Znamestrr   r   r    __repr__  s
    zGroup.__repr__)N)NNN)N)NN)F)NFF)NFFFFF)%rH   
__module____qualname____doc__r   r   r'   ZGROUP_CREATEr&   Zset_link_creation_orderZCRT_ORDER_TRACKEDZCRT_ORDER_INDEXEDZset_attr_creation_orderr+   r;   r   r>   r   rD   rK   rS   r1   r   rd   rm   rs   ru   rv   rw   ry   rz   r   r   r   r   r   __classcell__r   r   )r   r    r      s>   

x

5 
D.  
Qr   c               @   s   e Zd ZdZdS )rj   z
        Represents a hard link in an HDF5 file.  Provided only so that
        Group.get works in a sensible way.  Has no other function.
    N)rH   r   r   r   r   r   r   r    rj     s   rj   c               @   s,   e Zd ZdZedd Zdd Zdd ZdS )	rg   z
        Represents a symbolic ("soft") link in an HDF5 file.  The path
        may be absolute or relative.  No checking is performed to ensure
        that the target actually exists.
    c             C   s   | j S )z6 Soft link value.  Not guaranteed to be a valid path. )_path)r   r   r   r    ro     s    zSoftLink.pathc             C   s   t || _d S )N)rZ   r   )r   ro   r   r   r    r     s    zSoftLink.__init__c             C   s
   d| j  S )Nz<SoftLink to "%s">)ro   )r   r   r   r    r     s    zSoftLink.__repr__N)rH   r   r   r   propertyro   r   r   r   r   r   r    rg     s   rg   c               @   s8   e Zd ZdZedd Zedd Zdd Zdd	 Zd
S )ri   z
        Represents an HDF5 external link.  Paths may be absolute or relative.
        No checking is performed to ensure either the target or file exists.
    c             C   s   | j S )z5 Soft link path, i.e. the part inside the HDF5 file. )r   )r   r   r   r    ro     s    zExternalLink.pathc             C   s   | j S )z3 Path to the external HDF5 file in the filesystem. )	_filename)r   r   r   r    rB     s    zExternalLink.filenamec             C   s   t t|| _|| _d S )N)r   r   r   r   )r   rB   ro   r   r   r    r     s    zExternalLink.__init__c             C   s   d| j | jf S )Nz"<ExternalLink to "%s" in file "%s")ro   rB   )r   r   r   r    r     s    zExternalLink.__repr__N)	rH   r   r   r   r   ro   rB   r   r   r   r   r   r    ri     s
   ri   )r   
contextlibr   	posixpathr|   rI   compatr   r    r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r@   r   r   rj   rg   ri   r   r   r   r    <module>   s&   (     
