
    BVh                        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 ej"                  Zej&                  Zej*                  Zej.                  Zej2                  Zej6                  Zej:                  Zej>                  Z ejB                  Z"ejF                  Z$ejJ                  Z&dZ'd	Z(d
Z)dZ* G d dejV                        Z, G d de-      Z. e.       Z/d Z0d4dZ1d Z2d Z3d Z4d Z5d Z6d Z7d Z8d Z9d Z:	 d5dZ;	 d5dZ<d6dZ=	 d7dZ>d Z?d4d Z@d4d!ZA	 d7d"ZB	 d7d#ZCd$ ZDd% ZEd& ZFd' ZGd8d(ZHd8d)ZId* ZJ	 	 d5d+ZK	 d5d,ZL	 d6d-ZM	 	 d5d.ZN	 d5d/ZOd0 ZPd1 ZQd2 ZRd3 ZSy)9a  Utility methods for handling nests.

This module encapsulates different semantics of handling nests by the public
tf.nest APIs and internal tf.data APIs. The difference in semantics exists for
historic reasons and reconciliation would require a non-backwards compatible
change.

The implementation of the different semantics use a common utility to
avoid / minimize further divergence between the two APIs over time.
    N)pywrap_tensorflow)
tf_logging)_pywrap_utils)collections_abc)CustomNestProtocolzThe 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}.zThe 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: {}.c                       e Zd ZdZdZdZy)Modalitya7  Modality/semantic used for treating nested structures.

  - Modality.CORE follows tensorflow_core/tf.nest semantics.

    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`

  - Modality.DATA follows tf.data's nest semantics.

  This modality makes two changes:
  1. It removes support for lists as a level of nesting in nested structures.
  2. It adds support for `SparseTensorValue` as an atomic element.

  The motivation for this change is twofold:

  1. It seems more natural for lists to be treated (e.g. in Dataset
  constructors)
    as tensors, rather than lists of (lists of...) tensors.
  2. This is needed because `SparseTensorValue` is implemented as a `namedtuple`
    that would normally be flattened and we want to be able to create sparse
    tensor from `SparseTensorValue's similarly to creating tensors from numpy
    arrays.
  COREDATAN)__name__
__module____qualname____doc__r
   r        P/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/util/nest_util.pyr	   r	   L   s    &P 
$	$r   r	   c                       e Zd Zg Zd Zd Zy)
_DotStringc                      yN.r   selfs    r   __str__z_DotString.__str__|       r   c                      yr   r   r   s    r   __repr__z_DotString.__repr__   r   r   N)r   r   r   	__slots__r   r   r   r   r   r   r   y   s    )r   r   c                     | t         j                  k(  rt        |      S | t         j                  k(  rt	        |      S t        dj                  |             )aq  Returns true if its input is a nested structure.

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

  Args:
    modality: enum value of supported modality [Modality.CORE or Modality.DATA]
    structure: the value to test.

  Returns:
    True if the input is a nested structure.
  -Unknown modality used {} for nested structure)r	   r
   _tf_core_is_nestedr   _tf_data_is_nested
ValueErrorformat)modality	structures     r   	is_nestedr'      sM     i((8== i((
7>>xH r   c                 .    t        j                  | |      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stricts     r   is_namedtupler,      s     
	#	#Hf	55r   c                    t        |       rtt        t        t        |       |            t	        |       }|t
        j                  k(  r t        j                  | j                        }n |       }| D ]
  }|   ||<    |S t        |       r|t        t        t        |       |            t	        |       }t        |dd      s4t        j                  t        j                  dj                  |      d       	  |fd| D              S t        |       rt!        |      S t#        |       st%        |       r@t'        | t(        j*                        rt	        | j,                        }nt	        |       } || S t/        |       r0t1        |      dk(  sJ | j2                  }|j5                  |d         S t7        |       r$t1        |      dk(  sJ | j5                  |d         S t'        | t8              rt;        t!        |       |      S t'        | t(        j*                        r% t	        |       t;        | j,                  |            S t'        | t<              r.| j?                         d   }| jA                  |tC        |            S  t	        |       |      S # t        $ r*}t        dj                  t	        |       | |            d}~ww xY w)	a_  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`.
  __supported_by_tf_nest__FzPMapping types may not work well with tf.nest. Prefer using MutableMapping for {}   c              3   ,   K   | ]  }||   f  y wNr   ).0keyresults     r   	<genexpr>z sequence_like.<locals>.<genexpr>   s     B#C-Bs   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zip_tf_core_sortedtype_collectionsdefaultdictdefault_factory_is_mappinggetattrr   log_first_nWARNr$   	TypeError_is_mapping_viewlistr,   	_is_attrs
isinstance_wraptObjectProxy__wrapped___is_composite_tensorlen
_type_spec_from_components_is_type_specrangesequence_liker   __tf_flatten____tf_unflatten__tuple)	r*   argsinstance_typedr3   errspecmetadatar4   s	           @r   rP   rP      ss    " #oh/67FNM000

"
"8#;#;
<a
/a c{afH8#oh/67FNM="<eD
////5vm/D
		BBBB !:X)H"5(F../8//0m8nm$H%t9>>D  a))Xt9>>$$T!W--(E"h..(F../ 4>-(<(<dCDD(./&&(+H$$XuT{;; 4>$I  ( )/tH~x(M	 s   7J 	K%J??Kc                     t        | j                  d      }d |D        }|D cg c]  }|t        | |      f c}S c c}w )a<  Returns a list of (name, value) pairs from an attrs instance.

  TODO(b/268078256): check if this comment is valid, and if so, ensure it's
  handled in the function below.
  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              3   4   K   | ]  }|j                     y wr1   )name)r2   as     r   r5   z#_get_attrs_items.<locals>.<genexpr>
  s     &1&s   )r?   	__class__)objattrs
attr_names	attr_names       r   _get_attrs_itemsrd      s?     #--!2
3%&&*@J	K99gc9-
.	KK	Ks   <c                 f    	 t        | j                               S # t        $ r t        d      w xY w)HReturns a sorted list of the dict keys, with error if keys not sortable.z,nest only supports dicts with sortable keys.)sortedkeysrB   )dict_s    r   r9   r9     s6    D%**,	 D
B
CCDs    0c                 ~    	 t        t        |             S # t        $ r}t        d|j                         d}~ww xY w)rf   z4nest only supports dicts with sortable keys. Error: N)rg   rD   rB   message)ri   es     r   _tf_data_sortedrm     sA    $u+	 

>qyykJ s    	<7<c              #      K   | t         j                  k(  rt        |      E d{    y| t         j                  k(  rt	        |      E d{    yt        dj                  |             7 F7 !w)zYield elements of `iterable` in a deterministic order.

  Args:
    modality: enum value of supported modality [Modality.CORE or Modality.DATA]
    iterable: an iterable.

  Yields:
    The iterable elements in a deterministic order.
  Nr    )r	   r
   _tf_core_yield_valuer   _tf_data_yield_valuer#   r$   r%   iterables     r   yield_valuers   "  s`      #H---8== #H---
7>>xH 	 .-s!   "A/A+&A/A- A/-A/c              #   :   K   t        |       D ]	  \  }}|  y wr1   )_tf_core_yield_sorted_items)rr   _vs      r   ro   ro   6  s#     )(3 da
Gs   c                 r    | t         j                  k(  rt        |      S t        dj	                  |             )Nr    )r	   r
   ru   r#   r$   rq   s     r   yield_sorted_itemsry   ;  s4    &x00
7>>xH r   c              #   R  K   t        | t              rt        |       D ]  }|  yt        |       t        k(  rt        |       D ]  }|  yt        | t
        t        j                  f      rt        |       D ]  }|| |   f  yt        |       rt        |       D ]  }|  yt        |       r"| j                  D ]  }|t        | |      f  yt        |       r6| j                  }|j                   j"                  |j%                  |       f yt'        |       r%| j                   j"                  | j(                  f yt        | t*              r9| j-                         d   }t        |t              sJ t        |      E d{    yt        |       D ]  }|  y7 w)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.
  r/   N)rF   rD   	enumerater:   rS   r7   _collections_abcMappingr9   rE   rd   r,   _fieldsr?   rJ   rL   
value_typer   _to_componentsrN   _component_specsr   rQ   )rr   itemr3   field	type_specflat_components         r   ru   ru   D  s      $(# j H~(# j(T#3#;#;<= x( # * jX!! ,78U+++,H%##I



'
')A)A()K
KKX 


&
&(A(A
AA(./,,.q1Nne,,,((((# j )s   FF'
F%F'c              #     K   t        | t        j                        rt        |       D ]	  }| |     y| j                  j
                  dk(  r|  yt        |       rt        |       D ]	  \  }}|  yt        | t              r0| j                         d   }t        |t              sJ |E d{    y| D ]  }|  y7 w)zYield elements of `iterable` in a deterministic order.

  Args:
    iterable: an iterable.

  Yields:
    The iterable elements in a deterministic order.
  SparseTensorValuer/   N)rF   r|   r}   rm   r_   r   rE   rd   r   rQ   rS   )rr   r3   rv   attrr   values         r   rp   rp   y  s      *223 x( SM ""&99
N#H- 4j(./,,.q1Nne,,, k s   B.C0C1Cc                     | t         j                  k(  rt        ||||       y| t         j                  k(  rt	        |||       yt        dj                  |             )a<  Asserts that two structures are nested in the same way.

  For Modality.CORE 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

  For Modality.DATA, nested structures are treated differently than
  Modality.CORE. Please refer to class Modality's documentation above to read up
  on these differences.

  Args:
    modality: enum value of supported modality [Modality.CORE or Modality.DATA]
    nest1: an atom or a nested structure.
    nest2: an atom or a nested structure.
    check_types: - For Modality.CORE: 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. - For Modality.DATA: if `True` (default)
      types of sequences should be same as well. For dictionary, "type" of
      dictionary is considered to include its keys. In other words, two
      dictionaries with different keys are considered to have a different
      "type". If set to `False`, two iterables are considered same as long as
      they yield the elements that have same structures.
    expand_composites: Arg only valid for Modality.CORE. 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`.
  r    N)r	   r
   _tf_core_assert_same_structurer   _tf_data_assert_same_structurer#   r$   )r%   nest1nest2check_typesexpand_compositess        r   assert_same_structurer     sS    B "5%>OP8== "5%=
7>>xH r   c                 ,   t        |      }t        |      }	 t        j                  | |||       y # t        t        f$ rS}t        t        d |             }t        t        d |            } t        |      t        |      d|d|      d }~ww xY w)Nc                     t         S r1   _DOTrv   s    r   <lambda>z0_tf_core_assert_same_structure.<locals>.<lambda>       r   c                     t         S r1   r   r   s    r   r   z0_tf_core_assert_same_structure.<locals>.<lambda>  r   r   z
Entire first structure:
z
Entire second structure:
)boolr   AssertSameStructurer#   rB   str_tf_core_map_structurer:   )r   r   r   r   rl   str1str2s          r   r   r   	  s    
 [!+,-
%%uk#4 i	  %ne<=D%ne<=D
$q'q64	 s   1 B ABBc                 2    t        j                  | ||       y r1   )r   AssertSameStructureForData)r   r   r   s      r   r   r     s    **5%Er   c                     g }|xs t         }t        |       D ]P  } ||      r-t        |||||      \  }}|j                   |||             |}8|j                  ||          |dz  }R ||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 structure 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/   )rP   ro   !_tf_core_packed_nest_with_indicesappend)	r&   flatindexis_nested_fnsequence_fnpackeds	new_indexchilds	            r   r   r   !  s    0 &,}+	* 	aA:
T5,i mmK5)*emmDK qje	 
r   c                     g }t        |       D ]T  }t        |      r.t        |||      \  }}|j                  t	        ||             |}<|j                  ||          |dz  }V ||fS )a  Helper function for pack_nest_as.

  Args:
    structure: Substructure (tuple of elements and/or tuples) to mimic
    flat: Flattened values to output substructure for.
    index: Index at which to start reading from flat.

  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 elements than `flat`
      (assuming indexing starts from `index`).
  r/   )rp   r"   !_tf_data_packed_nest_with_indicesr   rP   )r&   r   r   r   r   r   r   s          r   r   r   H  su    & &	* a!:1dEJimmM!U+,emmDK qje 
r   c                     | t         j                  k(  rt        ||      S | t         j                  k(  rt	        |      S t        dj                  |             )ak  Flattens a nested structure.

  - For Modality.CORE: 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:
    modality: enum value of supported modality [Modality.CORE or Modality.DATA]
    structure: an atom or a nested structure. Note, numpy arrays are considered
      atoms and are not flattened.
    expand_composites: Arg valid for Modality.CORE only. 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.
  r    )r	   r
   _tf_core_flattenr   _tf_data_flattenr#   r$   )r%   r&   r   s      r   flattenr   g  sQ    @ I'8998== I&&
7>>xH r   c                 N    | dgS t        |      }t        j                  | |      S )z=See comments for flatten() in tensorflow/python/util/nest.py.N)r   r   Flatten)r&   r   s     r   r   r     s/    6M,-			y*;	<<r   c                     | t         j                  k(  rt        ||||      S | t         j                  k(  rt	        ||      S t        dj                  |             )aj  Returns a given flattened sequence packed into a given structure.

  - For Modality.CORE: 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)>}

  - For Modality.DATA:  If `structure` is a scalar, `flat_sequence` must be a
  single-element list;
  in this case the return value is `flat_sequence[0]`.

  Args:
    modality: enum value of supported modality [Modality.CORE or Modality.DATA]
    structure: - For Modality.CORE: Nested structure, whose structure is given
      by nested lists, tuples, and dicts. Note: numpy arrays and strings are
      considered scalars. - For Modality.DATA: tuple or list constructed of
      scalars and/or other tuples/lists, or a scalar.  Note: numpy arrays are
      considered scalars.
    flat_sequence: flat sequence to pack.
    expand_composites: Arg valid for Modality.CORE only. If true, then composite
      tensors such as `tf.sparse.SparseTensor` and `tf.RaggedTensor` are
      expanded into their component tensors.
    sequence_fn: Arg valid for Modality.CORE only.

  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: For Modality.CORE only. `structure` is or contains a dict with
    non-sortable keys.
  r    )r	   r
   _tf_core_pack_sequence_asr   _tf_data_pack_sequence_asr#   r$   )r%   r&   flat_sequencer   r   s        r   pack_sequence_asr     s^    z $="3[  8== $Y>>
7>>xH r   c                 r   |rt         nt        }|xs t        }d } ||      s+t        dj	                   ||d      t        |                   ||       sZt        |      dk7  rGt        dj	                  t        |        || d      t        |      t        |       ||d                  |d   S 	 t        | |d||      \  }}|t        |      k  rt        	  ||       S # t        $ rK t        | |      }t        |      t        |      k7  r$t        dt        |      t        |      | |fz        Y \w xY w)	zDImplements sequence packing, with the option to alter the structure.c                 6    t        |       }|d | ||d  xr dz   S )Nz...)r   )r   length	value_strs      r   truncatez+_tf_core_pack_sequence_as.<locals>.truncatek  s)    E
IWf67!3!=>>r   zYAttempted 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   r   zsCould not pack sequence. Structure had %d atoms, but flat_sequence had %d items.  Structure: %s, flat_sequence: %s.)_is_nested_or_compositer!   rP   rB   r$   r:   rK   r#   r   
IndexErrorr   )	r&   r   r   r   r   r   final_indexr   flat_structures	            r   r   r   b  sw   
 "38J  ,}+? 
m	$
	**0&]C($}*=+
  
i	 
=Q??Ev9oy#&=!- }c*@
 
 ;=!\;K S'' ( 
Y	'' 
 
%%6N >c-00K #m"4iOP  1	
s   2&C" "AD65D6c                    t        |      s2t        |t              s"t        dt	        |      j
                   d      t        |       s+t        |      dk7  rt        dt        |       d      |d   S t        |       }t        |      t        |      k7  r*t        dt        |       dt        |       d	|  d
| d	      t        | |d      \  }}t        | |      S )a<  Returns a given flattened sequence packed into a nest.

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

  Args:
    structure: tuple or list constructed of scalars and/or other tuples/lists,
      or a scalar.  Note: numpy arrays are considered scalars.
    flat_sequence: flat sequence to pack.

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

  Raises:
    ValueError: If nest and structure have different element counts.
  z2Argument `flat_sequence` must be a sequence. Got ''.r/   z:Argument `structure` is a scalar but `len(flat_sequence)`=z > 1r   z2Could not pack sequence. Argument `structure` had z, elements, but argument `flat_sequence` had z elements. Received structure: z, flat_sequence: r   )r"   rF   rD   rB   r:   r   rK   r#   r   r   rP   )r&   r   r   rv   r   s        r   r   r     s   $ ]
+z-/N
	(()	- 
 
I	&
=Q""%m"4!5T;  #I..C..
<~
K}
=+&}oQ	8  0	=!L)!V	y&	))r   c                     | t         j                  k(  rt        |g|i |S | t         j                  k(  rt	        |g|i |S t        dj                  |             )a  Creates a new structure by applying `func` to each atom in `structure`.

  - For Modality.CORE: 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))

  - For Modality.DATA: Applies `func(x[0], x[1], ...)` where x[i] is an entry in
  `structure[i]`.  All structures in `structure` must have the same arity,
  and the return value will contain the results in the same structure.

  Args:
    modality: enum value of supported modality [Modality.CORE or Modality.DATA]
    func: A callable that accepts as many arguments as there are structures.
    *structure: - For Modality.CORE: atom or nested structure. - For
      Modality.DATA: scalar, or tuple or list of constructed scalars and/or
      other tuples/lists, or scalars.  Note: numpy arrays are considered
      scalars.
    **kwargs: Valid keyword args are: * `check_types`: - For Modality.CORE: 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. - For Modality.DATA: only valid keyword
      argument is `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`. * `expand_composites`: Valid for Modality.CORE only.
      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.
  r    )r	   r
   r   r   _tf_data_map_structurer#   r$   )r%   funcr&   kwargss       r   map_structurer     sb    B !$==f==8== !$==f==
7>>xH r   c           	         t        |       st        d| z        |st        d      |j                  dd      }|j                  dd      |r+t        ddj	                  |j                               z        |d	d  D ]  }t        |d
   ||        fd|D        }t        | }t        |d
   |D cg c]  } | | 	 c}      S c c}w )Nzfunc must be callable, got: %s#Must provide at least one structurer   Tr   FzQOnly valid keyword arguments are `check_types` and `expand_composites`, not: `%s`z`, `r/   r   r   r   c              3   6   K   | ]  }t        |        y wr1   )r   )r2   r   r   s     r   r5   z)_tf_core_map_structure.<locals>.<genexpr>L  s     Nq$Q(9:N   r   )	callablerB   r#   popjoinrh   r   r8   r   )	r   r&   r   r   otherr   entriesxr   s	           @r   r   r   3  s    	$
4t;
<<	
:
;;

=$/+jj!4e<
	)
++fkkm
$	%  } e"!+	 OIN. '	"l !AtQx!)
 !s   5C

c           	      F   t        |       st        d|        |st        d      |r'd|vst        |      dkD  rt        d| d      |d   }nd}|dd  D ]  }t	        |d   ||	        d
 |D        }t        | }t        |d   |D cg c]  } | | 	 c}      S c c}w )Nz'Argument `func` must be callable, got: r   r   r/   zIOnly valid keyword argument for `check_types_dict` is 'check_types'. Got r   Tr   r   c              3   2   K   | ]  }t        |        y wr1   )r   )r2   r   s     r   r5   z)_tf_data_map_structure.<locals>.<genexpr>k  s     ;A$Q';s   )r   rB   r#   rK   r   r8   r   )r   r&   check_types_dictr   r   r   r   r   s           r   r   r   W  s    	$
=dVD
EE	
:
;;,,4D0E0I  014  #=1KK} Qe"9Q<KPQ <;. '	"9Q<G1Lq$(1L	MM1Ls   B
c              #      K   | t         j                  k(  rt        ||||      E d{    y| t         j                  k(  rt	        ||      E d{    yt        dj                  |             7 G7 !w)a  Yields (path, value) pairs of input_tree flattened up to shallow_tree.

  - For Modality.CORE: See comments for _tf_core_yield_flat_up_to() below
  - For Modality.DATA: See comments for _tf_data_yield_flat_up_to() below

  Args:
    modality: enum value of supported modality [Modality.CORE or Modality.DATA]
    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: Arg valid for Modality.CORE only. Function used to test if a
      value should be treated as a nested structure.
    path: Arg valid for Modality.CORE only. 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.
  Nr    )r	   r
   _tf_core_yield_flat_up_tor   _tf_data_yield_flat_up_tor#   r$   )r%   shallow_tree
input_treer   paths        r   yield_flat_up_tor   q  st     , (j,   8== (zBBB
7>>xH  Cs!   %A3A/'A3A1 A31A3c              #      K    ||       s||f yt        t        |            }t        |       D ]-  \  }}||fz   }||   }t        ||||      D ]  \  }}	||	f  / yw)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.
  )r   N)r7   ru   r   )
r   r   r   r   shallow_keyshallow_subtreesubpathinput_subtree	leaf_path
leaf_values
             r   r   r     s     $ 
l	#
1*=>J 
%\	2	& 	~%g -m#<
=,W$ &
)Z *%%&	&s   A A"c              #      K   t        |       r<t        t        |       t        |            D ]  \  }}t        ||      D ]  }|   y| yw)zFYields elements `input_tree` partially flattened up to `shallow_tree`.N)r"   r8   rp   r   )r   r   shallow_branchinput_branch
input_leafs        r   r   r     s]     %(+\*,@,L) $ 2.,O * s   AAc                     | t         j                  k(  rt        ||||       y| t         j                  k(  rt	        |||       yt        dj                  |             )aU  Asserts that `shallow_tree` is a shallow structure of `input_tree`.

  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:
    modality: enum value of supported modality [Modality.CORE or Modality.DATA]
    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: Valid for Modality.CORE only. 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`.
  r    N)r	   r
   !_tf_core_assert_shallow_structurer   !_tf_data_assert_shallow_structurer#   r$   r%   r   r   r   r   s        r   assert_shallow_structurer     sX    ` %j+/@ 8== %lJL
7>>xH r   c                    |rt         nt        } ||       r ||      st        dt        |      z        t	        | t
        j                        rt        | j                        }nt        |       }|rt	        ||      st        | d      }t        |d      }|r@|r>t        | |      st        t        j                  t        |      t        |                   t	        | t              rt	        |t              rnt        |       st        |       rt        |      st        |      rnft	        | t        j                         rt	        |t        j                         s2t        t        j                  t        |      t        |                   t        |       st        |      rt        |      st        |      rt        |       s=t        |       s2t        t        j                  t        |      t        |                   t        |       r| n| j"                  j%                         }t        |      r|n|j"                  j%                         }	t'        |d      r2t'        |	d      r&|j)                         |	j)                         k(  xs d }
n|j+                  |	g      }
|
t-        d|d|	      t        |       r"t        |      st        dt        |      z        t/        |      t/        |       k7  r2t-        t0        j                  t/        |      t/        |                   t/        |      t/        |       k  r2t-        t2        j                  t/        |      t/        |       	            t	        | t        j                         r@t5        |       t5        |      z
  }|r't-        t6        j                  t9        |                  t;        t=        |       t=        |            D ]  \  }}t?        ||||
        y y )NzVIf shallow structure is a sequence, input must also be a sequence. Input has type: %s.F)
input_typeshallow_type_get_structurez(Incompatible CompositeTensor TypeSpecs: z vs. zWIf shallow structure is a TypeSpec, input must also be a TypeSpec.  Input has type: %s.)input_lengthshallow_length)
input_sizeshallow_sizer   ) r   r!   rB   r:   rF   rG   rH   rI   r,   same_namedtuples!STRUCTURES_HAVE_MISMATCHING_TYPESr$   rD   rJ   rN   r|   r}   rL   _without_tensor_nameshasattrr   most_specific_common_supertyper#   rK   #STRUCTURES_HAVE_MISMATCHING_LENGTHS$INPUT_TREE_SMALLER_THAN_SHALLOW_TREEsetSHALLOW_TREE_HAS_INVALID_KEYSrg   r8   ro   r   )r   r   r   r   r   r   shallow_is_namedtupleinput_is_namedtupletype_spec_1type_spec_2r4   absent_keysr   r   s                 r   r   r     s    "38J  ,
#   , 2 23,223l,'l:j,? ,L%@)*e<	#6j9/66!*-D<N 7   lD)jT.J 	 |
,l0K!*-z1J \#3#;#;
<%5%=%=>-44
+$|:L 5 
 	
 L)-A*-M
+}Z/H"<0M,4O -44
+$|:L 5 
 	
 <( &&	  &j1*z7L7L 
 
.	/G
'5 &&(K,F,F,HHPD 	 ;;[MJ	K)
 	
 
|	$:&2:
 	
 
ZC-	-/66 _S=N 7 
 	

 z?S..077z?\9J 8 
 	
 , 0 8 89%J7k	)001DE
 	
 ),\*Z() 	$ (

!-			a  r   c                    t        |       rct        |      s"t        dt        |      j                   d      |rMt	        |t        |             s8t        dt        |      j                   dt        |       j                   d      t        |      t        |       k7  r$t        dt        |       dt        |        d      |rt	        | t        j                        rmt        |      t        |       k7  r$t        dt        |       d	t        |        d      t        |j                               }t        | j                               } t        | |      D ]  \  }}t        |||
        y y )NzTIf shallow structure is a sequence, input must also be a sequence. Input has type: 'r   zPThe two structures don't have the same sequence type. Input structure has type 'z%', while shallow structure has type 'zSThe two structures don't have the same sequence length. Input structure has length z%, while shallow structure has length r   zFThe two structures don't have the same keys. Input structure has keys z#, while shallow structure has keys r   )r"   rB   r:   r   rF   rK   r#   r|   r}   r  rD   rg   itemsr8   r   )r   r   r   r   r   s        r   r   r     s    %j)":.778< 
 :j$|2DE!!%j!1!:!: ; <!!%l!3!<!< =RA  :#l++""%j/!2 3L)*!-  z,0@0H0HI	ZC-	-""&z"2!3 4\*+1.
 	

 ***,-jL..01l(+L*(E $'
,K? &r   c                     | t         j                  k(  rt        ||||      S | t         j                  k(  rt	        ||      S t        dj                  |             )a
  Flattens `input_tree` up to `shallow_tree`.

  - For Modality.CORE: 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:

  ```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:
    modality: enum value of supported modality [Modality.CORE or Modality.DATA]
    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: Arg valid for Modality.CORE only. 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	   r
   _tf_core_flatten_up_tor   _tf_data_flatten_up_tor#   r$   r   s        r   flatten_up_tor    s^    n !j+/@  8== !,
;;
7>>xH r   c                     |rt         nt        }t        | |||       t        | ||      D cg c]  \  }}|	 c}}S c c}}w )Nr   )r   r!   r   r   )r   r   r   r   r   rv   rw   s          r   r  r    sZ     "38J  $)	 ,

L

!Q 
  
s   >c                 D    t        | |       t        t        | |            S r1   )r   rD   r   )r   r   s     r   r  r  !  s    #L*=	'jA	BBr   c                     | t         j                  k(  rt        ||g|i |S | t         j                  k(  rt	        ||g| S t        dj                  |             )a
  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:
    modality: enum value of supported modality [Modality.CORE or Modality.DATA]
    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: Arg valid for Modality.CORE only. 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`.
  r    )r	   r
   -_tf_core_map_structure_with_tuple_paths_up_tor   _tf_data_map_structure_up_tor#   r$   )r%   r   r   inputsr   s        r   map_structure_up_tor  &  sn    T 8d#'-  8== 'dDVDD
7>>xH r   c                 ^   
 |st        d      |j                  dd      
|j                  dd      rt        nt        }|D ]  }t	         |
        
 fd|D        }d t         |d	   |      D        }t        |g| D cg c]
  } ||i | }	}t         |	
      S c c}w )zZSee comments for map_structure_with_tuple_paths_up_to() in tensorflow/python/util/nest.py.zCannot map over no sequencesr   Tr   Fr   c              3   <   K   | ]  }t        |         yw)r   N)r  )r2   r   r   r   r   s     r   r5   z@_tf_core_map_structure_with_tuple_paths_up_to.<locals>.<genexpr>  s1        


-	 s   c              3   &   K   | ]	  \  }}|  y wr1   r   )r2   r   rv   s      r   r5   z@_tf_core_map_structure_with_tuple_paths_up_to.<locals>.<genexpr>  s      
$ s   r   )r&   r   r   )r#   r   r   r!   r   r   r8   r   )r   r   r  r   r   r   flat_value_genflat_path_genrT   resultsr   r   s   `         @@r   r  r  |  s     

3
44

=$/+jj!4e<!28J   j%+	 ..
q	<- ),M(KN(K $dDF'  
#)
 s   B*c                      |st        d      |D ]  }t         |         fd|D        }t        | D cg c]  } || 	 }}t         |      S c c}w )Nz9Argument `inputs` is empty. Cannot map over no sequences.c              3   6   K   | ]  }t        |        y wr1   )r  )r2   r   r   s     r   r5   z/_tf_data_map_structure_up_to.<locals>.<genexpr>  s      ;E\:6r   )r&   r   )r#   r   r8   r   )r   r   r  r   all_flattened_up_totensorsr  s   `      r   r  r    sz    	
C   @j%lJ?@
IO ,/0C+DET7^E'E	"G
  Fs   A)F)TF)Tr1   )r   )Tr   collectionsr;   enumwraptrG   tensorflow.pythonr   tensorflow.python.platformr   tensorflow.python.utilr   tensorflow.python.util.compatr   r|   +tensorflow.python.util.custom_nest_protocolr   IsMappingViewrC   IsAttrsrE   IsCompositeTensorrJ   
IsTypeSpecrN   IsMutableMappingr6   	IsMappingr>   IsNestedForDatar"   FlattenForDatar   IsNestedr!   IsNestedOrCompositer   SameNamedtuplesr   r   r   r   r  Enumr	   objectr   r   r'   r,   rP   rd   r9   rm   rs   ro   ry   ru   rp   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   r   r   <module>r4     s   	 #   / 1 0 M J !.. !!	$66 ((#44 %%"22  // "++ ';;  00 J " $ %N *tyy *Z  |26K \L$D(
2j!J AFhZ 7<(F
 7;$N>gT= HLFT >B5(p**ZhX HN4D&D	  9| CHH +/%X `H CH*C
Sl-br   