a
    zn„f¶; ã                   @  sV  d Z ddlmZ ddlZddlZddlZddlZddlZddlm	Z	m
Z
 ddlmZ ddlmZ ddlZddlZddlZddlZddlZddlZddlZddlZddlmZmZ dd	œd
d„Zdd	œdd„Zdd	œdd„Zej d¡ddejdœe_ ej e_ ej e_ G dd„ dej!j"ƒZ#G dd„ de
ƒZ$G dd„ dƒZ%G dd„ dƒZ&G dd„ dƒZ'dS )ak  
This module defines high-level functions and objects for file-writing.

The :doc:`uproot.writing.writable.create`, :doc:`uproot.writing.writable.recreate`, and :doc:`uproot.writing.writable.update`
functions open files for writing, overwriting, or updating, in a way that is similar
to :doc:`uproot.reading.open`.

The :doc:`uproot.writing.writable.WritableFile`, :doc:`uproot.writing.writable.WritableDirectory`,
:doc:`uproot.writing.writable.WritableTree`, and :doc:`uproot.writing.writable.WritableBranch`
classes are writable versions of :doc:`uproot.reading.ReadOnlyFile`, :doc:`uproot.reading.ReadOnlyDirectory`,
:doc:`uproot.behaviors.TTree.TTree`, and :doc:`uproot.behaviors.TBranch.TBranch`.

There is no feature parity between writable and readable versions of each of these
types. Writing and reading are considered separate projects with different capabilities.
é    )ÚannotationsN)ÚMappingÚMutableMapping)ÚPath)ÚIO)Ú	no_filterÚ	no_renamezstr | Path | IO)Ú	file_pathc                 K  s^   t j | ¡} dd„ | ¡ D ƒ}t| tƒrNt jjjj	| fi |¤ŽrNt
d| › �ƒ‚t| fi |¤ŽS )aß  
    Args:
        file_path (str, ``pathlib.Path`` or file-like object): The filesystem path of the
            file to open or an open file.
        options: See below.

    Opens a local file for writing. Like ROOT's ``"CREATE"`` option, this function
    raises an error (``FileExistsError``) if a file already exists at ``file_path``.

    Returns a :doc:`uproot.writing.writable.WritableDirectory`.

    Options (type; default):

    * initial_directory_bytes (int; 256)
    * initial_streamers_bytes (int; 1024)
    * uuid_function (callable; ``uuid.uuid1``)
    * compression (:doc:`uproot.compression.Compression` or None): Compression algorithm
    and level for new objects added to the file. Can be updated after creating
    the :doc:`uproot.writing.writable.WritableFile`. Default is ``uproot.ZLIB(1)``.

    See :doc:`uproot.writing.writable.WritableFile` for details on these options.

    Additional options are passed to as ``storage_options`` to the fsspec filesystem
    c                 S  s    i | ]\}}|t jvr||“qS © )ÚcreateÚdefaults©Ú.0ÚkeyÚvaluer
   r
   úZ/home/yuhw/wc/wire-cell-python/wcpy/lib/python3.9/site-packages/uproot/writing/writable.pyÚ
<dictcomp>C   s   zcreate.<locals>.<dictcomp>zUpath exists and refusing to overwrite (use 'uproot.recreate' to overwrite)

for path )ÚuprootÚ_utilÚregularize_pathÚitemsÚ
isinstanceÚstrÚsinkÚfileÚFileSinkZ_file_existsÚFileExistsErrorÚrecreate)r	   ÚoptionsÚstorage_optionsr
   r
   r   r   )   s    ÿÿÿÿÿr   c           	      K  sÂ   t j | ¡} dd„ | ¡ D ƒ}t jjj| fi |¤Ž}| dtj	d ¡}| dtj	d ¡}| dtj	d ¡}| dtj	d ¡}|rœt
dd d	d
„ |D ƒ¡ ƒ‚t jj |||||¡}t||||ƒjS )aË  
    Args:
        file_path (str, ``pathlib.Path`` or file-like object): The filesystem path of the
            file to open or an open file.
        options: See below.

    Opens a local file for writing. Like ROOT's ``"RECREATE"`` option, this function
    overwrites any file that already exists at ``file_path``.

    Returns a :doc:`uproot.writing.writable.WritableDirectory`.

    Options (type; default):

    * initial_directory_bytes (int; 256)
    * initial_streamers_bytes (int; 1024)
    * uuid_function (callable; ``uuid.uuid1``)
    * compression (:doc:`uproot.compression.Compression` or None): Compression algorithm
    and level for new objects added to the file. Can be updated after creating
    the :doc:`uproot.writing.writable.WritableFile`. Default is ``uproot.ZLIB(1)``.

    See :doc:`uproot.writing.writable.WritableFile` for details on these options.

    Additional options are passed to as ``storage_options`` to the fsspec filesystem.
    c                 S  s    i | ]\}}|t jvr||“qS r
   )r   r   r   r
   r
   r   r   k   s   zrecreate.<locals>.<dictcomp>ÚcompressionÚinitial_directory_bytesÚinitial_streamers_bytesÚuuid_functionz;unrecognized options for uproot.create or uproot.recreate: ú, c                 s  s   | ]}t |ƒV  qd S ©N©Úrepr©r   Úxr
   r
   r   Ú	<genexpr>{   ó    zrecreate.<locals>.<genexpr>)r   r   r   r   r   r   r   Úpopr   r   Ú	TypeErrorÚjoinÚwritingÚ_cascadeZcreate_emptyÚWritableFileÚroot_directory)	r	   r   r   r   r    r!   r"   r#   Ú	cascadingr
   r
   r   r   P   s:    ÿ
ÿ
ÿÿÿûÿr   c                 K  sš   t j | ¡} dd„ | ¡ D ƒ}t jjj| fi |¤Ž}| dtj	d ¡}| dtj	d ¡}|rxt
dd dd„ |D ƒ¡ ƒ‚t jj |||¡}t||||ƒjS )	aü  
    Args:
        file_path (str, ``pathlib.Path`` or file-like object): The filesystem path of the
            file to open or an open file.
        options: See below.

    Opens a local file for writing. Like ROOT's ``"UPDATE"`` option, this function
    expects a file to already exist at ``file_path`` and opens it so that new data
    can be added to it or individual objects may be deleted from it.

    Returns a :doc:`uproot.writing.writable.WritableDirectory`.

    Options (type; default):

    * initial_directory_bytes (int; 256)
    * uuid_function (callable; ``uuid.uuid1``)

    See :doc:`uproot.writing.writable.WritableFile` for details on these options.

    Additional options are passed to as ``storage_options`` to the fsspec filesystem
    c                 S  s    i | ]\}}|t jvr||“qS r
   )Úupdater   r   r
   r
   r   r   ¢   s   zupdate.<locals>.<dictcomp>r!   r#   z(unrecognized options for uproot.update: r$   c                 s  s   | ]}t |ƒV  qd S r%   r&   r(   r
   r
   r   r*   ®   r+   zupdate.<locals>.<genexpr>)r   r   r   r   r   r   r   r,   r   r   r-   r.   r/   r0   Zupdate_existingr1   r2   )r	   r   r   r   r!   r#   r3   r
   r
   r   r4   Š   s.    ÿ
ÿÿÿýÿr4   é   é   i   )r    r!   r"   r#   c                   @  sª  e Zd ZdZdd„ Zdd„ Zeddœdd	„ƒZed
dœdd„ƒZej	dd„ ƒZedd„ ƒZ
e
j	dd„ ƒZ
edd„ ƒZeddœdd„ƒZeddœdd„ƒZej	dd„ ƒZedd„ ƒZed
dœdd„ƒZed
dœdd„ƒZed
dœd d!„ƒZed"d#„ ƒZed$d%„ ƒZed
dœd&d'„ƒZed(d)„ ƒZed*d+„ ƒZd,d-„ Zed.dœd/d0„ƒZd1d2„ Zeddœd3d4„ƒZd5d6„ Zd7d8„ Zd9d:„ Zd;d<„ Zd=d>„ Zd?d@„ Z dAdB„ Z!dCdD„ Z"dEdF„ Z#dGS )Hr1   a+  
    Args:
        sink (:doc:`uproot.sink.file.FileSink`): The physical layer for file-writing.
        cascading (:doc:`uproot.writing._cascade.CascadingFile`): The low-level file
            object.
        initial_directory_bytes (int): Number of bytes to allocate for new directories,
            so that TKeys can be added to them without immediately needing to rewrite
            the block.
        uuid_function (zero-argument callable returning a ``uuid.UUID``): Function to
            create the file's UUID and/or any directory's UUID.

    Handle to a writable ROOT file, usually created by :doc:`uproot.writing.writable.create`,
    :doc:`uproot.writing.writable.recreate`, or :doc:`uproot.writing.writable.update` and
    accessed through a :doc:`uproot.writing.writable.WritableDirectory`.
    c                 C  sb   || _ || _|| _|| _|j| _| jjj| _| jjj	| _
| jjj| _| jjjj| _i | _i | _d S r%   )Ú_sinkÚ
_cascadingÚ_initial_directory_bytesÚ_uuid_functionr	   Ú
_file_pathÚ
fileheaderÚversionZ	_fVersionÚbeginZ_fBEGINZbegin_num_bytesZ_fNbytesNameÚuuidÚbytesZ_fUUIDÚ_treesÚ_ntuples)Úselfr   r3   r!   r#   r
   r
   r   Ú__init__Ö   s    zWritableFile.__init__c                 C  s   d| j ›dt| ƒd›d�S )Nz<WritableFile z at 0xZ012xú>)r	   Úid©rC   r
   r
   r   Ú__repr__å   s    zWritableFile.__repr__zuproot.sink.file.FileSink©Úreturnc                 C  s   | j S )z‚
        Returns a :doc:`uproot.sink.file.FileSink`, the physical layer for writing
        (and sometimes reading) data.
        )r7   rG   r
   r
   r   r   è   s    zWritableFile.sinkÚintc                 C  s   | j S )zŸ
        Number of bytes to allocate for new directories, so that TKeys can be added
        to them without immediately needing to rewrite the block.
        ©r9   rG   r
   r
   r   r!   ð   s    z$WritableFile.initial_directory_bytesc                 C  s
   || _ d S r%   rL   ©rC   r   r
   r
   r   r!   ø   s    c                 C  s   | j S )zZ
        The function used to create the file's UUID and/or any directory's UUID.
        ©r:   rG   r
   r
   r   r#   ü   s    zWritableFile.uuid_functionc                 C  s
   || _ d S r%   rN   rM   r
   r
   r   r#     s    c                 C  s   | j | jdœS )zÈ
        The options passed to :doc:`uproot.writing.writable.create`,
        :doc:`uproot.writing.writable.recreate`, or :doc:`uproot.writing.writable.update`
        when opening this file.
        )r!   r#   )r9   r:   rG   r
   r
   r   r     s    þzWritableFile.optionsÚboolc                 C  s
   | j jjS )zg
        True if the file has 8-byte pointers in its header; False if the pointers are 4-byte.
        ©r8   r<   ÚbigrG   r
   r
   r   Úis_64bit  s    zWritableFile.is_64bitz%uproot.compression.Compression | Nonec                 C  s
   | j jjS )aU  
        Compression algorithm and level (:doc:`uproot.compression.Compression` or None)
        for new objects added to the file.

        This property can be changed, which allows you to write different objects
        with different compression settings.

        See also :ref:`uproot.writing.writable.WritableFile.fCompress`.
        )r8   r<   r    rG   r
   r
   r   r      s    zWritableFile.compressionc                 C  sH   |d u st |tjjƒr<|| jj_| jj | j¡ | j ¡  nt	dƒ‚d S )Nújcompression must be None or a uproot.compression.Compression object, like uproot.ZLIB(4) or uproot.ZSTD(0))
r   r   r    ÚCompressionr8   r<   Úwriter7   Úflushr-   rM   r
   r
   r   r    '  s    
ÿc                 C  s
   | j jjS )z�
        The seek point (int) to the ``TFree`` data, for managing empty spaces
        in a ROOT file (filesystem-like fragmentation).
        )r8   r<   Zfree_locationrG   r
   r
   r   Ú	fSeekFree2  s    zWritableFile.fSeekFreec                 C  s
   | j jjS )zŽ
        The number of bytes in the ``TFree`` data, for managing empty spaces
        in a ROOT file (filesystem-like fragmentation).
        )r8   r<   Zfree_num_bytesrG   r
   r
   r   ÚfNbytesFree:  s    zWritableFile.fNbytesFreec                 C  s   | j jjd S )z�
        The number of objects in the ``TFree`` data, for managing empty spaces
        in a ROOT file (filesystem-like fragmentation).
        r5   )r8   r<   Zfree_num_slicesrG   r
   r
   r   ÚnfreeB  s    zWritableFile.nfreec                 C  s   | j jjrdS dS )zo
        Number of bytes in the serialization of file seek points, which can either
        be 4 or 8.
        é   é   rP   rG   r
   r
   r   ÚfUnitsJ  s    zWritableFile.fUnitsc                 C  s,   | j jjdu rtj d¡jS | j jjjS dS )a<  
        Compression algorithm and level (as an integer code) for new objects added
        to the file.

        This property can be changed, which allows you to write different objects
        with different compression settings.

        See also :ref:`uproot.writing.writable.WritableFile.compression`.
        Nr   )r8   r<   r    r   ÚZLIBÚcoderG   r
   r
   r   Ú	fCompressR  s    zWritableFile.fCompressc                 C  s
   | j jjS )zv
        The seek point (int) to the ``TStreamerInfo`` data, where
        TStreamerInfo records are located.
        )r8   r<   Úinfo_locationrG   r
   r
   r   Ú	fSeekInfob  s    zWritableFile.fSeekInfoc                 C  s
   | j jjS )zu
        The number of bytes in the ``TStreamerInfo`` data, where
        TStreamerInfo records are located.
        )r8   r<   Zinfo_num_bytesrG   r
   r
   r   ÚfNbytesInfoj  s    zWritableFile.fNbytesInfoc                 C  s
   | j jjS )zs
        The unique identifier (UUID) of the ROOT file expressed as a Python
        ``uuid.UUID`` object.
        )r8   r<   r?   rG   r
   r
   r   r?   r  s    zWritableFile.uuidc                 C  s   t d| | jjƒS )zo
        The root (first) directory in the file as a :doc:`uproot.writing.writable.WritableDirectory`.
        r
   )ÚWritableDirectoryr8   ZrootdirectoryrG   r
   r
   r   r2   z  s    zWritableFile.root_directoryc                 C  s   | j j | j|¡ dS )zµ
        Overwrite the TStreamerInfo in this file with a new list of :doc:`uproot.streamers.Model_TStreamerInfo`
        or :doc:`uproot.writable._cascade.RawStreamerInfo`.
        N)r8   Ú	streamersÚupdate_streamersr   )rC   rd   r
   r
   r   re   �  s    zWritableFile.update_streamersú
str | Nonec                 C  s   | j S ©zX
        Filesystem path of the open file, or None if using a file-like object.
        )r;   rG   r
   r
   r   r	   ˆ  s    zWritableFile.file_pathc                 C  s   | j  ¡  dS ©zÝ
        Explicitly close the file.

        (Files can also be closed with the Python ``with`` statement, as context
        managers.)

        After closing, objects cannot be read from or written to the file.
        N)r7   ÚcloserG   r
   r
   r   ri   �  s    	zWritableFile.closec                 C  s   | j jS ©aO  
        True if the file has been closed; False otherwise.

        The file may have been closed explicitly with
        :ref:`uproot.writing.writable.WritableFile.close` or implicitly in the Python
        ``with`` statement, as a context manager.

        After closing, objects cannot be read from or written to the file.
        )r7   ÚclosedrG   r
   r
   r   rk   š  s    zWritableFile.closedc                 C  s   | j  ¡  | S r%   )r7   Ú	__enter__rG   r
   r
   r   rl   §  s    
zWritableFile.__enter__c                 C  s   | j  |||¡ d S r%   )r7   Ú__exit__©rC   Zexception_typeZexception_valueÚ	tracebackr
   r
   r   rm   «  s    zWritableFile.__exit__c                 C  s   || j |jjj< d S r%   )rA   r8   r   Úseek_location)rC   Útreer
   r
   r   Ú	_new_tree®  s    zWritableFile._new_treec                 C  s   || j |jjj< d S r%   )rB   r8   r   rp   )rC   Úntupler
   r
   r   Ú_new_ntuple±  s    zWritableFile._new_ntuplec                 C  s
   || j v S r%   ©rA   ©rC   Úlocr
   r
   r   Ú	_has_tree´  s    zWritableFile._has_treec                 C  s
   | j | S r%   ru   rv   r
   r
   r   Ú	_get_tree·  s    zWritableFile._get_treec                 C  s
   || j v S r%   ©rB   rv   r
   r
   r   Ú_has_ntupleº  s    zWritableFile._has_ntuplec                 C  s
   | j | S r%   rz   rv   r
   r
   r   Ú_get_ntuple½  s    zWritableFile._get_ntuplec                 C  s    | j | }| j |= || j |< d S r%   ru   )rC   ÚoldlocÚnewlocrq   r
   r
   r   Ú
_move_treeÀ  s    
zWritableFile._move_treeN)$Ú__name__Ú
__module__Ú__qualname__Ú__doc__rD   rH   Úpropertyr   r!   Úsetterr#   r   rR   r    rW   rX   rY   r\   r_   ra   rb   r?   r2   re   r	   ri   rk   rl   rm   rr   rt   rx   ry   r{   r|   r   r
   r
   r
   r   r1   Å   sl   










r1   c                   @  sÜ  e Zd ZdZdd„ Zdd„ Zedd„ ƒZedd	„ ƒZed
d„ ƒZ	edd„ ƒZ
dd„ Zeddœdd„ƒZdd„ Zdd„ Zedd„ ƒZejdd„ ƒZdd„ Zdd„ Zdd „ Zd!d"„ Zd#d#eed$œd%d&„Zd#eed'œd(d)„Zd#d#eed$œd*d+„Zd#d#eed$œd,d-„Zd#d#eed$œd.d/„Zd#eed'œd0d1„Zd#d#eed$œd2d3„Zd#d#eed$œd4d5„Zd6d7„ Zd8d9„ Zd:d;„ Z d<d=„ Z!d>d?„ Z"d@dA„ Z#dBdC„ Z$dDdEœdFdG„Z%dXdIdJ„ dKdJ„ dLdMdNœdOdP„Z&dYdQdR„Z'eee(d#dSœdTdU„Z)dZdVdW„Z*dDS )[rc   aÛ  
    Args:
        path (tuple of str): Path of directory names to this subdirectory; ``()`` for
            the root (first) directory.
        file (:doc:`uproot.writing.writable.WritableFile`): Handle to the file in
            which this directory can be found.
        cascading (:doc:`uproot.writing._cascade.CascadingDirectory`): The low-level
            directory object.

    Represents a writable ``TDirectory`` from a ROOT file.

    Be careful not to confuse :doc:`uproot.writing.writable.WritableFile` and
    :doc:`uproot.writing.writable.WritableDirectory`: files are for modifying global
    information such as the TStreamerInfo and FreeSegments, whereas directories
    are for data in local hierarchies.

    A :doc:`uproot.writing.writable.WritableDirectory` is a Python ``MutableMapping``,
    which uses square bracket syntax to read, write, and delete objects:

    .. code-block:: python

        my_directory["histogram"]
        my_directory["histogram"] = np.histogram(...)
        del my_directory["histogram"]

    Objects in ROOT files also have "cycle numbers," which allow multiple versions
    of an object to exist with the same name. A cycle number may be specified after
    a semicolon for *reading* and *deleting* only:

    .. code-block:: python

        my_directory["histogram;2"]
        del my_directory["histogram;2"]

    When *writing*, cycle numbers are generated to avoid overwriting previous objects:

    .. code-block:: python

        my_directory["histogram"] = np.histogram(...)   # creates a new histogram
        my_directory["histogram"] = np.histogram(...)   # creates another histogram

    Note that this is unlike a Python ``MutableMapping``, which would overwrite the
    object in the second assignment. However, it is the way ROOT I/O works; use ``del``
    to remove unwanted versions of objects.

    Any types of objects that can be read from a :doc:`uproot.reading.ReadOnlyDirectory`
    can be read from a :doc:`uproot.writing.writable.WritableDirectory` *except TTrees*. A
    TTree can only be read from a :doc:`uproot.reading.ReadOnlyDirectory` if it was
    created in this open file handle, and then it returns a :doc:`uproot.writing.writable.WritableTree`
    instead of the :doc:`uproot.behaviors.TTree.TTree` that you would get from a
    :doc:`uproot.reading.ReadOnlyDirectory`. Readable TTrees and writable TTrees are
    distinct, with separate sets of features.

    Note that subdirectories can be created by assigning to path names that include
    slashes:

    .. code-block:: python

        my_directory["subdir1/subdir2/new_object"] = new_object

    Subdirectories created this way will never be empty; to make an empty directory,
    use :ref:`uproot.writing.writable.WritableDirectory.mkdir`.

    Similarly, non-empty TTrees can be created by assignment (see :doc:`uproot.writing.writable.WritableTree`
    for recognized TTree-like data), but empty TTrees require the
    :ref:`uproot.writing.writable.WritableDirectory.mktree` method.
    c                 C  s   || _ || _|| _i | _d S r%   )Ú_pathÚ_filer8   Ú_subdirs©rC   Úpathr   r3   r
   r
   r   rD     s    zWritableDirectory.__init__c                 C  s    d  tdd | j¡ ƒt| ƒ¡S )Nz#<WritableDirectory {} at 0x{:012x}>ú/©Úformatr'   r.   r†   rF   rG   r
   r
   r   rH     s    ÿzWritableDirectory.__repr__c                 C  s   | j S )z‰
        Path of directory names to this subdirectory as a tuple of strings; e.g. ``()``
        for the root (first) directory.
        ©r†   rG   r
   r
   r   rŠ     s    zWritableDirectory.pathc                 C  s    d  dg| j¢d‘R ¡ dd¡S )zp
        Path of directory names to this subdirectory as a single string, delimited
        by slashes.
        r‹   Ú ú//©r.   r†   ÚreplacerG   r
   r
   r   Úobject_path  s    zWritableDirectory.object_pathc                 C  s   | j jS rg   ©r‡   r	   rG   r
   r
   r   r	   &  s    zWritableDirectory.file_pathc                 C  s   | j S ©z~
        Handle to the :doc:`uproot.writing.writable.WritableDirectory` in which
        this directory can be found.
        ©r‡   rG   r
   r
   r   r   -  s    zWritableDirectory.filec                 C  s   | j  ¡  dS rh   ©r‡   ri   rG   r
   r
   r   ri   5  s    	zWritableDirectory.closerO   rI   c                 C  s   | j jS rj   ©r‡   rk   rG   r
   r
   r   rk   @  s    zWritableDirectory.closedc                 C  s   | j j ¡  | S r%   ©r‡   r   rl   rG   r
   r
   r   rl   M  s    zWritableDirectory.__enter__c                 C  s   | j j |||¡ d S r%   ©r‡   r   rm   rn   r
   r
   r   rm   Q  s    zWritableDirectory.__exit__c                 C  s   | j jS )a  
        Compression algorithm and level (:doc:`uproot.compression.Compression` or None)
        for new objects added to the file.

        This property can be changed, which allows you to write different objects
        with different compression settings.
        ©r‡   r    rG   r
   r
   r   r    T  s    	zWritableDirectory.compressionc                 C  s   || j _d S r%   r›   rM   r
   r
   r   r    _  s    c                   s&   ˆ j jjt‡ fdd„ˆ j jjD ƒƒ S )Nc                 3  s   | ]}t ˆ  |¡ƒV  qd S r%   )ÚlenÚ_subdirr(   rG   r
   r   r*   d  s   z,WritableDirectory.__len__.<locals>.<genexpr>)r8   ÚdataZnum_keysÚsumÚ	dir_namesrG   r
   rG   r   Ú__len__c  s    ÿzWritableDirectory.__len__c                   s0   ˆ j j ˆ¡rdS t‡ ‡fdd„ˆ j jjD ƒƒS )NTc                 3  s   | ]}ˆˆ   |¡v V  qd S r%   )r�   r(   ©rC   Úwherer
   r   r*   k  r+   z1WritableDirectory.__contains__.<locals>.<genexpr>)r8   rž   ÚhaskeyÚanyr    r¢   r
   r¢   r   Ú__contains__h  s    zWritableDirectory.__contains__c                 C  s   |   ¡ S r%   ©ÚiterkeysrG   r
   r
   r   Ú__iter__m  s    zWritableDirectory.__iter__c                 C  s   |   ¡ S )zJ
        Supports key-completion in an IPython or Jupyter kernel.
        r§   rG   r
   r
   r   Ú_ipython_key_completions_p  s    z+WritableDirectory._ipython_key_completions_T©Ú	recursiveÚcycleÚfilter_nameÚfilter_classnamec                C  s   t | j||||d�ƒS )uU  
        Args:
            recursive (bool): If True, descend into any nested subdirectories.
                If False, only return the names of objects directly accessible
                in this ``TDirectory``.
            cycle (bool): If True, include the cycle numbers in those names.
            filter_name (None, glob string, regex string in ``"/pattern/i"`` syntax, function of str â†’ bool, or iterable of the above): A
                filter to select keys by name.
            filter_classname (None, glob string, regex string in ``"/pattern/i"`` syntax, function of str â†’ bool, or iterable of the above): A
                filter to select keys by C++ (decoded) classname.

        Returns the names of the objects in this ``TDirectory`` as a list of
        strings.

        Note that this does not read any data from the file.
        r«   )Úlistr¨   ©rC   r¬   r­   r®   r¯   r
   r
   r   Úkeysv  s    üÿzWritableDirectory.keys©r¬   r®   r¯   c                C  s   t | j|||d�ƒS )u/  
        Args:
            recursive (bool): If True, descend into any nested subdirectories.
                If False, only return objects directly accessible in this
                ``TDirectory``.
            filter_name (None, glob string, regex string in ``"/pattern/i"`` syntax, function of str â†’ bool, or iterable of the above): A
                filter to select keys by name.
            filter_classname (None, glob string, regex string in ``"/pattern/i"`` syntax, function of str â†’ bool, or iterable of the above): A
                filter to select keys by C++ (decoded) classname.

        Returns objects in this ``TDirectory`` as a list of
        :doc:`uproot.model.Model`.

        Note that this reads all objects that are selected by ``filter_name``
        and ``filter_classname``.
        r³   )r°   Ú
itervalues)rC   r¬   r®   r¯   r
   r
   r   Úvalues—  s    ýÿzWritableDirectory.valuesc                C  s   t | j||||d�ƒS )u³  
        Args:
            recursive (bool): If True, descend into any nested subdirectories.
                If False, only return (name, object) pairs directly accessible
                in this ``TDirectory``.
            cycle (bool): If True, include the cycle numbers in the names.
            filter_name (None, glob string, regex string in ``"/pattern/i"`` syntax, function of str â†’ bool, or iterable of the above): A
                filter to select keys by name.
            filter_classname (None, glob string, regex string in ``"/pattern/i"`` syntax, function of str â†’ bool, or iterable of the above): A
                filter to select keys by C++ (decoded) classname.

        Returns (name, object) pairs for objects in this ``TDirectory`` as a
        list of 2-tuples of (str, :doc:`uproot.model.Model`).

        Note that this reads all objects that are selected by ``filter_name``
        and ``filter_classname``.
        r«   )r°   Ú	iteritemsr±   r
   r
   r   r   ¶  s    üÿzWritableDirectory.itemsc                C  s   t | j||||d�ƒS )uƒ  
        Args:
            recursive (bool): If True, descend into any nested subdirectories.
                If False, only return the names and classnames of objects
                directly accessible in this ``TDirectory``.
            cycle (bool): If True, include the cycle numbers in the names.
            filter_name (None, glob string, regex string in ``"/pattern/i"`` syntax, function of str â†’ bool, or iterable of the above): A
                filter to select keys by name.
            filter_classname (None, glob string, regex string in ``"/pattern/i"`` syntax, function of str â†’ bool, or iterable of the above): A
                filter to select keys by C++ (decoded) classname.

        Returns the names and C++ (decoded) classnames of the objects in this
        ``TDirectory`` as a dict of str â†’ str.

        Note that this does not read any data from the file.
        r«   )ÚdictÚiterclassnamesr±   r
   r
   r   Ú
classnamesØ  s    üÿzWritableDirectory.classnamesc                c  sÜ   t j |¡}t j |¡}| jjjD ]´\}}}|tu s<||ƒrh|tu sL||ƒrh|rb|› d|› �V  n|V  |r"|dv r"|  ||¡j||||d�D ]F}|› d|› �}	d|	v rº|	d|	 	d¡… n|	}
|tu sÎ||
ƒrŽ|	V  qŽq"dS )u\  
        Args:
            recursive (bool): If True, descend into any nested subdirectories.
                If False, only return the names of objects directly accessible
                in this ``TDirectory``.
            cycle (bool): If True, include the cycle numbers in those names.
            filter_name (None, glob string, regex string in ``"/pattern/i"`` syntax, function of str â†’ bool, or iterable of the above): A
                filter to select keys by name.
            filter_classname (None, glob string, regex string in ``"/pattern/i"`` syntax, function of str â†’ bool, or iterable of the above): A
                filter to select keys by C++ (decoded) classname.

        Returns the names of the objects in this ``TDirectory`` as an iterator
        over strings.

        Note that this does not read any data from the file.
        ú;©Ú
TDirectoryZTDirectoryFiler«   r‹   N)
r   r   Úregularize_filterr8   rž   Úkey_triplesr   Ú_getr¨   Úindex)rC   r¬   r­   r®   r¯   ÚkeynameÚcyclenumÚ	classnameÚk1Úk2Úk3r
   r
   r   r¨   ù  s,    ÿÿü
zWritableDirectory.iterkeysc                c  s&   | j |d||d�D ]}| | V  qdS )u6  
        Args:
            recursive (bool): If True, descend into any nested subdirectories.
                If False, only return objects directly accessible in this
                ``TDirectory``.
            filter_name (None, glob string, regex string in ``"/pattern/i"`` syntax, function of str â†’ bool, or iterable of the above): A
                filter to select keys by name.
            filter_classname (None, glob string, regex string in ``"/pattern/i"`` syntax, function of str â†’ bool, or iterable of the above): A
                filter to select keys by C++ (decoded) classname.

        Returns objects in this ``TDirectory`` as an iterator over
        :doc:`uproot.model.Model`.

        Note that this reads all objects that are selected by ``filter_name``
        and ``filter_classname``.
        Tr«   Nr§   )rC   r¬   r®   r¯   rÁ   r
   r
   r   r´   (  s    ü
zWritableDirectory.itervaluesc                c  sD   | j |d||d�D ],}|s0| d¡}|d|… }|| | fV  qdS )uº  
        Args:
            recursive (bool): If True, descend into any nested subdirectories.
                If False, only return (name, object) pairs directly accessible
                in this ``TDirectory``.
            cycle (bool): If True, include the cycle numbers in the names.
            filter_name (None, glob string, regex string in ``"/pattern/i"`` syntax, function of str â†’ bool, or iterable of the above): A
                filter to select keys by name.
            filter_classname (None, glob string, regex string in ``"/pattern/i"`` syntax, function of str â†’ bool, or iterable of the above): A
                filter to select keys by C++ (decoded) classname.

        Returns (name, object) pairs for objects in this ``TDirectory`` as an
        iterator over 2-tuples of (str, :doc:`uproot.model.Model`).

        Note that this reads all objects that are selected by ``filter_name``
        and ``filter_classname``.
        Tr«   rº   N)r¨   rÀ   )rC   r¬   r­   r®   r¯   rÁ   Úatr
   r
   r   r¶   G  s    ü

zWritableDirectory.iteritemsc                c  sì   t j |¡}t j |¡}| jjjD ]Ä\}}}|tu s<||ƒrp|tu sL||ƒrp|rf|› d|› �|fV  n
||fV  |r"|dv r"|  ||¡j||||d�D ]N\}}	|› d|› �}
d|
v rÆ|
d|
 	d¡… n|
}|tu sÚ||ƒr–|
|	fV  q–q"dS )u“  
        Args:
            recursive (bool): If True, descend into any nested subdirectories.
                If False, only return the names and classnames of objects
                directly accessible in this ``TDirectory``.
            cycle (bool): If True, include the cycle numbers in the names.
            filter_name (None, glob string, regex string in ``"/pattern/i"`` syntax, function of str â†’ bool, or iterable of the above): A
                filter to select keys by name.
            filter_classname (None, glob string, regex string in ``"/pattern/i"`` syntax, function of str â†’ bool, or iterable of the above): A
                filter to select keys by C++ (decoded) classname.

        Returns the names and C++ (decoded) classnames of the objects in this
        ``TDirectory`` as an iterator of 2-tuples of (str, str).

        Note that this does not read any data from the file.
        rº   r»   r«   r‹   N)
r   r   r½   r8   rž   r¾   r   r¿   r¸   rÀ   )rC   r¬   r­   r®   r¯   rÁ   rÂ   rÃ   rÄ   Úc1rÅ   rÆ   r
   r
   r   r¸   k  s,    ÿÿ
üz WritableDirectory.iterclassnamesc                 C  sv  d|v sd|v rê|  d¡}|  }}t|ƒD ]º\}}|dkr*t|tƒr|d|v rn|jj |¡sntj|d| j	d�‚qä|}|| }q*t|t
ƒr¸||d … }t|ƒdkr°tj|d| j	d�‚|  S tj|d |d |… ¡d |jjj| j	d�‚q*|S d	|v �rJ| d	¡}	|d |	… ||	d
 d …  }}
zt|
ƒ}
W n t�yF   |d  }}
Y n0 n
|d  }}
|�rf|  ||
¡S |  ||
¡S d S )Nr‹   ú:r�   z9TTrees in writable files can't be indexed by TBranch name©Úbecauser	   r   z is not a TDirectory)rË   r²   r	   rº   r5   )ÚsplitÚ	enumerater   rc   r8   rž   r¤   r   ÚKeyInFileErrorr	   ÚWritableTreerœ   r.   Ú	key_namesÚrindexrK   Ú
ValueErrorr¿   Ú_del)rC   r£   Zisgetr   ÚstepÚlastÚiÚitemÚrestrÇ   r­   r
   r
   r   Ú_get_del_searchš  sR    

ý

ýü


z!WritableDirectory._get_del_searchc                 C  s   | j jjrtdƒ‚|  |d¡S )Nz"cannot get data from a closed fileT©r‡   r   rk   rÒ   rÙ   r¢   r
   r
   r   Ú__getitem__Ð  s    
zWritableDirectory.__getitem__c                 C  s$   | j jjrtdƒ‚|  ||i¡ d S )Nz"cannot write data to a closed file)r‡   r   rk   rÒ   r4   )rC   r£   Úwhatr
   r
   r   Ú__setitem__Õ  s    
zWritableDirectory.__setitem__c                 C  s   | j jjrtdƒ‚|  |d¡S )Nz%cannot delete data from a closed fileFrÚ   r¢   r
   r
   r   Ú__delitem__Ú  s    
zWritableDirectory.__delitem__c           	        sR  ˆj j ||¡}|d u rDtjj||d u r,dn|ˆj jjˆjˆjd�‚|j	j
dv rZˆ |¡S |j	j
dkrŒˆj |j¡r‚ˆj |j¡S tdƒ‚nÂ|j	j
dkr¾ˆj |j¡r´ˆj |j¡S tdƒ‚n�‡ ‡fdd	„}tjj ˆjjˆjj|ˆjj j¡‰ ˆjj |j|j|j ¡}tjjj ˆ |¡}tjj j!d
|jd�}tj"j#||i ˆ ˆdd�}| $¡ S d S )Nr¥   )r­   r²   r	   r“   r»   ÚTTreez|WritableDirectory cannot view preexisting TTrees; open the file with uproot.open instead of uproot.recreate or uproot.updatezROOT::Experimental::RNTuplez}WritableDirectory cannot view preexisting RNTuple; open the file with uproot.open instead of uproot.recreate or uproot.updatec                   s*   ˆj j | ||  ¡}tjjjjˆ || d�S )N)Ústart)r‡   r   Úreadr   ÚsourceÚchunkÚChunkÚwrap)rà   ÚstopÚ	raw_bytes©ZreadforupdaterC   r
   r   Ú	get_chunkþ  s    
ÿz)WritableDirectory._get.<locals>.get_chunkr   )ÚoriginT)Zread_strings)%r8   rž   Úget_keyr   Ú
exceptionsrÎ   rÐ   r	   r“   rÃ   Ústringr�   r‡   rx   rp   ry   r-   r{   r|   r/   r0   Z_ReadForUpdater?   Ztlist_of_streamersr   rá   Ú	num_bytesÚcompressed_bytesrâ   rã   rä   rå   ÚcursorZCursorÚreadingZReadOnlyKeyÚget)	rC   Únamer­   r   ré   rç   rã   rð   Zreadonlykeyr
   rè   r   r¿   ß  sP    û
ÿÿü
þÿzWritableDirectory._getc                 C  sŠ   | j j ||¡}|j}||j |j }| j j ||¡ | j j 	|¡ t
j
 ¡ | j j_| j  | jj¡ | jj | j jjj¡ | jj ¡  d S r%   )r8   rž   rë   rp   rî   rï   ÚfreesegmentsÚreleaseÚ_dataZ
remove_keyÚdatetimeÚnowÚheaderZmodified_onrU   r‡   r   Úset_file_lengthr<   ÚendrV   )rC   ró   r­   r   rà   ræ   r
   r
   r   rÓ     s    zWritableDirectory._delc                 C  sØ  |j j}|| jv rz| j| }| jj ¡ D ]P}|jjjj	|jjj	kr(|jj|jur(t
g | j¢|‘R | j|jjƒ| j|<  qzq(|| jv�rÎ| jj |j|jtjjj d ¡}tjjj ||j| jjj¡}|j|j }tjjj |||j d … || jjj¡}|j|jk�s
J ‚|jdk�r4tjj d d d tjj d d¡tjj d |¡tjj d |¡|j|jd ¡	}	|	j| jj }
| jj  !|
¡|	_	|
|	j }tjj "|	j	|	j |g ¡}|j#|	_$|	j$|	_%tjj &|||	|| j| jj ¡}|	j	|_'|	j|j# |_| (| jj¡ | jj )| jj j*j+¡ | jj ,¡  t
g | j¢|‘R | j|ƒ| j|< nš| jj |j'|j¡}tjjj ||j'| jjj¡}	tjjj" ||	jd … |j'|	j | jjj¡}tjj &|||	|| j| jj ¡}t
g | j¢|‘R | j|ƒ| j|< | j| S )Né   r   r¼   )-ró   rí   rˆ   r‡   rA   rµ   r8   Ú	directoryr   Úlocationrc   r†   r   rá   rp   rî   r   rñ   Z_directory_format_bigÚsizer/   r0   ÚKeyZdeserializeZin_pathZDirectoryHeaderZbegin_locationZdata_num_bytesÚStringr­   Zparent_locationr9   rô   ÚallocateZDirectoryDataÚ
allocationZuncompressed_bytesrï   ZSubDirectoryZdata_locationrU   rú   r<   rû   rV   )rC   r   ró   Úsubrq   rç   Zdirectory_keyÚpositionZdirectory_headerZdirectory_datakeyZrequested_num_bytesZmight_be_slightly_moreZdirectory_dataÚsubdirectoryr
   r
   r   r�   &  sÄ    


ÿÿýÿ
þ
ÿ
ý÷ÿÿÿ
ýÿú	
ÿ
ÿÿÿ
ÿ

ýú	ÿ
zWritableDirectory._subdirN©r!   c          	   
   C  s  | j jjrtdƒ‚| d¡}z| d¡}W n tyF   |d }}Y n 0 |d|… ||d d…  }}| jj |¡}|du rÀ|du rŒ| j j	}t
g | j¢|‘R | j | j | j j||| j  ¡ ¡ƒ}n@|jjdvrötd|›d|jj› d| j› d	| j› �ƒ‚n
|  |¡}|du �r|S | |¡S dS )
a"  
        Args:
            name (str): Name of the new subdirectory.
            initial_directory_bytes (None or int): Number of bytes to allocate
                for the new directory, so that TKeys can be added to it without
                immediately needing to rewrite the block. If None, the
                :doc:`uproot.writing.writable.WritableFile`'s value is used.

        Creates an empty subdirectory in this directory.

        Note that subdirectories can be created by assigning to path names that
        include slashes:

        .. code-block:: python

            my_directory["subdir1/subdir2/new_object"] = new_object

        but subdirectories created this way will never be empty. Use this method
        to make an empty directory or to control directory parameters.
        z+cannot create a TDirectory in a closed filer‹   Nr5   r»   zcannot make a directory named z because a z already has that name
in file ú in directory )r‡   r   rk   rÒ   ÚstriprÀ   r8   rž   rë   r!   rc   r†   Zadd_directoryr#   rÃ   rí   r-   r	   rŠ   r�   Úmkdir)	rC   ró   r!   ÚstrippedrÇ   ÚheadÚtailr   rý   r
   r
   r   r
  ¤  sD    

üýÿÿÿ

zWritableDirectory.mkdirr�   c                 C  s   d|  S )NÚnr
   )Zcountedr
   r
   r   Ú<lambda>è  r+   zWritableDirectory.<lambda>c                 C  s   | dkr|S | d | S )Nr�   Ú_r
   )ÚouterÚinnerr
   r
   r   r  é  r+   é
   g      $@)Úcounter_nameÚ
field_nameÚinitial_basket_capacityÚresize_factorc                C  sn  | j jjrtdƒ‚z| d¡}W n ty:   |}	| }
Y n*0 |d|… ||d d…  }}	|  |¡}
g |
j¢|	‘R }t||
j |
j 	|
j j|	||||||¡ƒ}|
j  
|¡ tƒ }g }tjjjtjjjtjjjtjjjtjjjtjjjtjjjtjjjtjjjtjjjf
D ]L}|jD ]>}|d |d f}||v�r| |¡ | tjjj |Ž ¡ �q�q|
j jj! "|
j j|¡ |S )uŽ  
        Args:
            name (str): Name of the new TTree.
            branch_types (dict or pairs of str â†’ NumPy dtype/Awkward type): Name
                and type specification for the TBranches.
            title (str): Title for the new TTree.
            counter_name (callable of str â†’ str): Function to generate counter-TBranch
                names for Awkward Arrays of variable-length lists.
            field_name (callable of str â†’ str): Function to generate TBranch
                names for columns of an Awkward record array or a Pandas DataFrame.
            initial_basket_capacity (int): Number of TBaskets that can be written to the
                TTree without rewriting the TTree metadata to make room.
            resize_factor (float): When the TTree metadata needs to be rewritten,
                this specifies how many more TBasket slots to allocate as a multiplicative
                factor.

        Creates an empty TTree in this directory.

        Note that TTrees can be created by assigning TTree-like data to a directory
        (see :doc:`uproot.writing.writable.WritableTree` for recognized TTree-like types):

        .. code-block:: python

            my_directory["tree"] = {"branch1": np.array(...), "branch2": ak.Array(...)}

        but TTrees created this way will never be empty. Use this method
        to make an empty TTree or to control its parameters.
        z&cannot create a TTree in a closed filer‹   Nr5   éþÿÿÿéÿÿÿÿ)#r‡   r   rk   rÒ   rÑ   r
  r†   rÏ   r8   Zadd_treerr   Úsetr   ÚmodelsZTLeafZModel_TLeafB_v1ZModel_TLeafS_v1ZModel_TLeafI_v1ZModel_TLeafL_v1ZModel_TLeafF_v1ZModel_TLeafD_v1ZModel_TLeafC_v1ZModel_TLeafO_v1ZTBranchZModel_TBranch_v13rß   ZModel_TTree_v20Zclass_rawstreamersÚaddÚappendr/   r0   ZRawStreamerInford   re   )rC   ró   Úbranch_typesÚtitler  r  r  r  rÇ   Útreenamerý   ÚdirpathrŠ   rq   Úseenrd   ÚmodelZrawstreamerZclassname_versionr
   r
   r   Úmktreeâ  sb    '


øýö


ÿ
ÿzWritableDirectory.mktreec           
   	   C  s¤   | j jjrtdƒ‚z| d¡}W n ty:   |}| }Y n*0 |d|… ||d d…  }}|  |¡}g |j¢|‘R }t||j |j 	|j j|||¡ƒ}	|j  
|	¡ |	S )u>  
        Args:
            name (str): Name of the new RNTuple.
            branch_types (dict or pairs of str â†’ NumPy dtype/Awkward type): Name
                and type specification for the TBranches.
            title (str): Title for the new RNTuple.

        Creates an empty RNTuple in this directory.
        z(cannot create a RNTuple in a closed filer‹   Nr5   )r‡   r   rk   rÒ   rÑ   r
  r†   ÚWritableNTupler8   Zadd_rntuplert   )
rC   ró   r  r  rÇ   r   rý   r!  rŠ   rs   r
   r
   r   Ú	mkrntupleC  s,    


üý
zWritableDirectory.mkrntuple)r®   r¯   ÚrenameÚrequire_matchesc             	     s*  t ˆtƒrtdƒ‚nt ˆtjjƒs*tdƒ‚ˆj||dd�}t|ƒdkrn|rjt	d|›dˆj
› dˆj› �ƒ‚nd	S ‡fd
d„|D ƒ}|D ]4}|jdks¦|j d¡d dkr„td|j› d�ƒ‚q„tj ˆ ¡‰ ‡ fdd„|D ƒ}	t ¡ }
i }t|	|ƒD ]4\}}|jdvrî|jj}||j }||f|||f< qîˆjjjt|ƒ|
d� tƒ }dd„ |D ƒD ]8}ˆj |¡D ]$}g }| ˆjj|¡ | |¡ �q^�qN‡fdd„|D ƒ}| jj j !| jj"|¡ i }t|	|ƒD ]’\}}|j}| #d¡ d¡}|dv�rò|d	d… }d $|¡}||v�rd||< ||  tjj%j&d t|jƒ d t|j'ƒ d t|j(ƒ 7  < �q¾| )¡ D ]"\}}| j*|t+| jj,|ƒd� �qZt-t|ƒƒD ]š}|
 .¡ }t |tjj/j0ƒ�s¬J ‚tj 1|j2¡}||j3|j4f \}}| #d¡ d¡}| }|d	d… D ]}|| }�qî|j  5| jj"|j|d |j(||j6¡ �qŠd	S )uH  
        Args:
            source (:doc:`uproot.writing.writable.WritableDirectory` or :doc:`uproot.reading.ReadOnlyDirectory`): Directory from which to copy.
            filter_name (None, glob string, regex string in ``"/pattern/i"`` syntax, function of str â†’ bool, or iterable of the above): A
                filter to select keys by name.
            filter_classname (None, glob string, regex string in ``"/pattern/i"`` syntax, function of str â†’ bool, or iterable of the above): A
                filter to select keys by C++ (decoded) classname.
            rename (None, regex string in ``"/from/to/"`` syntax, dict of str â†’ str, function of str â†’ str, or iterable of the above): A
                function to convert old names into new names.
            require_matches (bool): If True and the filters do not match any data, raise
                a ``ValueError``.

        Bulk-copy method to copy data from one ROOT file to another without interpretation
        or even decompression/recompression.

        This method will likely have performance advantages over copying objects one
        at a time, in part because it avoids interpretation and decompression/recompression,
        and also because it collects TStreamerInfo from all of the data types and
        rewrites the output file's TStreamerInfo exactly once.
        zrcopying from a WritableDirectory is not yet supported; open the 'source' as a ReadOnlyDirectory (with uproot.open)z'source' must be a TDirectoryF)r®   r¯   r­   r   z%no objects found with names matching z	
in file r  Nc                   s   g | ]}ˆ   |¡‘qS r
   )r   r(   ©râ   r
   r   Ú
<listcomp>ž  r+   z/WritableDirectory.copy_from.<locals>.<listcomp>rß   z::r  ZRNTuplezcopy_from cannot copy z objects yetc                   s   g | ]}ˆ |ƒ‘qS r
   r
   r(   )r'  r
   r   r*  §  r+   r»   )Únotificationsc                 S  s   h | ]
}|j ’qS r
   )Ú
fClassNamer(   r
   r
   r   Ú	<setcomp>´  r+   z.WritableDirectory.copy_from.<locals>.<setcomp>c                   s   g | ]\}}ˆ j  ||¡‘qS r
   )r   Zstreamer_named)r   ÚcÚvr)  r
   r   r*  º  r+   r‹   r[   é   r  )7r   rc   ÚNotImplementedErrorr   rñ   ZReadOnlyDirectoryr-   r²   rœ   rÒ   r	   rŠ   r,  rÌ   r   Zregularize_renameÚqueueÚQueueÚzipZdata_cursorrÀ   Zdata_compressed_bytesr   râ   Úchunksr°   r  Zstreamers_namedZ_dependenciesrd   r4   r‡   r8   re   r   r	  r.   Z_key_format_bigrÿ   ÚfNameZfTitler   r
  Úmaxr!   Úrangerò   rã   rä   ÚtobytesÚraw_datarà   ræ   Ú
add_objectZdata_uncompressed_bytes)rC   râ   r®   r¯   r'  r(  Z	old_namesr²   r   Z	new_namesr+  ÚrangesÚnew_nameÚold_keyrà   ræ   Zclassversion_pairsrÃ   ÚstreamerÚbatchrd   Znew_dirsrŠ   ró   r  r  rã   r:  rý   r×   r
   )r'  râ   r   Ú	copy_fromm  s¶    
ÿÿÿÿÿÿ




ÿþýüûúÿ

ÿþ
úzWritableDirectory.copy_fromc                   sð   g }ˆ durLt ˆ dƒr:t ‡ fdd„ˆ  ¡ D ƒ| ¡ ¡}qTt ˆ | ¡ ¡}n| ¡ }|D ]|\}}| d¡ d¡}|dd… |d  }}	t|ƒdkrª| jd 	|¡| j
jd� | }
|D ]}|
| }
q²tjj ||	|
|¡ qX| j
jj | j
j|¡ dS )	u6  
        Args:
            pairs (dict or pairs of str â†’ writable data): Names and data to write.
            more_pairs (dict or pairs of str â†’ writable data): More names and data to write.

        Bulk-update function, like assignment, but it collects TStreamerInfo for a single
        update.
        Nr²   c                 3  s   | ]}|ˆ | fV  qd S r%   r
   )r   Úk©Úpairsr
   r   r*   ü  r+   z+WritableDirectory.update.<locals>.<genexpr>r‹   r  r   r  )ÚhasattrÚ	itertoolsÚchainr²   r   r	  rÌ   rœ   r
  r.   r‡   r!   r   r/   ÚidentifyZadd_to_directoryr8   rd   re   r   )rC   rD  Z
more_pairsrd   Z	all_pairsrB  r/  ÚfullpathrŠ   ró   rý   r×   r
   rC  r   r4   î  s*    	
ÿþ
zWritableDirectory.update)r�   )r�   )N)+r€   r�   r‚   rƒ   rD   rH   r„   rŠ   r“   r	   r   ri   rk   rl   rm   r    r…   r¡   r¦   r©   rª   r   r²   rµ   r   r¹   r¨   r´   r¶   r¸   rÙ   rÛ   rÝ   rÞ   r¿   rÓ   r�   r
  r$  r&  r   rA  r4   r
   r
   r
   r   rc   Æ  s¬   D






	ú$û"ú%ú$ú2û"ú'ú/6:~B ü÷e ü
.ù rc   c                
   @  sô   e Zd ZdZdd„ Zdd„ Zedd„ ƒZedd	œd
d„ƒZedd	œdd„ƒZ	edd„ ƒZ
dd„ Zedd	œdd„ƒZdd„ Zdd„ Zedd„ ƒZejdd„ ƒZdd„ Zedd	œd d!„ƒZedd	œd"d#„ƒZd$d%„ Zeeed&d&d'd(d)ejd*œ	d+d,„Zd-S ).rÏ   aE  
    Args:
        path (tuple of str): Path of directory names to this TTree.
        file (:doc:`uproot.writing.writable.WritableFile`): Handle to the file in
            which this TTree can be found.
        cascading (:doc:`uproot.writing._cascadetree.Tree`): The low-level
            directory object.

    Represents a writable ``TTree`` from a ROOT file.

    This object would normally be created by assigning a TTree-like data to a
    :doc:`uproot.writing.writable.WritableDirectory`. For instance:

    .. code-block:: python

        my_directory["tree1"] = {"branch1": np.array(...), "branch2": ak.Array(...)}
        my_directory["tree2"] = numpy_structured_array
        my_directory["tree3"] = awkward_record_array
        my_directory["tree4"] = pandas_dataframe

    Recognized data types:

    * dict of NumPy arrays (flat, multidimensional, and/or structured), Awkward Arrays containing one level of variable-length lists and/or one level of records, or a Pandas DataFrame with a numeric index
    * a single NumPy structured array (one level deep)
    * a single Awkward Array containing one level of variable-length lists and/or one level of records
    * a single Pandas DataFrame with a numeric index

    The arrays may have different types, but their lengths must be identical, at
    least in the first dimension (i.e. number of entries).

    If the Awkward Array contains variable-length lists (i.e. it is "jagged"), a
    counter TBranch will be created along with the data TBranch. ROOT needs the
    counter TBranch to quantify the size of the variable-size arrays. Combining
    Awkward Arrays with the same number of nested items using
    `ak.zip <https://awkward-array.readthedocs.io/en/latest/_auto/ak.zip.html>`__ prevents
    a proliferation of counter TBranches:

    .. code-block:: python

        my_directory["tree5"] = ak.zip({"branch1": array1, "branch2": array2, "branch3": array3})

    would produce only one counter TBranch.

    Assigning TTree-like data to a directory creates the TTree object with all of
    its metadata and fills it with the contents of the arrays in one step. To separate
    the process of creating the TTree metadata from filling the first TBasket, use the
    :doc:`uproot.writing.writable.WritableDirectory.mktree` method:

    .. code-block:: python

        my_directory.mktree("tree6", {"branch1": numpy_dtype, "branch2": awkward_type})

    The :doc:`uproot.writing.writable.WritableDirectory.mktree` method can also control the
    title of the TTree and the rules used to name counter TBranches and nested field TBranches.

    The ``numpy_dtype`` is any data that NumPy recognizes as a ``np.dtype``, and the
    ``awkward_type`` is an `ak.types.Type <https://awkward-array.readthedocs.io/en/latest/ak.types.Type.html>`__ from
    `ak.type <https://awkward-array.readthedocs.io/en/latest/_auto/ak.type.html>`__ or
    a string in that form, such as ``"var * float64"`` for variable-length doubles.

    TBaskets can be added to each TBranch using the :ref:`uproot.writing.writable.WritableTree.extend`
    method:

    .. code-block:: python

        my_directory["tree6"].extend({"branch1": another_numpy_array,
                                      "branch2": another_awkward_array})

    Be sure to make these extensions as large as is feasible within memory constraints,
    because a ROOT file full of small TBaskets is bloated (larger than it needs to be)
    and slow to read (especially for Uproot, but also for ROOT).

    For instance, if you want to write a million events and have enough memory
    available to do that 100 thousand events at a time (total of 10 TBaskets),
    then do so. Filling the TTree a hundred events at a time (total of 10000 TBaskets)
    would be considerably slower for writing and reading, and the file would be much
    larger than it could otherwise be, even with compression.
    c                 C  s   || _ || _|| _d S r%   ©r†   r‡   r8   r‰   r
   r
   r   rD   f  s    zWritableTree.__init__c                 C  s    d  tdd | j¡ ƒt| ƒ¡S )Nz<WritableTree {} at 0x{:012x}>r‹   rŒ   rG   r
   r
   r   rH   k  s    ÿzWritableTree.__repr__c                 C  s   | j S )zN
        Path of directory names to this TTree as a tuple of strings.
        rŽ   rG   r
   r
   r   rŠ   p  s    zWritableTree.pathr   rI   c                 C  s    d  dg| j¢d‘R ¡ dd¡S )zi
        Path of directory names to this TTree as a single string, delimited by
        slashes.
        r‹   r�   r�   r‘   rG   r
   r
   r   r“   w  s    zWritableTree.object_pathrf   c                 C  s   | j jS rg   r”   rG   r
   r
   r   r	     s    zWritableTree.file_pathc                 C  s   | j S r•   r–   rG   r
   r
   r   r   †  s    zWritableTree.filec                 C  s   | j  ¡  dS rh   r—   rG   r
   r
   r   ri   Ž  s    	zWritableTree.closerO   c                 C  s   | j jS rj   r˜   rG   r
   r
   r   rk   ™  s    zWritableTree.closedc                 C  s   | j j ¡  | S r%   r™   rG   r
   r
   r   rl   ¦  s    zWritableTree.__enter__c                 C  s   | j j |||¡ d S r%   rš   rn   r
   r
   r   rm   ª  s    zWritableTree.__exit__c                   s\   i }d‰ | j jD ]$}|d dkr|d  ‰ ||d < qt‡ fdd„| ¡ D ƒƒrTˆ S |S dS )aó  
        Compression algorithm and level (:doc:`uproot.compression.Compression` or None)
        for new TBaskets added to the TTree.

        This property can be changed and doesn't have to be the same as the compression
        of the file, which allows you to write different objects with different
        compression settings.

        The following are equivalent:

        .. code-block:: python

            my_directory["tree"]["branch1"].compression = uproot.ZLIB(1)
            my_directory["tree"]["branch2"].compression = uproot.LZMA(9)

        and

        .. code-block:: python

            my_directory["tree"].compression = {"branch1": uproot.ZLIB(1),
                                                "branch2": uproot.LZMA(9)}
        NÚkindÚrecordr    r6  c                 3  s   | ]}|ˆ kV  qd S r%   r
   r(   ©rÕ   r
   r   r*   Ê  r+   ú+WritableTree.compression.<locals>.<genexpr>©r8   Ú_branch_dataÚallrµ   ©rC   ÚoutÚdatumr
   rM  r   r    ­  s    zWritableTree.compressionc                   sÊ   ˆ d u st ˆ tjjƒr:| jjD ]}|d dkrˆ |d< qnŒt ˆ tƒr¾tdd„ ˆ  ¡ D ƒƒr¾t‡ fdd„| jjD ƒƒr¾t	ˆ ƒt	dd„ | jjD ƒƒkr¾| jjD ] }|d dkršˆ |d	  |d< qšnt
d
ƒ‚d S )NrK  rL  r    c                 s  s2   | ]*\}}t |tƒo(|d u p(t |tjjƒV  qd S r%   ©r   r   r   r    rT   ©r   rB  r/  r
   r
   r   r*   Ø  s   þ
rN  c                 3  s&   | ]}|d  dkr|d ˆ v V  qdS ©rK  rL  r6  Nr
   ©r   rT  ©r   r
   r   r*   Ý  s   þc                 S  s   g | ]}|d  dkr|‘qS ©rK  rL  r
   rX  r
   r
   r   r*  ä  s   þz,WritableTree.compression.<locals>.<listcomp>r6  ú–compression must be None, a uproot.compression.Compression object, like uproot.ZLIB(4) or uproot.ZSTD(0), or a mapping of branch names to such objects©r   r   r    rT   r8   rP  r   rQ  r   rœ   r-   ©rC   r   rT  r
   rY  r   r    Ï  s8    ÿýþþùþÿÿôÿc                 C  sJ   | j jD ]*}|d dkr|d |krt| |ƒ  S qtj|d| jd�‚d S )NrK  rL  r6  zno such branch in writable treerÊ   )r8   rP  ÚWritableBranchr   rÎ   r	   )rC   r£   rT  r
   r
   r   rÛ   ô  s    ýzWritableTree.__getitem__rK   c                 C  s   | j jS ©z;
        The number of entries accumulated so far.
        ©r8   Únum_entriesrG   r
   r
   r   ra  ÿ  s    zWritableTree.num_entriesc                 C  s   | j jS )z<
        The number of TBaskets accumulated so far.
        )r8   Únum_basketsrG   r
   r
   r   rb    s    zWritableTree.num_basketsc                 C  s   | j  | j| jj|¡ dS )uV  
        Args:
            data (dict of str â†’ arrays): More array data to add to the TTree.

        This method adds data to an existing TTree, whether it was created through
        assignment or :doc:`uproot.writing.writable.WritableDirectory.mktree`.

        The arrays must be a dict, but the values of the dict can be any of the
        array/DataFrame types described in :doc:`uproot.writing.writable.WritableTree`.
        However, these types must be compatible with the established TBranch
        types, the dict must contain a key for every TBranch, and the arrays must have
        the same lengths (in their first dimension).

        For example,

        .. code-block:: python

            my_directory.mktree("tree6", {"branch1": numpy_dtype, "branch2": awkward_type})

            my_directory["tree6"].extend({"branch1": another_numpy_array,
                                          "branch2": another_awkward_array})

        .. warning::

            **As a word of warning,** be sure that each call to :ref:`uproot.writing.writable.WritableTree.extend` includes at least 100 kB per branch/array. (NumPy and Awkward Arrays have an `nbytes <https://numpy.org/doc/stable/reference/generated/numpy.ndarray.nbytes.html>`__ property; you want at least ``100000`` per array.) If you ask Uproot to write very small TBaskets, it will spend more time working on TBasket overhead than actually writing data. The absolute worst case is one-entry-per-:ref:`uproot.writing.writable.WritableTree.extend`. See `#428 (comment) <https://github.com/scikit-hep/uproot5/pull/428#issuecomment-908703486>`__.
        N©r8   Úextendr‡   r   ©rC   rž   r
   r
   r   rd    s    zWritableTree.extendTé   é   é   ©	r®   Úfilter_typenameÚfilter_branchr¬   Ú
full_pathsÚ
name_widthÚtypename_widthÚinterpretation_widthÚstreamc       	   
      C  s2   t  | jjj¡| j j|||||||||	d�	 dS )z¦
        Opens the TTree for reading and calls :doc:`uproot.behaviors.TBranch.HasBranches.show`
        on it (follow link for documentation of this method).
        ri  N)r   Úopenr‡   r   r“   Úshow)
rC   r®   rj  rk  r¬   rl  rm  rn  ro  rp  r
   r
   r   rr  *  s    ÷zWritableTree.showN)r€   r�   r‚   rƒ   rD   rH   r„   rŠ   r“   r	   r   ri   rk   rl   rm   r    r…   rÛ   ra  rb  rd  r   ÚsysÚstdoutrr  r
   r
   r
   r   rÏ     sH   O


!
$ õrÏ   c                   @  sF   e Zd ZdZdd„ Zdd„ Zedd„ ƒZedd	„ ƒZej	d
d	„ ƒZdS )r^  a‘  
    Represents a TBranch from a :doc:`uproot.writing.writable.WritableTree`.

    This object exists only to be able to assign compression settings differently
    on each TBranch:

    .. code-block:: python

        my_directory["tree"]["branch1"].compression = uproot.ZLIB(1)
        my_directory["tree"]["branch2"].compression = uproot.LZMA(9)

    Note that compression settings on all TBranches can be set through
    :doc:`uproot.writing.writable.WritableTree.compression`:

    .. code-block:: python

        my_directory["tree"].compression = {"branch1": uproot.ZLIB(1),
                                            "branch2": uproot.LZMA(9)}
    c                 C  s   || _ || _d S r%   )Ú_treeÚ_datum)rC   rq   rT  r
   r
   r   rD   ]  s    zWritableBranch.__init__c                 C  s.   d  t| jd ƒtdd | jj¡ ƒt| ƒ¡S )Nz&<WritableBranch {} in {} at 0x{:012x}>r6  r‹   )r�   r'   rv  r.   ru  rŠ   rF   rG   r
   r
   r   rH   a  s    &ÿzWritableBranch.__repr__c                 C  s
   | j d S )z;
        The type used to initialize this TBranch.
        Zbranch_type©rv  rG   r
   r
   r   Útypef  s    zWritableBranch.typec                 C  s
   | j d S )a  
        Compression algorithm and level (:doc:`uproot.compression.Compression` or None)
        for new TBaskets added to the TBranch.

        This property can be changed and doesn't have to be the same as the compression
        of the file or the rest of the TTree, which allows you to write different objects
        with different compression settings.

        The following are equivalent:

        .. code-block:: python

            my_directory["tree"]["branch1"].compression = uproot.ZLIB(1)
            my_directory["tree"]["branch2"].compression = uproot.LZMA(9)

        and

        .. code-block:: python

            my_directory["tree"].compression = {"branch1": uproot.ZLIB(1),
                                                "branch2": uproot.LZMA(9)}
        r    rw  rG   r
   r
   r   r    m  s    zWritableBranch.compressionc                 C  s.   |d u st |tjjƒr"|| jd< ntdƒ‚d S )Nr    rS   )r   r   r    rT   rv  r-   rM   r
   r
   r   r    ‡  s
    ÿN)
r€   r�   r‚   rƒ   rD   rH   r„   rx  r    r…   r
   r
   r
   r   r^  H  s   

r^  c                   @  s´   e Zd ZdZdd„ Zdd„ Zedd„ ƒZedd	„ ƒZed
dœdd„ƒZ	edd„ ƒZ
dd„ Zeddœdd„ƒZdd„ Zdd„ Zedd„ ƒZejdd„ ƒZeddœdd„ƒZdd „ Zd!S )"r%  a:  
    Args:
        path (tuple of str): Path of directory names to this RNTuple.
        file (:doc:`uproot.writing.writable.WritableFile`): Handle to the file in
            which this RNTuple can be found.
        cascading (:doc:`uproot.writing._cascadetree.NTuple`): The low-level
            directory object.

    Represents a writable ``RNTuple`` from a ROOT file.

    Assigning TTree-like data to a directory creates the TTree object with all of
    its metadata and fills it with the contents of the arrays in one step. To separate
    the process of creating the TTree metadata from filling the first TBasket, use the
    :doc:`uproot.writing.writable.WritableDirectory.mktree` method:

    .. code-block:: python

        my_directory.mkrntuple("tuple6", {"branch1": numpy_dtype, "branch2": awkward_type})

    The ``numpy_dtype`` is any data that NumPy recognizes as a ``np.dtype``, and the
    ``awkward_type`` is an `ak.types.Type <https://awkward-array.readthedocs.io/en/latest/ak.types.Type.html>`__ from
    `ak.type <https://awkward-array.readthedocs.io/en/latest/_auto/ak.type.html>`__ or
    a string in that form, such as ``"var * float64"`` for variable-length doubles.

    RNTuple can be extended using :ref:`uproot.writing.writable.WritableNTuple.extend`
    method:

    .. code-block:: python

        my_directory["tuple6"].extend({"branch1": another_numpy_array,
                                      "branch2": another_awkward_array})

    Be sure to make these extensions as large as is feasible within memory constraints,
    because a ROOT file full of small clusters is bloated (larger than it needs to be)
    and slow to read (especially for Uproot, but also for ROOT).

    For instance, if you want to write a million events and have enough memory
    available to do that 100 thousand events at a time (total of 10 TBaskets),
    then do so. Filling the RNTuple a hundred events at a time (total of 10000 TBaskets)
    would be considerably slower for writing and reading, and the file would be much
    larger than it could otherwise be, even with compression.
    c                 C  s   || _ || _|| _d S r%   rJ  r‰   r
   r
   r   rD   ½  s    zWritableNTuple.__init__c                 C  s    d  tdd | j¡ ƒt| ƒ¡S )Nz <WritableNTuple {} at 0x{:012x}>r‹   rŒ   rG   r
   r
   r   rH   Â  s    ÿzWritableNTuple.__repr__c                 C  s   | j S )zP
        Path of directory names to this RNTuple as a tuple of strings.
        rŽ   rG   r
   r
   r   rŠ   Ç  s    zWritableNTuple.pathc                 C  s    d  dg| j¢d‘R ¡ dd¡S )zk
        Path of directory names to this RNTuple as a single string, delimited by
        slashes.
        r‹   r�   r�   r‘   rG   r
   r
   r   r“   Î  s    zWritableNTuple.object_pathrf   rI   c                 C  s   | j jS rg   r”   rG   r
   r
   r   r	   Ö  s    zWritableNTuple.file_pathc                 C  s   | j S r•   r–   rG   r
   r
   r   r   Ý  s    zWritableNTuple.filec                 C  s   | j  ¡  dS rh   r—   rG   r
   r
   r   ri   å  s    	zWritableNTuple.closerO   c                 C  s   | j jS rj   r˜   rG   r
   r
   r   rk   ð  s    zWritableNTuple.closedc                 C  s   | j j ¡  | S r%   r™   rG   r
   r
   r   rl   ý  s    zWritableNTuple.__enter__c                 C  s   | j j |||¡ d S r%   rš   rn   r
   r
   r   rm     s    zWritableNTuple.__exit__c                   s\   i }d‰ | j jD ]$}|d dkr|d  ‰ ||d < qt‡ fdd„| ¡ D ƒƒrTˆ S |S dS )aò  
        Compression algorithm and level (:doc:`uproot.compression.Compression` or None)
        for new blobs added to the RNTuple.

        This property can be changed and doesn't have to be the same as the compression
        of the file, which allows you to write different objects with different
        compression settings.

        The following are equivalent:

        .. code-block:: python

            my_directory["tree"]["branch1"].compression = uproot.ZLIB(1)
            my_directory["tree"]["branch2"].compression = uproot.LZMA(9)

        and

        .. code-block:: python

            my_directory["tree"].compression = {"branch1": uproot.ZLIB(1),
                                                "branch2": uproot.LZMA(9)}
        NrK  rL  r    r6  c                 3  s   | ]}|ˆ kV  qd S r%   r
   r(   rM  r
   r   r*   !  r+   ú-WritableNTuple.compression.<locals>.<genexpr>rO  rR  r
   rM  r   r      s    zWritableNTuple.compressionc                   sÊ   ˆ d u st ˆ tjjƒr:| jjD ]}|d dkrˆ |d< qnŒt ˆ tƒr¾tdd„ ˆ  ¡ D ƒƒr¾t‡ fdd„| jjD ƒƒr¾t	ˆ ƒt	dd„ | jjD ƒƒkr¾| jjD ] }|d dkršˆ |d	  |d< qšnt
d
ƒ‚d S )NrK  rL  r    c                 s  s2   | ]*\}}t |tƒo(|d u p(t |tjjƒV  qd S r%   rU  rV  r
   r
   r   r*   /  s   þ
ry  c                 3  s&   | ]}|d  dkr|d ˆ v V  qdS rW  r
   rX  rY  r
   r   r*   4  s   þc                 S  s   g | ]}|d  dkr|‘qS rZ  r
   rX  r
   r
   r   r*  ;  s   þz.WritableNTuple.compression.<locals>.<listcomp>r6  r[  r\  r]  r
   rY  r   r    &  s8    ÿýþþùþÿÿôÿrK   c                 C  s   | j jS r_  r`  rG   r
   r
   r   ra  K  s    zWritableNTuple.num_entriesc                 C  s   | j  | j| jj|¡ dS )uf  
        Args:
            data (dict of str â†’ arrays): More array data to add to the RNTuple.

        This method adds data to an existing RNTuple, whether it was created through
        assignment or :doc:`uproot.writing.writable.WritableDirectory.mkrntuple`.

        The arrays must be a dict, but the values of the dict can be any of the
        array/DataFrame types described in :doc:`uproot.writing.writable.WritableTree`.
        However, these types must be compatible with the established TBranch
        types, the dict must contain a key for every TBranch, and the arrays must have
        the same lengths (in their first dimension).

        For example,

        .. code-block:: python

            my_directory.mkrntuple("ntuple6", {"branch1": numpy_dtype, "branch2": awkward_type})

            my_directory["ntuple6"].extend({"branch1": another_numpy_array,
                                          "branch2": another_awkward_array})

        .. warning::

            **As a word of warning,** be sure that each call to :ref:`uproot.writing.writable.WritableNTuple.extend` includes at least 100 kB per branch/array. (NumPy and Awkward Arrays have an `nbytes <https://numpy.org/doc/stable/reference/generated/numpy.ndarray.nbytes.html>`__ property; you want at least ``100000`` per array.) If you ask Uproot to write very small TBaskets, it will spend more time working on TBasket overhead than actually writing data. The absolute worst case is one-entry-per-:ref:`uproot.writing.writable.WritableTree.extend`. See `#428 (comment) <https://github.com/scikit-hep/uproot5/pull/428#issuecomment-908703486>`__.
        Nrc  re  r
   r
   r   rd  R  s    zWritableNTuple.extendN)r€   r�   r‚   rƒ   rD   rH   r„   rŠ   r“   r	   r   ri   rk   rl   rm   r    r…   ra  rd  r
   r
   r
   r   r%  ‘  s.   +



!
$r%  )(rƒ   Ú
__future__r   r÷   rF  r2  rs  r?   Úcollections.abcr   r   Úpathlibr   Útypingr   Zuproot._utilr   Zuproot.compressionZuproot.deserializationZuproot.exceptionsZuproot.modelZuproot.models.TObjStringZuproot.sink.fileZuproot.writing._cascader   r   r   r   r4   r    r]   Úuuid1r   rñ   ZCommonFileMethodsr1   rc   rÏ   r^  r%  r
   r
   r
   r   Ú<module>   sZ   ':2
ü          X  4I