a
    .SicI                    @   s  d Z ddlZddlZddlZddlmZ ddl	m
Z
 ddl	mZ ddlmZ ddlmZ dZd	Zd
ZdZdZdd Zdd ZdfddZeZejZejZejZej Z!ej"Z#ej$Z%edg ddd Z&edg ddd Z'edg ddd Z(dd Z)d d! Z*ej+Z,ej-Z.ed"d#d$ Z/d%d& Z0d'd( Z1d)d* Z2ed+dgd,d-Z3ej4Z5e5Z6G d.d/ d/e7Z8e8 Z9ed0dhd2d3Z:d4d5 Z;did6d7Z<djd8d9Z=ed:dkd;d<Z>ed=d>d? Z?d@dA Z@dBdC ZAdldEdFZBdmdGdHZCedIg ddndJdKZDdodLdMZEedNg ddOdP ZFdQdR ZGedSg ddpdTdUZHedVg ddqdWdXZIdrdZd[ZJdsd\d]ZKed^g dd_d` ZLeMdaejN eMdbejO eMdcejP eMddejQ eMdeejR dS )tac	  Functions that work with structures.

A structure is either:

* one of the recognized Python collections, holding _nested structures_;
* a value of any other type, typically a TensorFlow data type like Tensor,
  Variable, or of compatible types such as int, float, ndarray, etc. these are
  commonly referred to as _atoms_ of the structure.

A structure of type `T` is a structure whose atomic items are of type `T`.
For example, a structure of `tf.Tensor` only contains `tf.Tensor` as its atoms.

Historically a _nested structure_ was called a _nested sequence_ in TensorFlow.
A nested structure is sometimes called a _nest_ or a _tree_, but the formal
name _nested structure_ is preferred.

Refer to [Nesting Data Structures]
(https://en.wikipedia.org/wiki/Nesting_(computing)#Data_structures).

The following collection types are recognized by `tf.nest` as nested
structures:

* `collections.abc.Sequence` (except `string` and `bytes`).
  This includes `list`, `tuple`, and `namedtuple`.
* `collections.abc.Mapping` (with sortable keys).
  This includes `dict` and `collections.OrderedDict`.
* `collections.abc.MappingView` (with sortable keys).
* [`attr.s` classes](https://www.attrs.org/).

Any other values are considered **atoms**.  Not all collection types are
considered nested structures.  For example, the following types are
considered atoms:

* `set`; `{"a", "b"}` is an atom, while `["a", "b"]` is a nested structure.
* [`dataclass` classes](https://docs.python.org/library/dataclasses.html)
* `tf.Tensor`
* `numpy.array`

`tf.nest.is_nested` checks whether an object is a nested structure or an atom.
For example:

  >>> tf.nest.is_nested("1234")
  False
  >>> tf.nest.is_nested([1, 3, [4, 5]])
  True
  >>> tf.nest.is_nested(((7, 8), (5, 6)))
  True
  >>> tf.nest.is_nested([])
  True
  >>> tf.nest.is_nested({"a": 1, "b": 2})
  True
  >>> tf.nest.is_nested({"a": 1, "b": 2}.keys())
  True
  >>> tf.nest.is_nested({"a": 1, "b": 2}.values())
  True
  >>> tf.nest.is_nested({"a": 1, "b": 2}.items())
  True
  >>> tf.nest.is_nested(set([1, 2]))
  False
  >>> ones = tf.ones([2, 3])
  >>> tf.nest.is_nested(ones)
  False

Note: A proper structure shall form a tree. The user shall ensure there is no
cyclic references within the items in the structure,
i.e., no references in the structure of the input of these functions
should be recursive. The behavior is undefined if there is a cycle.

    N)
tf_logging)_pywrap_nest)_pywrap_utils)collections_abc)	tf_exportzThe shallow_tree's keys are not a subset of the input_tree's keys. The shallow_tree has the following keys that are not in the input_tree: {}.zThe two structures don't have the same sequence type. Input structure has type {input_type}, while shallow structure has type {shallow_type}.zThe two structures don't have the same sequence length. Input structure has length {input_length}, while shallow structure has length {shallow_length}.zThe input_tree has fewer items than the shallow_tree. Input structure has length {input_size}, while shallow structure has length {shallow_size}.zVIf shallow structure is a sequence, input must also be a sequence. Input has type: {}.c                    s,   t  jd}dd |D } fdd|D S )zReturns a list of (name, value) pairs from an attrs instance.

  The list will be sorted by name.

  Args:
    obj: an object.

  Returns:
    A list of (attr_name, attr_value) pairs, sorted by attr_name.
  __attrs_attrs__c                 s   s   | ]}|j V  qd S N)name).0a r   W/var/www/html/django/DPS/env/lib/python3.9/site-packages/tensorflow/python/util/nest.py	<genexpr>       z#_get_attrs_items.<locals>.<genexpr>c                    s   g | ]}|t  |fqS r   )getattr)r
   	attr_nameobjr   r   
<listcomp>   r   z$_get_attrs_items.<locals>.<listcomp>)r   	__class__)r   attrsZ
attr_namesr   r   r   _get_attrs_itemsz   s    r   c                 C   s.   zt |  W S  ty(   tdY n0 dS )zHReturns a sorted list of the dict keys, with error if keys not sortable.z,nest only supports dicts with sortable keys.N)sortedkeys	TypeError)dict_r   r   r   _sorted   s    r   Fc                 C   s   t | |S )a  Returns True iff `instance` is a `namedtuple`.

  Args:
    instance: An instance of a Python object.
    strict: If True, `instance` is considered to be a `namedtuple` only if
        it is a "plain" namedtuple. For instance, a class inheriting
        from a `namedtuple` will be considered to be a `namedtuple`
        iff `strict=False`.

  Returns:
    True if `instance` is a `namedtuple`.
  )r   IsNamedtuple)instancestrictr   r   r   is_namedtuple   s    r    z__internal__.nest.is_attrs)v1c                 C   s   t | S )zHReturns a true if its input is an instance of an attr.s decorated class.)	_is_attrsr   r   r   r   is_attrs   s    r#   z__internal__.nest.is_mappingc                 C   s   t | S )z5Returns a true if its input is a collections.Mapping.)_is_mappingr   r   r   r   
is_mapping   s    r%   z__internal__.nest.sequence_likec              
      s  t | rZttt| | t| }|tjkr:t| j}n| }| D ]} | ||< qD|S t| rttt| | t| }t	|ddst
t
jd|d z| fdd| D W S  ty } z"tdt| | |W Y d}~n
d}~0 0  nt| rt|S t| st| rFt| tjr6t| j}nt| }|| S t| rvt|dksbJ | j}||d	 S t| rt|dksJ | |d	 S t| tjjrtt| |S t| tjrt| t| j|S t| |S dS )
ac  Converts the sequence `args` to the same type as `instance`.

  Args:
    instance: an instance of `tuple`, `list`, `namedtuple`, `dict`,
        `collections.OrderedDict`, or `composite_tensor.Composite_Tensor`
        or `type_spec.TypeSpec`.
    args: items to be converted to the `instance` type.

  Returns:
    `args` with the type of `instance`.
  Z__supported_by_tf_nest__FzPMapping types may not work well with tf.nest. Prefer using MutableMapping for {}   c                 3   s   | ]}| | fV  qd S r   r   )r
   keyresultr   r   r      r   z!_sequence_like.<locals>.<genexpr>zError creating an object of type {} like {}. Note that it must accept a single positional argument representing an iterable of key-value pairs, in addition to self. Cause: {}Nr   ) _is_mutable_mappingdictzipr   type_collectionsdefaultdictdefault_factoryr$   r   r   log_first_nWARNformatr   _is_mapping_viewlistr    r"   
isinstance_wraptObjectProxy__wrapped___is_composite_tensorlen
_type_spec_from_components_is_type_spec_sixmovesrange_sequence_like)r   argsZinstance_typedr'   errspecr   r(   r   rB      sX    

 


rB   c                 c   s   t | D ]\}}|V  qd S r   )_yield_sorted_items)iterable_vr   r   r   _yield_value   s    rK   c                 c   s
  t | tr t| D ]
}|V  qnt| tkrBt| D ]
}|V  q4nt | ttjfrpt| D ]}|| | fV  qZnt	| rt
| D ]
}|V  qnxt| r| jD ]}|t| |fV  qnRt| r| j}|jj|| fV  n.t| r| jj| jfV  nt| D ]
}|V  qdS )a  Yield (key, value) pairs for `iterable` in a deterministic order.

  For Sequences, the key will be an int, the array index of a value.
  For Mappings, the key will be the dictionary key.
  For objects (e.g. namedtuples), the key will be the attribute name.

  In all cases, the keys will be iterated in sorted order.

  Args:
    iterable: an iterable.

  Yields:
    The iterable's (key, value) pairs, in order of sorted keys.
  N)r6   r5   	enumerater-   tupler+   _collections_abcMappingr   r"   r   r    _fieldsr   r:   r<   
value_type__name___to_componentsr>   _component_specs)rH   itemr'   field	type_specr   r   r   rG     s,    




rG   znest.is_nestedc                 C   s   t | S )a  Returns true if its input is a nested structure.

  Refer to [tf.nest](https://www.tensorflow.org/api_docs/python/tf/nest)
  for the definition of a nested structure.

  Args:
    seq: the value to test.

  Returns:
    True if the input is a nested structure.
  
_is_nestedseqr   r   r   	is_nested;  s    r\   c                 C   s   t | S )a%  Returns true if its input is a nested structure or a composite.

  Refer to [tf.nest](https://www.tensorflow.org/api_docs/python/tf/nest)
  for the definition of a nested structure.

  Args:
    seq: the value to test.

  Returns:
    True if the input is a nested structure or a composite.
  _is_nested_or_compositerZ   r   r   r   is_nested_or_compositeK  s    r_   c                 C   s   t | S r   rX   rZ   r   r   r   is_sequence\  s    r`   c                 C   s   t | S r   r]   rZ   r   r   r   is_sequence_or_composite`  s    ra   znest.flattenc                 C   s"   | du rdgS t |}t| |S )a  Returns a flat list from a given structure.

  Refer to [tf.nest](https://www.tensorflow.org/api_docs/python/tf/nest)
  for the definition of a structure.

  If the structure is an atom, then returns a single-item list: [structure].

  This is the inverse of the `nest.pack_sequence_as` method that takes in a
  flattened list and re-packs it into the nested structure.

  In the case of dict instances, the sequence consists of the values, sorted by
  key to ensure deterministic behavior. This is true also for OrderedDict
  instances: their sequence order is ignored, the sorting order of keys is used
  instead. The same convention is followed in `nest.pack_sequence_as`. This
  correctly repacks dicts and OrderedDicts after they have been flattened, and
  also allows flattening an OrderedDict and then repacking it back using a
  corresponding plain dict, or vice-versa. Dictionaries with non-sortable keys
  cannot be flattened.

  Users must not modify any collections used in nest while this function is
  running.

  Examples:

  1. Python dict (ordered by key):

    >>> dict = { "key3": "value3", "key1": "value1", "key2": "value2" }
    >>> tf.nest.flatten(dict)
    ['value1', 'value2', 'value3']

  2. For a nested python tuple:

    >>> tuple = ((1.0, 2.0), (3.0, 4.0, 5.0), 6.0)
    >>> tf.nest.flatten(tuple)
        [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]

  3. For a nested dictionary of dictionaries:

    >>> dict = { "key3": {"c": (1.0, 2.0), "a": (3.0)},
    ... "key1": {"m": "val1", "g": "val2"} }
    >>> tf.nest.flatten(dict)
    ['val2', 'val1', 3.0, 1.0, 2.0]

  4. Numpy array (will not flatten):

    >>> array = np.array([[1, 2], [3, 4]])
    >>> tf.nest.flatten(array)
        [array([[1, 2],
                [3, 4]])]

  5. `tf.Tensor` (will not flatten):

    >>> tensor = tf.constant([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]])
    >>> tf.nest.flatten(tensor)
        [<tf.Tensor: shape=(3, 3), dtype=float32, numpy=
          array([[1., 2., 3.],
                 [4., 5., 6.],
                 [7., 8., 9.]], dtype=float32)>]

  6. `tf.RaggedTensor`: This is a composite tensor thats representation consists
  of a flattened list of 'values' and a list of 'row_splits' which indicate how
  to chop up the flattened list into different rows. For more details on
  `tf.RaggedTensor`, please visit
  https://www.tensorflow.org/api_docs/python/tf/RaggedTensor.

  with `expand_composites=False`, we just return the RaggedTensor as is.

    >>> tensor = tf.ragged.constant([[3, 1, 4, 1], [], [5, 9, 2]])
    >>> tf.nest.flatten(tensor, expand_composites=False)
    [<tf.RaggedTensor [[3, 1, 4, 1], [], [5, 9, 2]]>]

  with `expand_composites=True`, we return the component Tensors that make up
  the RaggedTensor representation (the values and row_splits tensors)

    >>> tensor = tf.ragged.constant([[3, 1, 4, 1], [], [5, 9, 2]])
    >>> tf.nest.flatten(tensor, expand_composites=True)
    [<tf.Tensor: shape=(7,), dtype=int32, numpy=array([3, 1, 4, 1, 5, 9, 2],
                                                      dtype=int32)>,
     <tf.Tensor: shape=(4,), dtype=int64, numpy=array([0, 4, 4, 7])>]

  Args:
    structure: an atom or a nested structure. Note, numpy arrays are considered
      atoms and are not flattened.
    expand_composites: If true, then composite tensors such as
      `tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their
      component tensors.

  Returns:
    A Python list, the flattened version of the input.

  Raises:
    TypeError: The nest is or contains a dict with non-sortable keys.
  N)boolr   Flatten	structureexpand_compositesr   r   r   flattend  s    _rg   c                   @   s    e Zd Zg Zdd Zdd ZdS )
_DotStringc                 C   s   dS N.r   selfr   r   r   __str__  s    z_DotString.__str__c                 C   s   dS ri   r   rk   r   r   r   __repr__  s    z_DotString.__repr__N)rR   
__module____qualname__	__slots__rm   rn   r   r   r   r   rh     s   rh   znest.assert_same_structureTc              
   C   s   t |}t |}zt| ||| W nf ttfy } zJttdd | }ttdd |}t|dt|||f W Y d}~n
d}~0 0 dS )ag  Asserts that two structures are nested in the same way.

  Refer to [tf.nest](https://www.tensorflow.org/api_docs/python/tf/nest)
  for the definition of a structure.

  Note the method does not check the types of atoms inside the structures.

  Examples:

  * These atom vs. atom comparisons will pass:

    >>> tf.nest.assert_same_structure(1.5, tf.Variable(1, tf.uint32))
    >>> tf.nest.assert_same_structure("abc", np.array([1, 2]))

  * These nested structure vs. nested structure comparisons will pass:

    >>> structure1 = (((1, 2), 3), 4, (5, 6))
    >>> structure2 = ((("foo1", "foo2"), "foo3"), "foo4", ("foo5", "foo6"))
    >>> structure3 = [(("a", "b"), "c"), "d", ["e", "f"]]
    >>> tf.nest.assert_same_structure(structure1, structure2)
    >>> tf.nest.assert_same_structure(structure1, structure3, check_types=False)

    >>> import collections
    >>> tf.nest.assert_same_structure(
    ...     collections.namedtuple("bar", "a b")(1, 2),
    ...     collections.namedtuple("foo", "a b")(2, 3),
    ...     check_types=False)

    >>> tf.nest.assert_same_structure(
    ...     collections.namedtuple("bar", "a b")(1, 2),
    ...     { "a": 1, "b": 2 },
    ...     check_types=False)

    >>> tf.nest.assert_same_structure(
    ...     { "a": 1, "b": 2, "c": 3 },
    ...     { "c": 6, "b": 5, "a": 4 })

    >>> ragged_tensor1 = tf.RaggedTensor.from_row_splits(
    ...       values=[3, 1, 4, 1, 5, 9, 2, 6],
    ...       row_splits=[0, 4, 4, 7, 8, 8])
    >>> ragged_tensor2 = tf.RaggedTensor.from_row_splits(
    ...       values=[3, 1, 4],
    ...       row_splits=[0, 3])
    >>> tf.nest.assert_same_structure(
    ...       ragged_tensor1,
    ...       ragged_tensor2,
    ...       expand_composites=True)

  * These examples will raise exceptions:

    >>> tf.nest.assert_same_structure([0, 1], np.array([0, 1]))
    Traceback (most recent call last):
    ...
    ValueError: The two structures don't have the same nested structure

    >>> tf.nest.assert_same_structure(
    ...       collections.namedtuple('bar', 'a b')(1, 2),
    ...       collections.namedtuple('foo', 'a b')(2, 3))
    Traceback (most recent call last):
    ...
    TypeError: The two structures don't have the same nested structure

  Args:
    nest1: an atom or a nested structure.
    nest2: an atom or a nested structure.
    check_types: if `True` (default) types of structures are checked as well,
      including the keys of dictionaries. If set to `False`, for example a list
      and a tuple of objects will look the same if they have the same size. Note
      that namedtuples with identical name and fields are always considered to
      have the same shallow structure. Two types will also be considered the
      same if they are both list subtypes (which allows "list" and
      "_ListWrapper" from trackable dependency tracking to compare equal).
      `check_types=True` only checks type of sub-structures. The types of atoms
      are not checked.
    expand_composites: If true, then composite tensors such as
      `tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their
      component tensors.

  Raises:
    ValueError: If the two structures do not have the same number of atoms or
      if the two structures are not nested in the same way.
    TypeError: If the two structures differ in the type of sequence in any of
      their substructures. Only possible if `check_types` is `True`.
  c                 S   s   t S r   _DOTrI   r   r   r   <lambda>;  r   z'assert_same_structure.<locals>.<lambda>c                 S   s   t S r   rr   rt   r   r   r   ru   <  r   z9%s
Entire first structure:
%s
Entire second structure:
%sN)rb   r   AssertSameStructure
ValueErrorr   strmap_structurer-   )nest1nest2check_typesrf   eZstr1Zstr2r   r   r   assert_same_structure  s    Y
r~   c                 C   s
   t | S )aa  Returns a dictionary with flattened keys and values.

  This function flattens the keys and values of a dictionary, which can be
  arbitrarily nested structures, and returns the flattened version of such
  structures:

  ```python
  example_dictionary = {(4, 5, (6, 8)): ("a", "b", ("c", "d"))}
  result = {4: "a", 5: "b", 6: "c", 8: "d"}
  flatten_dict_items(example_dictionary) == result
  ```

  The input dictionary must satisfy two properties:

  1. Its keys and values should have the same exact nested structure.
  2. The set of all flattened keys of the dictionary must not contain repeated
     keys.

  Args:
    dictionary: the dictionary to zip

  Returns:
    The zipped dictionary.

  Raises:
    TypeError: If the input is not a dictionary.
    ValueError: If any key and value do not have the same structure layout, or
    if keys are not unique.
  )r   ZFlattenDictItems)
dictionaryr   r   r   flatten_dict_itemsC  s    r   c           	      C   sj   g }|p
t }t| D ]L}||rJt|||||\}}|||| |}q|||  |d7 }q||fS )a  Helper function for pack_sequence_as.

  Args:
    structure: structure to mimic.
    flat: Flattened values to output substructure for.
    index: Index at which to start reading from flat.
    is_nested_fn: Function used to test if a value should be treated as a
      nested structure.
    sequence_fn: Function used to generate a new strcuture instance.

  Returns:
    The tuple (new_index, child), where:
      * new_index - the updated index into `flat` having processed `structure`.
      * packed - the subset of `flat` corresponding to `structure`,
                 having started at `index`, and packed into the same nested
                 format.

  Raises:
    ValueError: if `structure` contains more atoms than `flat`
      (assuming indexing starts from `index`).
  r&   )rB   rK   _packed_nest_with_indicesappend)	re   flatindexis_nested_fnsequence_fnpackeds	new_indexchildr   r   r   r   d  s    

r   c           	   
   C   s  |rt nt}|pt}dd }||s>td||dt||| st|dkrtdt| || dt|t|||d|d S z(t| |d||\}}|t|k rt	W nJ t	y   t
| |d}t|t|krtd	t|t|| |f Y n0 || |S )
zDImplements sequence packing, with the option to alter the structure.c                 S   s$   t | }|d | ||d  o d S )Nz...rx   )valuelength	value_strr   r   r   truncate  s    z#_pack_sequence_as.<locals>.truncatezYAttempted to pack value:
  {}
into a structure, but found incompatible type `{}` instead.d   r&   zThe target structure is of type `{}`
  {}
However the input is a sequence ({}) of length {}.
  {}
nest cannot guarantee that it is safe to map one to the other.r   rf   zsCould not pack sequence. Structure had %d atoms, but flat_sequence had %d items.  Structure: %s, flat_sequence: %s.)r^   rY   rB   r   r3   r-   r;   rw   r   
IndexErrorrg   )	re   flat_sequencerf   r   r   r   Zfinal_indexr   flat_structurer   r   r   _pack_sequence_as  sB    
r   znest.pack_sequence_asc                 C   s   t | ||S )aF  Returns a given flattened sequence packed into a given structure.

  Refer to [tf.nest](https://www.tensorflow.org/api_docs/python/tf/nest)
  for the definition of a structure.

  If `structure` is an atom, `flat_sequence` must be a single-item list;
  in this case the return value is `flat_sequence[0]`.

  If `structure` is or contains a dict instance, the keys will be sorted to
  pack the flat sequence in deterministic order. This is true also for
  `OrderedDict` instances: their sequence order is ignored, the sorting order of
  keys is used instead. The same convention is followed in `flatten`.
  This correctly repacks dicts and `OrderedDict`s after they have been
  flattened, and also allows flattening an `OrderedDict` and then repacking it
  back using a corresponding plain dict, or vice-versa.
  Dictionaries with non-sortable keys cannot be flattened.

  Examples:

  1. Python dict:

    >>> structure = { "key3": "", "key1": "", "key2": "" }
    >>> flat_sequence = ["value1", "value2", "value3"]
    >>> tf.nest.pack_sequence_as(structure, flat_sequence)
    {'key3': 'value3', 'key1': 'value1', 'key2': 'value2'}

  2. For a nested python tuple:

    >>> structure = (('a','b'), ('c','d','e'), 'f')
    >>> flat_sequence = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
    >>> tf.nest.pack_sequence_as(structure, flat_sequence)
    ((1.0, 2.0), (3.0, 4.0, 5.0), 6.0)

  3. For a nested dictionary of dictionaries:

    >>> structure = { "key3": {"c": ('alpha', 'beta'), "a": ('gamma')},
    ...               "key1": {"e": "val1", "d": "val2"} }
    >>> flat_sequence = ['val2', 'val1', 3.0, 1.0, 2.0]
    >>> tf.nest.pack_sequence_as(structure, flat_sequence)
    {'key3': {'c': (1.0, 2.0), 'a': 3.0}, 'key1': {'e': 'val1', 'd': 'val2'}}

  4. Numpy array (considered a scalar):

    >>> structure = ['a']
    >>> flat_sequence = [np.array([[1, 2], [3, 4]])]
    >>> tf.nest.pack_sequence_as(structure, flat_sequence)
    [array([[1, 2],
           [3, 4]])]

  5. tf.Tensor (considered a scalar):

    >>> structure = ['a']
    >>> flat_sequence = [tf.constant([[1., 2., 3.], [4., 5., 6.]])]
    >>> tf.nest.pack_sequence_as(structure, flat_sequence)
    [<tf.Tensor: shape=(2, 3), dtype=float32,
     numpy= array([[1., 2., 3.], [4., 5., 6.]], dtype=float32)>]

  6. `tf.RaggedTensor`: This is a composite tensor thats representation consists
  of a flattened list of 'values' and a list of 'row_splits' which indicate how
  to chop up the flattened list into different rows. For more details on
  `tf.RaggedTensor`, please visit
  https://www.tensorflow.org/api_docs/python/tf/RaggedTensor.

  With `expand_composites=False`, we treat RaggedTensor as a scalar.

    >>> structure = { "foo": tf.ragged.constant([[1, 2], [3]]),
    ...               "bar": tf.constant([[5]]) }
    >>> flat_sequence = [ "one", "two" ]
    >>> tf.nest.pack_sequence_as(structure, flat_sequence,
    ... expand_composites=False)
    {'foo': 'two', 'bar': 'one'}

  With `expand_composites=True`, we expect that the flattened input contains
  the tensors making up the ragged tensor i.e. the values and row_splits
  tensors.

    >>> structure = { "foo": tf.ragged.constant([[1., 2.], [3.]]),
    ...               "bar": tf.constant([[5.]]) }
    >>> tensors = tf.nest.flatten(structure, expand_composites=True)
    >>> print(tensors)
    [<tf.Tensor: shape=(1, 1), dtype=float32, numpy=array([[5.]],
     dtype=float32)>,
     <tf.Tensor: shape=(3,), dtype=float32, numpy=array([1., 2., 3.],
     dtype=float32)>,
     <tf.Tensor: shape=(3,), dtype=int64, numpy=array([0, 2, 3])>]
    >>> verified_tensors = [tf.debugging.check_numerics(t, 'invalid tensor: ')
    ...                     if t.dtype==tf.float32 else t
    ...                     for t in tensors]
    >>> tf.nest.pack_sequence_as(structure, verified_tensors,
    ...                          expand_composites=True)
    {'foo': <tf.RaggedTensor [[1.0, 2.0], [3.0]]>,
     'bar': <tf.Tensor: shape=(1, 1), dtype=float32, numpy=array([[5.]],
     dtype=float32)>}

  Args:
    structure: Nested structure, whose structure is given by nested lists,
      tuples, and dicts. Note: numpy arrays and strings are considered
      scalars.
    flat_sequence: flat sequence to pack.
    expand_composites: If true, then composite tensors such as
      `tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their
      component tensors.

  Returns:
    packed: `flat_sequence` converted to have the same recursive structure as
      `structure`.

  Raises:
    ValueError: If `flat_sequence` and `structure` have different
      atom counts.
    TypeError: `structure` is or contains a dict with non-sortable keys.
  )r   re   r   rf   r   r   r   pack_sequence_as  s    rr   znest.map_structurec                    s   t std |s td|dd}|dd |rRtdd|  |d	d
 D ]}t|d || d q^ fdd|D }t| }t|d fdd|D  dS )a  Creates a new structure by applying `func` to each atom in `structure`.

  Refer to [tf.nest](https://www.tensorflow.org/api_docs/python/tf/nest)
  for the definition of a structure.

  Applies `func(x[0], x[1], ...)` where x[i] enumerates all atoms in
  `structure[i]`.  All items in `structure` must have the same arity,
  and the return value will contain results with the same structure layout.

  Examples:

  * A single Python dict:

  >>> a = {"hello": 24, "world": 76}
  >>> tf.nest.map_structure(lambda p: p * 2, a)
  {'hello': 48, 'world': 152}

  * Multiple Python dictionaries:

  >>> d1 = {"hello": 24, "world": 76}
  >>> d2 = {"hello": 36, "world": 14}
  >>> tf.nest.map_structure(lambda p1, p2: p1 + p2, d1, d2)
  {'hello': 60, 'world': 90}

  * A single Python list:

  >>> a = [24, 76, "ab"]
  >>> tf.nest.map_structure(lambda p: p * 2, a)
  [48, 152, 'abab']

  * Scalars:

  >>> tf.nest.map_structure(lambda x, y: x + y, 3, 4)
  7

  * Empty structures:

  >>> tf.nest.map_structure(lambda x: x + 1, ())
  ()

  * Check the types of iterables:

  >>> s1 = (((1, 2), 3), 4, (5, 6))
  >>> s1_list = [[[1, 2], 3], 4, [5, 6]]
  >>> tf.nest.map_structure(lambda x, y: None, s1, s1_list)
  Traceback (most recent call last):
  ...
  TypeError: The two structures don't have the same nested structure

  * Type check is set to False:

  >>> s1 = (((1, 2), 3), 4, (5, 6))
  >>> s1_list = [[[1, 2], 3], 4, [5, 6]]
  >>> tf.nest.map_structure(lambda x, y: None, s1, s1_list, check_types=False)
  (((None, None), None), None, (None, None))

  Args:
    func: A callable that accepts as many arguments as there are structures.
    *structure: atom or nested structure.
    **kwargs: Valid keyword args are:
      * `check_types`: If set to `True` (default) the types of iterables within
        the structures have to be same (e.g. `map_structure(func, [1], (1,))`
        raises a `TypeError` exception). To allow this set this argument to
        `False`. Note that namedtuples with identical name and fields are always
        considered to have the same shallow structure.
      * `expand_composites`: If set to `True`, then composite tensors such as
        `tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their
        component tensors.  If `False` (the default), then composite tensors are
        not expanded.

  Returns:
    A new structure with the same arity as `structure[0]`, whose atoms
    correspond to `func(x[0], x[1], ...)` where `x[i]` is the atom in the
    corresponding location in `structure[i]`. If there are different structure
    types and `check_types` is `False` the structure types of the first
    structure will be used.

  Raises:
    TypeError: If `func` is not callable or if the structures do not match
      each other by depth tree.
    ValueError: If no structure is provided or if the structures do not match
      each other by type.
    ValueError: If wrong keyword arguments are provided.
  zfunc must be callable, got: %sz#Must provide at least one structurer|   Trf   FzQOnly valid keyword arguments are `check_types` and `expand_composites`, not: `%s`z`, `r&   Nr   r|   rf   c                 3   s   | ]}t | V  qd S r   )rg   r
   r   r   r   r   r     r   z map_structure.<locals>.<genexpr>c                    s   g | ]} | qS r   r   )r
   xfuncr   r   r     r   z!map_structure.<locals>.<listcomp>r   )	callabler   rw   popjoinr   r~   r,   r   )r   re   kwargsr|   otherr   entriesr   )rf   r   r   ry   )  s,    Vry   c                    s(    fdd}t |d |g|R i |S )a]  Applies `func` to each entry in `structure` and returns a new structure.

  Applies `func(path, x[0], x[1], ..., **kwargs)` where x[i] is an entry in
  `structure[i]` and `path` is the common path to x[i] in the structures.  All
  structures in `structure` must have the same arity, and the return value will
  contain the results with the same structure layout. Special kwarg
  `check_types` determines whether the types of iterables within the structure
  must be the same-- see **kwargs definition below.

  Args:
    func: A callable with the signature func(path, *values, **kwargs) that is
      evaluated on the leaves of the structure.
    *structure: A variable number of compatible structures to process.
    **kwargs: Optional kwargs to be passed through to func. Special kwarg
      `check_types` is not passed to func, but instead determines whether the
      types of iterables within the structures have to be same (e.g.,
      `map_structure(func, [1], (1,))` raises a `TypeError` exception). By
      default, the types must match. To allow iteration over structures of
      different types (but common arity), set this kwarg to `False`.

  Returns:
    A structure of the same form as the input structures whose leaves are the
    result of evaluating func on corresponding leaves of the input structures.

  Raises:
    TypeError: If `func` is not callable or if the structures do not match
      each other by depth tree.
    TypeError: If `check_types` is not `False` and the two structures differ in
      the type of sequence in any of their substructures.
    ValueError: If no structures are provided.
  c                    s*   d dd | D } |g|R i |S )N/c                 s   s   | ]}t |V  qd S r   r   r   r   r   r   r     r   zAmap_structure_with_paths.<locals>.wrapper_func.<locals>.<genexpr>r   )Z
tuple_pathinputsr   Zstring_pathr   r   r   wrapper_func  s    z.map_structure_with_paths.<locals>.wrapper_funcr   $map_structure_with_tuple_paths_up_to)r   re   r   r   r   r   r   map_structure_with_paths  s     r   c                 O   s   t |d | g|R i |S )ax  Applies `func` to each entry in `structure` and returns a new structure.

  Applies `func(tuple_path, x[0], x[1], ..., **kwargs)` where `x[i]` is an entry
  in `structure[i]` and `tuple_path` is a tuple of indices and/or dictionary
  keys (as returned by `nest.yield_flat_paths`), which uniquely specifies the
  common path to x[i] in the structures. All structures in `structure` must have
  the same arity, and the return value will contain the results in the same
  structure. Special kwarg `check_types` determines whether the types of
  iterables within the structure must be the same-- see **kwargs definition
  below.

  Args:
    func: A callable with the signature `func(tuple_path, *values, **kwargs)`
      that is evaluated on the leaves of the structure.
    *structure: A variable number of compatible structures to process.
    **kwargs: Optional kwargs to be passed through to func. Special kwarg
      `check_types` is not passed to func, but instead determines whether the
      types of iterables within the structures have to be same (e.g.
      `map_structure(func, [1], (1,))` raises a `TypeError` exception). To allow
      this set this argument to `False`.

  Returns:
    A structure of the same form as the input structures whose leaves are the
    result of evaluating func on corresponding leaves of the input structures.

  Raises:
    TypeError: If `func` is not callable or if the structures do not match
      each other by depth tree.
    TypeError: If `check_types` is not `False` and the two structures differ in
      the type of sequence in any of their substructures.
    ValueError: If no structures are provided.
  r   r   )r   re   r   r   r   r   map_structure_with_tuple_paths  s    !r   r   c           
      c   sl   || s||fV  nTt t|}t| D ]>\}}||f }|| }t||||dD ]\}}	||	fV  qRq(dS )a  Yields (path, value) pairs of input_tree flattened up to shallow_tree.

  Args:
    shallow_tree: Nested structure. Traverse no further than its leaf nodes.
    input_tree: Nested structure. Return the paths and values from this tree.
      Must have the same upper structure as shallow_tree.
    is_nested_fn: Function used to test if a value should be treated as a
      nested structure.
    path: Tuple. Optional argument, only used when recursing. The path from the
      root of the original shallow_tree, down to the root of the shallow_tree
      arg of this recursive call.

  Yields:
    Pairs of (path, value), where path the tuple path of a leaf node in
    shallow_tree, and value is the value of the corresponding node in
    input_tree.
  )pathN)r+   rG   _yield_flat_up_to)
shallow_tree
input_treer   r   Zshallow_keyZshallow_subtreesubpathZinput_subtreeZ	leaf_pathZ
leaf_valuer   r   r   r     s    
r   c                 C   s  |rt nt}|| r||s.tdt| t| tjrFt| j}nt| }|rt||st| d}t|d}|r|rt	| |stt
jt|t| dnlt| trt|trnVt| st|rt| st|rn4t| tjrt|tjstt
jt|t| dt| s"t|rt|s6t|rJt| sdt| sdtt
jt|t| dt| rr| n| j }t|r|n|j }	||	g}
|
du r<td||	f nt| rt|s<tdt| nZt|t| krttjt|t| dn,t|t| k r<ttjt|t| dt| tjrrt| t| }|rrttt|tt| t|D ]\}}t||||d	 qdS )
a  Asserts that `shallow_tree` is a shallow structure of `input_tree`.

  That is, this function tests if the `input_tree` structure can be created from
  the `shallow_tree` structure by replacing its leaf nodes with deeper
  tree structures.

  Examples:

  The following code will raise an exception:
  ```python
    shallow_tree = {"a": "A", "b": "B"}
    input_tree = {"a": 1, "c": 2}
    assert_shallow_structure(shallow_tree, input_tree)
  ```

  The following code will raise an exception:
  ```python
    shallow_tree = ["a", "b"]
    input_tree = ["c", ["d", "e"], "f"]
    assert_shallow_structure(shallow_tree, input_tree)
  ```

  Args:
    shallow_tree: an arbitrarily nested structure.
    input_tree: an arbitrarily nested structure.
    check_types: if `True` (default) the sequence types of `shallow_tree` and
      `input_tree` have to be the same. Note that even with check_types==True,
      this function will consider two different namedtuple classes with the same
      name and _fields attribute to be the same class.
    expand_composites: If true, then composite tensors such as
      `tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their
      component tensors.
  Raises:
    TypeError: If `shallow_tree` is a sequence but `input_tree` is not.
    TypeError: If the sequence types of `shallow_tree` are different from
      `input_tree`. Only raised if `check_types` is `True`.
    ValueError: If the sequence lengths of `shallow_tree` are different from
      `input_tree`.
  zVIf shallow structure is a sequence, input must also be a sequence. Input has type: %s.F)
input_typeshallow_typeNz1Incompatible CompositeTensor TypeSpecs: %s vs. %szWIf shallow structure is a TypeSpec, input must also be a TypeSpec.  Input has type: %s.)Zinput_lengthZshallow_length)
input_sizeZshallow_sizer   )r^   rY   r   r-   r6   r7   r8   r9   r    same_namedtuples"_STRUCTURES_HAVE_MISMATCHING_TYPESr3   r5   r:   r>   rN   rO   r<   Z_without_tensor_namesZmost_specific_common_supertyperw   r;   $_STRUCTURES_HAVE_MISMATCHING_LENGTHS%_INPUT_TREE_SMALLER_THAN_SHALLOW_TREEset_SHALLOW_TREE_HAS_INVALID_KEYSr   r,   rK   assert_shallow_structure)r   r   r|   rf   r   r   Zshallow_is_namedtupleZinput_is_namedtupleZtype_spec_1Ztype_spec_2r)   Zabsent_keysshallow_branchinput_branchr   r   r   r     s    +








r   z__internal__.nest.flatten_up_toc                 C   s2   |rt nt}t| |||d dd t| ||D S )a
  Flattens `input_tree` up to `shallow_tree`.

  Refer to [tf.nest](https://www.tensorflow.org/api_docs/python/tf/nest)
  for the definition of a structure.

  Any further depth in structure in `input_tree` is retained as structures in
  the partially flatten output.

  If `shallow_tree` and `input_tree` are atoms, this returns a
  single-item list: `[input_tree]`.

  Use Case:

  Sometimes we may wish to partially flatten a structure, retaining some
  of the nested structure. We achieve this by specifying a shallow structure,
  `shallow_tree`, we wish to flatten up to.

  The input, `input_tree`, can be thought of as having the same structure layout
  as `shallow_tree`, but with leaf nodes that are themselves tree structures.

  Examples:

  ```python
  input_tree = [[[2, 2], [3, 3]], [[4, 9], [5, 5]]]
  shallow_tree = [[True, True], [False, True]]

  flattened_input_tree = flatten_up_to(shallow_tree, input_tree)
  flattened_shallow_tree = flatten_up_to(shallow_tree, shallow_tree)

  # Output is:
  # [[2, 2], [3, 3], [4, 9], [5, 5]]
  # [True, True, False, True]
  ```

  ```python
  input_tree = [[('a', 1), [('b', 2), [('c', 3), [('d', 4)]]]]]
  shallow_tree = [['level_1', ['level_2', ['level_3', ['level_4']]]]]

  input_tree_flattened_as_shallow_tree = flatten_up_to(shallow_tree, input_tree)
  input_tree_flattened = flatten(input_tree)

  # Output is:
  # [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
  # ['a', 1, 'b', 2, 'c', 3, 'd', 4]
  ```

  Edge Cases for atoms:

  ```python
  flatten_up_to(0, 0)  # Output: [0]
  flatten_up_to(0, [0, 1, 2])  # Output: [[0, 1, 2]]
  flatten_up_to([0, 1, 2], 0)  # Output: TypeError
  flatten_up_to([0, 1, 2], [0, 1, 2])  # Output: [0, 1, 2]
  ```

  Args:
    shallow_tree: a possibly pruned structure of input_tree.
    input_tree: an atom or a nested structure.
      Note, numpy arrays are considered atoms.
    check_types: bool. If True, check that each node in shallow_tree has the
      same type as the corresponding node in input_tree.
    expand_composites: If true, then composite tensors such as
      `tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their
      component tensors.

  Returns:
    A Python list, the partially flattened version of `input_tree` according to
    the structure of `shallow_tree`.

  Raises:
    TypeError: If `shallow_tree` is a nested structure but `input_tree` is not.
    TypeError: If the structure types of `shallow_tree` are different from
      `input_tree`.
    ValueError: If the structure lengths of `shallow_tree` are different from
      `input_tree`.
  r   c                 S   s   g | ]\}}|qS r   r   )r
   rI   rJ   r   r   r   r     s   z!flatten_up_to.<locals>.<listcomp>)r^   rY   r   r   r   r   r|   rf   r   r   r   r   flatten_up_to  s    O
r   c                 C   s,   |rt nt}t| |||d tt| ||S )a  Flattens `input_tree` up to `shallow_tree`.

  Any further depth in structure in `input_tree` is retained as structures in
  the partially flattened output.

  Returns a list of (path, value) pairs, where value a leaf node in the
  flattened tree, and path is the tuple path of that leaf in input_tree.

  If `shallow_tree` and `input_tree` are not sequences, this returns a
  single-item list: `[((), input_tree)]`.

  Use Case:

  Sometimes we may wish to partially flatten a nested sequence, retaining some
  of the nested structure. We achieve this by specifying a shallow structure,
  `shallow_tree`, we wish to flatten up to.

  The input, `input_tree`, can be thought of as having the same structure layout
  as `shallow_tree`, but with leaf nodes that are themselves tree structures.

  Examples:

  ```python
  input_tree = [[[2, 2], [3, 3]], [[4, 9], [5, 5]]]
  shallow_tree = [[True, True], [False, True]]

  flattened_input_tree = flatten_with_tuple_paths_up_to(shallow_tree,
                                                        input_tree)
  flattened_shallow_tree = flatten_with_tuple_paths_up_to(shallow_tree,
                                                          shallow_tree)

  # Output is:
  # [((0, 0), [2, 2]),
  #  ((0, 1), [3, 3]),
  #  ((1, 0), [4, 9]),
  #  ((1, 1), [5, 5])]
  #
  # [((0, 0), True),
  #  ((0, 1), True),
  #  ((1, 0), False),
  #  ((1, 1), True)]
  ```

  ```python
  input_tree = [[('a', 1), [('b', 2), [('c', 3), [('d', 4)]]]]]
  shallow_tree = [['level_1', ['level_2', ['level_3', ['level_4']]]]]

  input_tree_flattened_as_shallow_tree = flatten_up_to(shallow_tree, input_tree)
  input_tree_flattened = flatten(input_tree)

  # Output is:
  # [((0, 0), ('a', 1)),
  #  ((0, 1, 0), ('b', 2)),
  #  ((0, 1, 1, 0), ('c', 3)),
  #  ((0, 1, 1, 1), ('d', 4))]
  # ['a', 1, 'b', 2, 'c', 3, 'd', 4]
  ```

  Non-Sequence Edge Cases:

  ```python
  flatten_with_tuple_paths_up_to(0, 0)  # Output: [(), 0]

  flatten_with_tuple_paths_up_to(0, [0, 1, 2])  # Output: [(), [0, 1, 2]]

  flatten_with_tuple_paths_up_to([0, 1, 2], 0)  # Output: TypeError

  flatten_with_tuple_paths_up_to([0, 1, 2], [0, 1, 2])
  # Output: [((0,) 0), ((1,), 1), ((2,), 2)]
  ```

  Args:
    shallow_tree: a possibly pruned structure of input_tree.
    input_tree: an atom or a nested structure.
      Note, numpy arrays are considered atoms.
    check_types: bool. If True, check that each node in shallow_tree has the
      same type as the corresponding node in input_tree.
    expand_composites: If true, then composite tensors such as
      `tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their
      component tensors.

  Returns:
    A Python list, the partially flattened version of `input_tree` according to
    the structure of `shallow_tree`.

  Raises:
    TypeError: If `shallow_tree` is a nested structure but `input_tree` is not.
    TypeError: If the structure types of `shallow_tree` are different from
      `input_tree`.
    ValueError: If the structure lengths of `shallow_tree` are different from
      `input_tree`.
  r   )r^   rY   r   r5   r   r   r   r   r   flatten_with_tuple_paths_up_to  s    `r   z%__internal__.nest.map_structure_up_toc                    s    t |  fddg|R i |S )aK
  Applies a function or op to a number of partially flattened inputs.

  The `inputs` are flattened up to `shallow_tree` before being mapped.

  Use Case:

  Sometimes we wish to apply a function to a partially flattened
  structure (for example when the function itself takes structure inputs). We
  achieve this by specifying a shallow structure, `shallow_tree` we wish to
  flatten up to.

  The `inputs`, can be thought of as having the same structure layout as
  `shallow_tree`, but with leaf nodes that are themselves tree structures.

  This function therefore will return something with the same base structure as
  `shallow_tree`.

  Examples:

  ```python
  shallow_tree = [None, None]
  inp_val = [1, 2, 3]
  out = map_structure_up_to(shallow_tree, lambda x: 2 * x, inp_val)

  # Output is: [2, 4]
  ```

  ```python
  ab_tuple = collections.namedtuple("ab_tuple", "a, b")
  op_tuple = collections.namedtuple("op_tuple", "add, mul")
  inp_val = ab_tuple(a=2, b=3)
  inp_ops = ab_tuple(a=op_tuple(add=1, mul=2), b=op_tuple(add=2, mul=3))
  out = map_structure_up_to(inp_val, lambda val, ops: (val + ops.add) * ops.mul,
                            inp_val, inp_ops)

  # Output is: ab_tuple(a=6, b=15)
  ```

  ```python
  data_list = [[2, 4, 6, 8], [[1, 3, 5, 7, 9], [3, 5, 7]]]
  name_list = ['evens', ['odds', 'primes']]
  out = map_structure_up_to(
      name_list,
      lambda name, sec: "first_{}_{}".format(len(sec), name),
      name_list, data_list)

  # Output is: ['first_4_evens', ['first_5_odds', 'first_3_primes']]
  ```

  Args:
    shallow_tree: a shallow structure, common to all the inputs.
    func: callable which will be applied to each input individually.
    *inputs: structures that are compatible with shallow_tree. The function
        `func` is applied to corresponding structures due to partial flattening
        of each input, so the function must support arity of `len(inputs)`.
    **kwargs: kwargs to feed to func(). Special kwarg
      `check_types` is not passed to func, but instead determines whether the
      types of iterables within the structures have to be same (e.g.
      `map_structure(func, [1], (1,))` raises a `TypeError` exception). To allow
      this set this argument to `False`.

  Raises:
    TypeError: If `shallow_tree` is a nested structure but `input_tree` is not.
    TypeError: If the structure types of `shallow_tree` are different from
      `input_tree`.
    ValueError: If the structure lengths of `shallow_tree` are different from
      `input_tree`.

  Returns:
    result of repeatedly applying `func`, with the same structure layout as
    `shallow_tree`.
  c                    s    | S r   r   )rI   valuesr   r   r   ru     r   z%map_structure_up_to.<locals>.<lambda>r   )r   r   r   r   r   r   r   map_structure_up_toJ  s    J
r   c           	         s   |st ddd ddr,tnt}|D ]}t| d q4 fdd|D }d	d t|d
 |D }fddt|g|R  D }t|dS )a]
  Applies a function or op to a number of partially flattened inputs.

  Like map_structure_up_to(), except that the 'func' argument takes a path
  tuple as its first argument, followed by the corresponding values from
  *inputs.

  Example:

  ```python
  lowercase = {'a': 'a', 'b': ('b0', 'b1')}
  uppercase = {'a': 'A', 'b': ('B0', 'B1')}

  def print_path_and_values(path, *values):
    print("path: {}, values: {}".format(path, values))

  shallow_tree = {'a': None}
  map_structure_with_tuple_paths_up_to(shallow_tree,
                                       print_path_and_values,
                                       lowercase,
                                       uppercase)
  path: ('a',), values: ('a', 'A')
  path: ('b', 0), values: ('b0', 'B0')
  path: ('b', 1), values: ('b1', 'B1')

  shallow_tree = {'b': None}
  map_structure_with_tuple_paths_up_to(shallow_tree,
                                       print_path_and_values,
                                       lowercase,
                                       uppercase,
                                       check_types=False)
  path: ('b', 1), values: (('bo', 'b1'), ('B0', 'B1'))

  shallow_tree = {'a': None, 'b': {1: None}}
  map_structure_with_tuple_paths_up_to(shallow_tree,
                                       print_path_and_values,
                                       lowercase,
                                       uppercase,
                                       check_types=False)
  path: ('a',), values: ('a', 'A')
  path: ('b', 1), values: ('b1', B1')
  ```

  Args:
    shallow_tree: a shallow structure, common to all the inputs.
    func: callable that takes args (path, inputs_0_value, ... , inputs_N_value),
      where path is a tuple path to an atom in shallow_tree, and
      inputs_i_value is the corresponding value from inputs[i].
    *inputs: structures that are all structurally compatible with
        shallow_tree.
    **kwargs: kwargs to feed to func(). Special kwarg
      `check_types` is not passed to func, but instead determines whether the
      types of iterables within the structures have to be same (e.g.
      `map_structure(func, [1], (1,))` raises a `TypeError` exception). To allow
      this set this argument to `False`.

  Raises:
    TypeError: If `shallow_tree` is a nested structure but one of `*inputs` is
      not.
    TypeError: If the structure types of `shallow_tree` are different from
      `input_tree`.
    ValueError: If the structure lengths of `shallow_tree` are different from
      `input_tree`.

  Returns:
    Result of repeatedly applying `func`. Has the same structure layout as
    `shallow_tree`.
  zCannot map over no sequencesr|   Trf   Fr   c                 3   s   | ]}t | d V  qdS )r   N)r   )r
   r   )r|   rf   r   r   r   r     s   z7map_structure_with_tuple_paths_up_to.<locals>.<genexpr>c                 s   s   | ]\}}|V  qd S r   r   )r
   r   rI   r   r   r   r     s   r   c                    s   g | ]} |i qS r   r   )r
   rC   )r   r   r   r   r     s   z8map_structure_with_tuple_paths_up_to.<locals>.<listcomp>r   )rw   r   r^   rY   r   r   r,   r   )	r   r   r   r   r   r   Zflat_value_genZflat_path_genresultsr   )r|   rf   r   r   r   r   r     s0    Dr   z0__internal__.nest.get_traverse_shallow_structurec                 C   s   |rt nt}| |}||s:t|ts6td||f |S g }t|trt|sPdS t|D ]}|t| ||d qXn~||std||f ndt|||d t	t|t|D ]B\}}t|tstd||f |r|t| | q|d qt
||S )a  Generates a shallow structure from a `traverse_fn` and `structure`.

  `traverse_fn` must accept any possible subtree of `structure` and return
  a depth=1 structure containing `True` or `False` values, describing which
  of the top-level subtrees may be traversed.  It may also
  return scalar `True` or `False` "traversal is OK / not OK for all subtrees."

  Examples are available in the unit tests (nest_test.py).

  Args:
    traverse_fn: Function taking a substructure and returning either a scalar
      `bool` (whether to traverse that substructure or not) or a depth=1
      shallow structure of the same type, describing which parts of the
      substructure to traverse.
    structure: The structure to traverse.
    expand_composites: If true, then composite tensors such as
      `tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their
      component tensors.

  Returns:
    A shallow structure containing python bools, which can be passed to
    `map_structure_up_to` and `flatten_up_to`.

  Raises:
    TypeError: if `traverse_fn` returns a nested structure for an atom input.
      or a structure with depth higher than 1 for a nested structure input,
      or if any leaf values in the returned structure or scalar are not type
      `bool`.
  z8traverse_fn returned structure: %s for non-structure: %sFr   z8traverse_fn returned a non-bool scalar: %s for input: %szStraverse_fn didn't return a depth=1 structure of bools.  saw: %s  for structure: %s)r^   rY   r6   rb   r   rK   r   get_traverse_shallow_structurer   r,   rB   )Ztraverse_fnre   rf   r   Zto_traverseZlevel_traversebranchtr   r   r   r     sP     


r   z"__internal__.nest.yield_flat_pathsc                 c   s,   |rt nt}t| | |D ]\}}|V  qdS )a  Yields paths for some nested structure.

  Refer to [tf.nest](https://www.tensorflow.org/api_docs/python/tf/nest)
  for the definition of a structure.

  Paths are lists of objects which can be str-converted, which may include
  integers or other types which are used as indices in a dict.

  The flat list will be in the corresponding order as if you called
  `nest.flatten` on the structure. This is handy for naming Tensors such
  the TF scope structure matches the tuple structure.

  E.g. if we have a tuple `value = Foo(a=3, b=Bar(c=23, d=42))`

  ```shell
  nest.flatten(value)
  [3, 23, 42]
  list(nest.yield_flat_paths(value))
  [('a',), ('b', 'c'), ('b', 'd')]
  ```

  ```shell
  list(nest.yield_flat_paths({'a': [3]}))
  [('a', 0)]
  list(nest.yield_flat_paths({'a': 3}))
  [('a',)]
  ```

  Args:
    nest: the value to produce a flattened paths list for.
    expand_composites: If true, then composite tensors such as
      `tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their
      component tensors.

  Yields:
    Tuples containing index or key values which form the path to a specific
    leaf value in the nested structure.
  N)r^   rY   r   )nestrf   r   krI   r   r   r   yield_flat_pathsF  s    (r   r   c                    s@   t | |d} fddfdd|D }tt|t| |dS )a  Returns a list of (string path, atom) tuples.

  The order of tuples produced matches that of `nest.flatten`. This allows you
  to flatten a nested structure while keeping information about where in the
  structure each atom was located. See `nest.yield_flat_paths`
  for more information.

  Args:
    structure: the nested structure to flatten.
    separator: string to separate levels of hierarchy in the results, defaults
      to '/'.
    expand_composites: If true, then composite tensors such as
      `tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their
      component tensors.

  Returns:
    A list of (string, atom) tuples.
  r   c                    s     dd | D S )Nc                 s   s   | ]}t |V  qd S r   r   )r
   Zpath_elementr   r   r   r     r   zOflatten_with_joined_string_paths.<locals>.stringify_and_join.<locals>.<genexpr>r   )Zpath_elements)	separatorr   r   stringify_and_join  s    z<flatten_with_joined_string_paths.<locals>.stringify_and_joinc                 3   s   | ]} |V  qd S r   r   )r
   r   )r   r   r   r     r   z3flatten_with_joined_string_paths.<locals>.<genexpr>)r   r5   r,   rg   )re   r   rf   Z
flat_pathsZflat_string_pathsr   )r   r   r    flatten_with_joined_string_pathss  s    
r   c                 C   s   t tt| |dt| |dS )a  Returns a list of `(tuple_path, atom)` tuples.

  The order of pairs produced matches that of `nest.flatten`. This allows you
  to flatten a nested structure while keeping information about where in the
  structure each atom was located. See `nest.yield_flat_paths`
  for more information about tuple paths.

  Args:
    structure: the nested structure to flatten.
    expand_composites: If true, then composite tensors such as
      `tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their
      component tensors.

  Returns:
    A list of `(tuple_path, atom)` tuples. Each `tuple_path` is a tuple
    of indices and/or dictionary keys that uniquely specify the path to
    `atom` within `structure`.
  r   )r5   r,   r   rg   rd   r   r   r   flatten_with_tuple_paths  s
    
r   z__internal__.nest.list_to_tuplec                 C   s   dd }t | t| d|dS )a  Replace all lists with tuples.

  The fork of nest that tf.data uses treats lists as atoms, while
  tf.nest treats them as structures to recurse into. Keras has chosen to adopt
  the latter convention, and must therefore deeply replace all lists with tuples
  before passing structures to Dataset.from_generator.

  Args:
    structure: A nested structure to be remapped.

  Returns:
    structure mapped to replace all lists with tuples.
  c                 S   s   t | trt|S t| |S r   )r6   r5   rM   rB   )r   rC   r   r   r   r     s    
z"list_to_tuple.<locals>.sequence_fnF)r   )r   rg   )re   r   r   r   r   list_to_tuple  s    r   rO   MutableMappingSequenceMappingViewr8   )F)F)TF)N)N)F)r   )TF)TF)TF)F)F)r   F)F)S__doc__collectionsr.   sixr?   wraptr7   tensorflow.python.platformr   tensorflow.python.utilr   r   tensorflow.python.util.compatr   rN    tensorflow.python.util.tf_exportr   r   r   r   r   Z$_IF_SHALLOW_IS_SEQ_INPUT_MUST_BE_SEQr   r   r    _is_namedtupleIsMappingViewr4   IsAttrsr"   IsCompositeTensorr:   
IsTypeSpecr>   IsMutableMappingr*   	IsMappingr$   r#   r%   rB   rK   rG   IsNestedrY   IsNestedOrCompositer^   r\   r_   r`   ra   rg   SameNamedtuplesr   Z_same_namedtuplesobjectrh   rs   r~   r   r   r   r   ry   r   r   r   r   r   r   r   r   r   r   r   r   r   RegisterTyperO   r   r   r   r8   r   r   r   r   <module>   s   F	






F1
e  f% 
) 
(t
o*'
   
 
  [  
h

Pd
 F
,  



