__init__.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  1. # Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ==============================================================================
  15. """Functions for working with nested data structures."""
  16. from collections import abc as collections_abc
  17. import logging
  18. import sys
  19. from typing import Mapping, Sequence, Text, TypeVar, Union
  20. #import numpy as np # Added by 20231229
  21. from .sequence import _is_attrs
  22. from .sequence import _is_namedtuple
  23. from .sequence import _sequence_like
  24. from .sequence import _sorted
  25. # pylint: disable=g-import-not-at-top
  26. try:
  27. import wrapt
  28. ObjectProxy = wrapt.ObjectProxy
  29. except ImportError:
  30. class ObjectProxy(object):
  31. """Stub-class for `wrapt.ObjectProxy``."""
  32. try:
  33. from tree import _tree
  34. except ImportError:
  35. if "sphinx" not in sys.modules:
  36. raise
  37. print("Not find the file (_tree.cpython-310-x86_64-linux-gnu.so*). You need find it in https://colab.research.google.com/github/deepmind/graphcast/blob/master/graphcast_demo.ipynb, or you can rewrite _tree.py by our way. Added by 20231229 S.F. Sune, https://github.com/sfsun67")
  38. _tree = None
  39. # pylint: enable=g-import-not-at-top
  40. __all__ = [
  41. "is_nested",
  42. "assert_same_structure",
  43. "unflatten_as",
  44. "flatten",
  45. "flatten_up_to",
  46. "flatten_with_path",
  47. "flatten_with_path_up_to",
  48. "map_structure",
  49. "map_structure_up_to",
  50. "map_structure_with_path",
  51. "map_structure_with_path_up_to",
  52. "traverse",
  53. "MAP_TO_NONE",
  54. ]
  55. __version__ = "0.1.8"
  56. # Note: this is *not* the same as `six.string_types`, which in Python3 is just
  57. # `(str,)` (i.e. it does not include byte strings).
  58. _TEXT_OR_BYTES = (str, bytes)
  59. _SHALLOW_TREE_HAS_INVALID_KEYS = (
  60. "The shallow_tree's keys are not a subset of the input_tree's keys. The "
  61. "shallow_tree has the following keys that are not in the input_tree: {}.")
  62. _STRUCTURES_HAVE_MISMATCHING_TYPES = (
  63. "The two structures don't have the same sequence type. Input structure has "
  64. "type {input_type}, while shallow structure has type {shallow_type}.")
  65. _STRUCTURES_HAVE_MISMATCHING_LENGTHS = (
  66. "The two structures don't have the same sequence length. Input "
  67. "structure has length {input_length}, while shallow structure has length "
  68. "{shallow_length}."
  69. )
  70. _INPUT_TREE_SMALLER_THAN_SHALLOW_TREE = (
  71. "The input_tree has fewer elements than the shallow_tree. Input structure "
  72. "has length {input_size}, while shallow structure has length "
  73. "{shallow_size}.")
  74. _IF_SHALLOW_IS_SEQ_INPUT_MUST_BE_SEQ = (
  75. "If shallow structure is a sequence, input must also be a sequence. "
  76. "Input has type: {}.")
  77. _IF_SHALLOW_IS_SEQ_INPUT_MUST_BE_SEQ_WITH_PATH = (
  78. "If shallow structure is a sequence, input must also be a sequence. "
  79. "Input at path: {path} has type: {input_type}.")
  80. K = TypeVar("K")
  81. V = TypeVar("V")
  82. # A generic monomorphic structure type, e.g. ``StructureKV[Text, int]``
  83. # is an arbitrarily nested structure where keys must be of type ``Text``
  84. # and values are integers.
  85. StructureKV = Union[
  86. Sequence["StructureKV[K, V]"],
  87. Mapping[K, "StructureKV[K, V]"],
  88. V,
  89. ]
  90. # A specialization of ``StructureKV`` for the common case of ``Text`` keys.
  91. try:
  92. Structure = StructureKV[Text, V]
  93. except TypeError:
  94. # Older Python 3.5 and 3.6 releases do not always support such use
  95. # of generics. Specialize ``StructureKV`` manually.
  96. Structure = Union[Sequence["Structure[V]"], Mapping[Text, "Structure[V]"], V]
  97. def _get_attrs_items(obj):
  98. """Returns a list of (name, value) pairs from an attrs instance.
  99. The list will be sorted by name.
  100. Args:
  101. obj: an object.
  102. Returns:
  103. A list of (attr_name, attr_value) pairs.
  104. """
  105. return [(attr.name, getattr(obj, attr.name))
  106. for attr in obj.__class__.__attrs_attrs__]
  107. def _yield_value(iterable):
  108. for _, v in _yield_sorted_items(iterable):
  109. yield v
  110. def _yield_sorted_items(iterable):
  111. """Yield (key, value) pairs for `iterable` in a deterministic order.
  112. For Sequences, the key will be an int, the array index of a value.
  113. For Mappings, the key will be the dictionary key.
  114. For objects (e.g. namedtuples), the key will be the attribute name.
  115. In all cases, the keys will be iterated in sorted order.
  116. Args:
  117. iterable: an iterable.
  118. Yields:
  119. The iterable's (key, value) pairs, in order of sorted keys.
  120. """
  121. if isinstance(iterable, collections_abc.Mapping):
  122. # Iterate through dictionaries in a deterministic order by sorting the
  123. # keys. Notice this means that we ignore the original order of `OrderedDict`
  124. # instances. This is intentional, to avoid potential bugs caused by mixing
  125. # ordered and plain dicts (e.g., flattening a dict but using a
  126. # corresponding `OrderedDict` to pack it back).
  127. for key in _sorted(iterable):
  128. yield key, iterable[key]
  129. elif _is_attrs(iterable):
  130. for item in _get_attrs_items(iterable):
  131. yield item
  132. elif _is_namedtuple(iterable):
  133. for field in iterable._fields:
  134. yield (field, getattr(iterable, field))
  135. else:
  136. for item in enumerate(iterable):
  137. yield item
  138. def _num_elements(structure):
  139. if _is_attrs(structure):
  140. return len(getattr(structure.__class__, "__attrs_attrs__"))
  141. else:
  142. return len(structure)
  143. def is_nested(structure):
  144. """Checks if a given structure is nested.
  145. >>> tree.is_nested(42)
  146. False
  147. >>> tree.is_nested({"foo": 42})
  148. True
  149. Args:
  150. structure: A structure to check.
  151. Returns:
  152. `True` if a given structure is nested, i.e. is a sequence, a mapping,
  153. or a namedtuple, and `False` otherwise.
  154. """
  155. return _tree.is_sequence(structure)
  156. def flatten(structure):
  157. r"""Flattens a possibly nested structure into a list.
  158. >>> tree.flatten([[1, 2, 3], [4, [5], [[6]]]])
  159. [1, 2, 3, 4, 5, 6]
  160. If `structure` is not nested, the result is a single-element list.
  161. >>> tree.flatten(None)
  162. [None]
  163. >>> tree.flatten(1)
  164. [1]
  165. In the case of dict instances, the sequence consists of the values,
  166. sorted by key to ensure deterministic behavior. This is true also for
  167. :class:`~collections.OrderedDict` instances: their sequence order is
  168. ignored, the sorting order of keys is used instead. The same convention
  169. is followed in :func:`~tree.unflatten`. This correctly unflattens dicts
  170. and ``OrderedDict``\ s after they have been flattened, and also allows
  171. flattening an ``OrderedDict`` and then unflattening it back using a
  172. corresponding plain dict, or vice-versa.
  173. Dictionaries with non-sortable keys cannot be flattened.
  174. >>> tree.flatten({100: 'world!', 6: 'Hello'})
  175. ['Hello', 'world!']
  176. Args:
  177. structure: An arbitrarily nested structure.
  178. Returns:
  179. A list, the flattened version of the input `structure`.
  180. Raises:
  181. TypeError: If `structure` is or contains a mapping with non-sortable keys.
  182. """
  183. return _tree.flatten(structure)
  184. class _DotString(object):
  185. def __str__(self):
  186. return "."
  187. def __repr__(self):
  188. return "."
  189. _DOT = _DotString()
  190. def assert_same_structure(a, b, check_types=True):
  191. """Asserts that two structures are nested in the same way.
  192. >>> tree.assert_same_structure([(0, 1)], [(2, 3)])
  193. Note that namedtuples with identical name and fields are always considered
  194. to have the same shallow structure (even with `check_types=True`).
  195. >>> Foo = collections.namedtuple('Foo', ['a', 'b'])
  196. >>> AlsoFoo = collections.namedtuple('Foo', ['a', 'b'])
  197. >>> tree.assert_same_structure(Foo(0, 1), AlsoFoo(2, 3))
  198. Named tuples with different names are considered to have different shallow
  199. structures:
  200. >>> Bar = collections.namedtuple('Bar', ['a', 'b'])
  201. >>> tree.assert_same_structure(Foo(0, 1), Bar(2, 3))
  202. Traceback (most recent call last):
  203. ...
  204. TypeError: The two structures don't have the same nested structure.
  205. ...
  206. Args:
  207. a: an arbitrarily nested structure.
  208. b: an arbitrarily nested structure.
  209. check_types: if `True` (default) types of sequences are checked as
  210. well, including the keys of dictionaries. If set to `False`, for example
  211. a list and a tuple of objects will look the same if they have the same
  212. size. Note that namedtuples with identical name and fields are always
  213. considered to have the same shallow structure.
  214. Raises:
  215. ValueError: If the two structures do not have the same number of elements or
  216. if the two structures are not nested in the same way.
  217. TypeError: If the two structures differ in the type of sequence in any of
  218. their substructures. Only possible if `check_types` is `True`.
  219. """
  220. try:
  221. _tree.assert_same_structure(a, b, check_types)
  222. except (ValueError, TypeError) as e:
  223. str1 = str(map_structure(lambda _: _DOT, a))
  224. str2 = str(map_structure(lambda _: _DOT, b))
  225. raise type(e)("%s\n"
  226. "Entire first structure:\n%s\n"
  227. "Entire second structure:\n%s"
  228. % (e, str1, str2))
  229. def _packed_nest_with_indices(structure, flat, index):
  230. """Helper function for ``unflatten_as``.
  231. Args:
  232. structure: Substructure (list / tuple / dict) to mimic.
  233. flat: Flattened values to output substructure for.
  234. index: Index at which to start reading from flat.
  235. Returns:
  236. The tuple (new_index, child), where:
  237. * new_index - the updated index into `flat` having processed `structure`.
  238. * packed - the subset of `flat` corresponding to `structure`,
  239. having started at `index`, and packed into the same nested
  240. format.
  241. Raises:
  242. ValueError: if `structure` contains more elements than `flat`
  243. (assuming indexing starts from `index`).
  244. """
  245. packed = []
  246. for s in _yield_value(structure):
  247. if is_nested(s):
  248. new_index, child = _packed_nest_with_indices(s, flat, index)
  249. packed.append(_sequence_like(s, child))
  250. index = new_index
  251. else:
  252. packed.append(flat[index])
  253. index += 1
  254. return index, packed
  255. def unflatten_as(structure, flat_sequence):
  256. r"""Unflattens a sequence into a given structure.
  257. >>> tree.unflatten_as([[1, 2], [[3], [4]]], [5, 6, 7, 8])
  258. [[5, 6], [[7], [8]]]
  259. If `structure` is a scalar, `flat_sequence` must be a single-element list;
  260. in this case the return value is ``flat_sequence[0]``.
  261. >>> tree.unflatten_as(None, [1])
  262. 1
  263. If `structure` is or contains a dict instance, the keys will be sorted to
  264. pack the flat sequence in deterministic order. This is true also for
  265. :class:`~collections.OrderedDict` instances: their sequence order is
  266. ignored, the sorting order of keys is used instead. The same convention
  267. is followed in :func:`~tree.flatten`. This correctly unflattens dicts
  268. and ``OrderedDict``\ s after they have been flattened, and also allows
  269. flattening an ``OrderedDict`` and then unflattening it back using a
  270. corresponding plain dict, or vice-versa.
  271. Dictionaries with non-sortable keys cannot be unflattened.
  272. >>> tree.unflatten_as({1: None, 2: None}, ['Hello', 'world!'])
  273. {1: 'Hello', 2: 'world!'}
  274. Args:
  275. structure: Arbitrarily nested structure.
  276. flat_sequence: Sequence to unflatten.
  277. Returns:
  278. `flat_sequence` unflattened into `structure`.
  279. Raises:
  280. ValueError: If `flat_sequence` and `structure` have different
  281. element counts.
  282. TypeError: If `structure` is or contains a mapping with non-sortable keys.
  283. """
  284. if not is_nested(flat_sequence):
  285. raise TypeError("flat_sequence must be a sequence not a {}:\n{}".format(
  286. type(flat_sequence), flat_sequence))
  287. if not is_nested(structure):
  288. if len(flat_sequence) != 1:
  289. raise ValueError("Structure is a scalar but len(flat_sequence) == %d > 1"
  290. % len(flat_sequence))
  291. return flat_sequence[0]
  292. flat_structure = flatten(structure)
  293. if len(flat_structure) != len(flat_sequence):
  294. raise ValueError(
  295. "Could not pack sequence. Structure had %d elements, but flat_sequence "
  296. "had %d elements. Structure: %s, flat_sequence: %s."
  297. % (len(flat_structure), len(flat_sequence), structure, flat_sequence))
  298. _, packed = _packed_nest_with_indices(structure, flat_sequence, 0)
  299. return _sequence_like(structure, packed)
  300. def map_structure(func, *structures, **kwargs): # pylint: disable=redefined-builtin
  301. """Maps `func` through given structures.
  302. >>> structure = [[1], [2], [3]]
  303. >>> tree.map_structure(lambda v: v**2, structure)
  304. [[1], [4], [9]]
  305. >>> tree.map_structure(lambda x, y: x * y, structure, structure)
  306. [[1], [4], [9]]
  307. >>> Foo = collections.namedtuple('Foo', ['a', 'b'])
  308. >>> structure = Foo(a=1, b=2)
  309. >>> tree.map_structure(lambda v: v * 2, structure)
  310. Foo(a=2, b=4)
  311. Args:
  312. func: A callable that accepts as many arguments as there are structures.
  313. *structures: Arbitrarily nested structures of the same layout.
  314. **kwargs: The only valid keyword argument is `check_types`. If `True`
  315. (default) the types of components within the structures have
  316. to be match, e.g. ``tree.map_structure(func, [1], (1,))`` will raise
  317. a `TypeError`, otherwise this is not enforced. Note that namedtuples
  318. with identical name and fields are considered to be the same type.
  319. Returns:
  320. A new structure with the same layout as the given ones. If the
  321. `structures` have components of varying types, the resulting structure
  322. will use the same types as ``structures[0]``.
  323. Raises:
  324. TypeError: If `func` is not callable.
  325. ValueError: If the two structures do not have the same number of elements or
  326. if the two structures are not nested in the same way.
  327. TypeError: If `check_types` is `True` and any two `structures`
  328. differ in the types of their components.
  329. ValueError: If no structures were given or if a keyword argument other
  330. than `check_types` is provided.
  331. """
  332. if not callable(func):
  333. raise TypeError("func must be callable, got: %s" % func)
  334. if not structures:
  335. raise ValueError("Must provide at least one structure")
  336. check_types = kwargs.pop("check_types", True)
  337. if kwargs:
  338. raise ValueError(
  339. "Only valid keyword arguments are `check_types` "
  340. "not: `%s`" % ("`, `".join(kwargs.keys())))
  341. for other in structures[1:]:
  342. assert_same_structure(structures[0], other, check_types=check_types)
  343. return unflatten_as(structures[0],
  344. [func(*args) for args in zip(*map(flatten, structures))])
  345. def map_structure_with_path(func, *structures, **kwargs):
  346. """Maps `func` through given structures.
  347. This is a variant of :func:`~tree.map_structure` which accumulates
  348. a *path* while mapping through the structures. A path is a tuple of
  349. indices and/or keys which uniquely identifies the positions of the
  350. arguments passed to `func`.
  351. >>> tree.map_structure_with_path(
  352. ... lambda path, v: (path, v**2),
  353. ... [{"foo": 42}])
  354. [{'foo': ((0, 'foo'), 1764)}]
  355. Args:
  356. func: A callable that accepts a path and as many arguments as there are
  357. structures.
  358. *structures: Arbitrarily nested structures of the same layout.
  359. **kwargs: The only valid keyword argument is `check_types`. If `True`
  360. (default) the types of components within the structures have to be match,
  361. e.g. ``tree.map_structure_with_path(func, [1], (1,))`` will raise a
  362. `TypeError`, otherwise this is not enforced. Note that namedtuples with
  363. identical name and fields are considered to be the same type.
  364. Returns:
  365. A new structure with the same layout as the given ones. If the
  366. `structures` have components of varying types, the resulting structure
  367. will use the same types as ``structures[0]``.
  368. Raises:
  369. TypeError: If `func` is not callable or if the `structures` do not
  370. have the same layout.
  371. TypeError: If `check_types` is `True` and any two `structures`
  372. differ in the types of their components.
  373. ValueError: If no structures were given or if a keyword argument other
  374. than `check_types` is provided.
  375. """
  376. return map_structure_with_path_up_to(structures[0], func, *structures,
  377. **kwargs)
  378. def _yield_flat_up_to(shallow_tree, input_tree, path=()):
  379. """Yields (path, value) pairs of input_tree flattened up to shallow_tree.
  380. Args:
  381. shallow_tree: Nested structure. Traverse no further than its leaf nodes.
  382. input_tree: Nested structure. Return the paths and values from this tree.
  383. Must have the same upper structure as shallow_tree.
  384. path: Tuple. Optional argument, only used when recursing. The path from the
  385. root of the original shallow_tree, down to the root of the shallow_tree
  386. arg of this recursive call.
  387. Yields:
  388. Pairs of (path, value), where path the tuple path of a leaf node in
  389. shallow_tree, and value is the value of the corresponding node in
  390. input_tree.
  391. """
  392. if (isinstance(shallow_tree, _TEXT_OR_BYTES) or
  393. not (isinstance(shallow_tree, (collections_abc.Mapping,
  394. collections_abc.Sequence)) or
  395. _is_namedtuple(shallow_tree) or
  396. _is_attrs(shallow_tree))):
  397. yield (path, input_tree)
  398. else:
  399. input_tree = dict(_yield_sorted_items(input_tree))
  400. for shallow_key, shallow_subtree in _yield_sorted_items(shallow_tree):
  401. subpath = path + (shallow_key,)
  402. input_subtree = input_tree[shallow_key]
  403. for leaf_path, leaf_value in _yield_flat_up_to(shallow_subtree,
  404. input_subtree,
  405. path=subpath):
  406. yield (leaf_path, leaf_value)
  407. def _multiyield_flat_up_to(shallow_tree, *input_trees):
  408. """Same as `_yield_flat_up_to`, but takes multiple input trees."""
  409. zipped_iterators = zip(*[_yield_flat_up_to(shallow_tree, input_tree)
  410. for input_tree in input_trees])
  411. try:
  412. for paths_and_values in zipped_iterators:
  413. paths, values = zip(*paths_and_values)
  414. yield paths[:1] + values
  415. except KeyError as e:
  416. paths = locals().get("paths", ((),))
  417. raise ValueError(f"Could not find key '{e.args[0]}' in some `input_trees`. "
  418. "Please ensure the structure of all `input_trees` are "
  419. "compatible with `shallow_tree`. The last valid path "
  420. f"yielded was {paths[0]}.") from e
  421. def _assert_shallow_structure(shallow_tree,
  422. input_tree,
  423. path=None,
  424. check_types=True):
  425. """Asserts that `shallow_tree` is a shallow structure of `input_tree`.
  426. That is, this function recursively tests if each key in shallow_tree has its
  427. corresponding key in input_tree.
  428. Examples:
  429. The following code will raise an exception:
  430. >>> shallow_tree = {"a": "A", "b": "B"}
  431. >>> input_tree = {"a": 1, "c": 2}
  432. >>> _assert_shallow_structure(shallow_tree, input_tree)
  433. Traceback (most recent call last):
  434. ...
  435. ValueError: The shallow_tree's keys are not a subset of the input_tree's ...
  436. The following code will raise an exception:
  437. >>> shallow_tree = ["a", "b"]
  438. >>> input_tree = ["c", ["d", "e"], "f"]
  439. >>> _assert_shallow_structure(shallow_tree, input_tree)
  440. Traceback (most recent call last):
  441. ...
  442. ValueError: The two structures don't have the same sequence length. ...
  443. By setting check_types=False, we drop the requirement that corresponding
  444. nodes in shallow_tree and input_tree have to be the same type. Sequences
  445. are treated equivalently to Mappables that map integer keys (indices) to
  446. values. The following code will therefore not raise an exception:
  447. >>> _assert_shallow_structure({0: "foo"}, ["foo"], check_types=False)
  448. Args:
  449. shallow_tree: an arbitrarily nested structure.
  450. input_tree: an arbitrarily nested structure.
  451. path: if not `None`, a tuple containing the current path in the nested
  452. structure. This is only used for more informative errror messages.
  453. check_types: if `True` (default) the sequence types of `shallow_tree` and
  454. `input_tree` have to be the same.
  455. Raises:
  456. TypeError: If `shallow_tree` is a sequence but `input_tree` is not.
  457. TypeError: If the sequence types of `shallow_tree` are different from
  458. `input_tree`. Only raised if `check_types` is `True`.
  459. ValueError: If the sequence lengths of `shallow_tree` are different from
  460. `input_tree`.
  461. """
  462. if is_nested(shallow_tree):
  463. if not is_nested(input_tree):
  464. if path is not None:
  465. raise TypeError(
  466. _IF_SHALLOW_IS_SEQ_INPUT_MUST_BE_SEQ_WITH_PATH.format(
  467. path=list(path), input_type=type(input_tree)))
  468. else:
  469. raise TypeError(
  470. _IF_SHALLOW_IS_SEQ_INPUT_MUST_BE_SEQ.format(
  471. type(input_tree)))
  472. if isinstance(shallow_tree, ObjectProxy):
  473. shallow_type = type(shallow_tree.__wrapped__)
  474. else:
  475. shallow_type = type(shallow_tree)
  476. if check_types and not isinstance(input_tree, shallow_type):
  477. # Duck-typing means that nest should be fine with two different
  478. # namedtuples with identical name and fields.
  479. shallow_is_namedtuple = _is_namedtuple(shallow_tree, False)
  480. input_is_namedtuple = _is_namedtuple(input_tree, False)
  481. if shallow_is_namedtuple and input_is_namedtuple:
  482. # pylint: disable=protected-access
  483. if not _tree.same_namedtuples(shallow_tree, input_tree):
  484. raise TypeError(_STRUCTURES_HAVE_MISMATCHING_TYPES.format(
  485. input_type=type(input_tree),
  486. shallow_type=shallow_type))
  487. # pylint: enable=protected-access
  488. elif not (isinstance(shallow_tree, collections_abc.Mapping)
  489. and isinstance(input_tree, collections_abc.Mapping)):
  490. raise TypeError(_STRUCTURES_HAVE_MISMATCHING_TYPES.format(
  491. input_type=type(input_tree),
  492. shallow_type=shallow_type))
  493. if _num_elements(input_tree) != _num_elements(shallow_tree):
  494. raise ValueError(
  495. _STRUCTURES_HAVE_MISMATCHING_LENGTHS.format(
  496. input_length=_num_elements(input_tree),
  497. shallow_length=_num_elements(shallow_tree)))
  498. elif _num_elements(input_tree) < _num_elements(shallow_tree):
  499. raise ValueError(
  500. _INPUT_TREE_SMALLER_THAN_SHALLOW_TREE.format(
  501. input_size=_num_elements(input_tree),
  502. shallow_size=_num_elements(shallow_tree)))
  503. shallow_iter = _yield_sorted_items(shallow_tree)
  504. input_iter = _yield_sorted_items(input_tree)
  505. def get_matching_input_branch(shallow_key):
  506. for input_key, input_branch in input_iter:
  507. if input_key == shallow_key:
  508. return input_branch
  509. raise ValueError(_SHALLOW_TREE_HAS_INVALID_KEYS.format([shallow_key]))
  510. for shallow_key, shallow_branch in shallow_iter:
  511. input_branch = get_matching_input_branch(shallow_key)
  512. _assert_shallow_structure(
  513. shallow_branch,
  514. input_branch,
  515. path + (shallow_key,) if path is not None else None,
  516. check_types=check_types)
  517. def flatten_up_to(shallow_structure, input_structure, check_types=True):
  518. """Flattens `input_structure` up to `shallow_structure`.
  519. All further nested components in `input_structure` are retained as-is.
  520. >>> structure = [[1, 1], [2, 2]]
  521. >>> tree.flatten_up_to([None, None], structure)
  522. [[1, 1], [2, 2]]
  523. >>> tree.flatten_up_to([None, [None, None]], structure)
  524. [[1, 1], 2, 2]
  525. If `shallow_structure` and `input_structure` are not nested, the
  526. result is a single-element list:
  527. >>> tree.flatten_up_to(42, 1)
  528. [1]
  529. >>> tree.flatten_up_to(42, [1, 2, 3])
  530. [[1, 2, 3]]
  531. Args:
  532. shallow_structure: A structure with the same (but possibly more shallow)
  533. layout as `input_structure`.
  534. input_structure: An arbitrarily nested structure.
  535. check_types: If `True`, check that each node in shallow_tree has the
  536. same type as the corresponding node in `input_structure`.
  537. Returns:
  538. A list, the partially flattened version of `input_structure` wrt
  539. `shallow_structure`.
  540. Raises:
  541. TypeError: If the layout of `shallow_structure` does not match that of
  542. `input_structure`.
  543. TypeError: If `check_types` is `True` and `shallow_structure` and
  544. `input_structure` differ in the types of their components.
  545. """
  546. _assert_shallow_structure(
  547. shallow_structure, input_structure, path=None, check_types=check_types)
  548. # Discard paths returned by _yield_flat_up_to.
  549. return [v for _, v in _yield_flat_up_to(shallow_structure, input_structure)]
  550. def flatten_with_path_up_to(shallow_structure,
  551. input_structure,
  552. check_types=True):
  553. """Flattens `input_structure` up to `shallow_structure`.
  554. This is a combination of :func:`~tree.flatten_up_to` and
  555. :func:`~tree.flatten_with_path`
  556. Args:
  557. shallow_structure: A structure with the same (but possibly more shallow)
  558. layout as `input_structure`.
  559. input_structure: An arbitrarily nested structure.
  560. check_types: If `True`, check that each node in shallow_tree has the
  561. same type as the corresponding node in `input_structure`.
  562. Returns:
  563. A list of ``(path, item)`` pairs corresponding to the partially flattened
  564. version of `input_structure` wrt `shallow_structure`.
  565. Raises:
  566. TypeError: If the layout of `shallow_structure` does not match that of
  567. `input_structure`.
  568. TypeError: If `input_structure` is or contains a mapping with non-sortable
  569. keys.
  570. TypeError: If `check_types` is `True` and `shallow_structure` and
  571. `input_structure` differ in the types of their components.
  572. """
  573. _assert_shallow_structure(
  574. shallow_structure, input_structure, path=(), check_types=check_types)
  575. return list(_yield_flat_up_to(shallow_structure, input_structure))
  576. def map_structure_up_to(shallow_structure, func, *structures, **kwargs):
  577. """Maps `func` through given structures up to `shallow_structure`.
  578. This is a variant of :func:`~tree.map_structure` which only maps
  579. the given structures up to `shallow_structure`. All further nested
  580. components are retained as-is.
  581. >>> structure = [[1, 1], [2, 2]]
  582. >>> tree.map_structure_up_to([None, None], len, structure)
  583. [2, 2]
  584. >>> tree.map_structure_up_to([None, [None, None]], str, structure)
  585. ['[1, 1]', ['2', '2']]
  586. Args:
  587. shallow_structure: A structure with layout common to all `structures`.
  588. func: A callable that accepts as many arguments as there are structures.
  589. *structures: Arbitrarily nested structures of the same layout.
  590. **kwargs: No valid keyword arguments.
  591. Raises:
  592. ValueError: If `func` is not callable or if `structures` have different
  593. layout or if the layout of `shallow_structure` does not match that of
  594. `structures` or if no structures were given.
  595. Returns:
  596. A new structure with the same layout as `shallow_structure`.
  597. """
  598. return map_structure_with_path_up_to(
  599. shallow_structure,
  600. lambda _, *args: func(*args), # Discards path.
  601. *structures,
  602. **kwargs)
  603. def map_structure_with_path_up_to(shallow_structure, func, *structures,
  604. **kwargs):
  605. """Maps `func` through given structures up to `shallow_structure`.
  606. This is a combination of :func:`~tree.map_structure_up_to` and
  607. :func:`~tree.map_structure_with_path`
  608. Args:
  609. shallow_structure: A structure with layout common to all `structures`.
  610. func: A callable that accepts a path and as many arguments as there are
  611. structures.
  612. *structures: Arbitrarily nested structures of the same layout.
  613. **kwargs: No valid keyword arguments.
  614. Raises:
  615. ValueError: If `func` is not callable or if `structures` have different
  616. layout or if the layout of `shallow_structure` does not match that of
  617. `structures` or if no structures were given.
  618. Returns:
  619. Result of repeatedly applying `func`. Has the same structure layout
  620. as `shallow_tree`.
  621. """
  622. if "check_types" in kwargs:
  623. logging.warning("The use of `check_types` is deprecated and does not have "
  624. "any effect.")
  625. del kwargs
  626. results = []
  627. for path_and_values in _multiyield_flat_up_to(shallow_structure, *structures):
  628. results.append(func(*path_and_values))
  629. return unflatten_as(shallow_structure, results)
  630. def flatten_with_path(structure):
  631. r"""Flattens a possibly nested structure into a list.
  632. This is a variant of :func:`~tree.flattens` which produces a list of
  633. pairs: ``(path, item)``. A path is a tuple of indices and/or keys
  634. which uniquely identifies the position of the corresponding ``item``.
  635. >>> tree.flatten_with_path([{"foo": 42}])
  636. [((0, 'foo'), 42)]
  637. Args:
  638. structure: An arbitrarily nested structure.
  639. Returns:
  640. A list of ``(path, item)`` pairs corresponding to the flattened version
  641. of the input `structure`.
  642. Raises:
  643. TypeError:
  644. If ``structure`` is or contains a mapping with non-sortable keys.
  645. """
  646. return list(_yield_flat_up_to(structure, structure))
  647. #: Special value for use with :func:`traverse`.
  648. MAP_TO_NONE = object()
  649. def traverse(fn, structure, top_down=True):
  650. """Traverses the given nested structure, applying the given function.
  651. The traversal is depth-first. If ``top_down`` is True (default), parents
  652. are returned before their children (giving the option to avoid traversing
  653. into a sub-tree).
  654. >>> visited = []
  655. >>> tree.traverse(visited.append, [(1, 2), [3], {"a": 4}], top_down=True)
  656. [(1, 2), [3], {'a': 4}]
  657. >>> visited
  658. [[(1, 2), [3], {'a': 4}], (1, 2), 1, 2, [3], 3, {'a': 4}, 4]
  659. >>> visited = []
  660. >>> tree.traverse(visited.append, [(1, 2), [3], {"a": 4}], top_down=False)
  661. [(1, 2), [3], {'a': 4}]
  662. >>> visited
  663. [1, 2, (1, 2), 3, [3], 4, {'a': 4}, [(1, 2), [3], {'a': 4}]]
  664. Args:
  665. fn: The function to be applied to each sub-nest of the structure.
  666. When traversing top-down:
  667. If ``fn(subtree) is None`` the traversal continues into the sub-tree.
  668. If ``fn(subtree) is not None`` the traversal does not continue into
  669. the sub-tree. The sub-tree will be replaced by ``fn(subtree)`` in the
  670. returned structure (to replace the sub-tree with None, use the special
  671. value :data:`MAP_TO_NONE`).
  672. When traversing bottom-up:
  673. If ``fn(subtree) is None`` the traversed sub-tree is returned unaltered.
  674. If ``fn(subtree) is not None`` the sub-tree will be replaced by
  675. ``fn(subtree)`` in the returned structure (to replace the sub-tree
  676. with None, use the special value :data:`MAP_TO_NONE`).
  677. structure: The structure to traverse.
  678. top_down: If True, parent structures will be visited before their children.
  679. Returns:
  680. The structured output from the traversal.
  681. """
  682. return traverse_with_path(lambda _, x: fn(x), structure, top_down=top_down)
  683. def traverse_with_path(fn, structure, top_down=True):
  684. """Traverses the given nested structure, applying the given function.
  685. The traversal is depth-first. If ``top_down`` is True (default), parents
  686. are returned before their children (giving the option to avoid traversing
  687. into a sub-tree).
  688. >>> visited = []
  689. >>> tree.traverse_with_path(
  690. ... lambda path, subtree: visited.append((path, subtree)),
  691. ... [(1, 2), [3], {"a": 4}],
  692. ... top_down=True)
  693. [(1, 2), [3], {'a': 4}]
  694. >>> visited == [
  695. ... ((), [(1, 2), [3], {'a': 4}]),
  696. ... ((0,), (1, 2)),
  697. ... ((0, 0), 1),
  698. ... ((0, 1), 2),
  699. ... ((1,), [3]),
  700. ... ((1, 0), 3),
  701. ... ((2,), {'a': 4}),
  702. ... ((2, 'a'), 4)]
  703. True
  704. >>> visited = []
  705. >>> tree.traverse_with_path(
  706. ... lambda path, subtree: visited.append((path, subtree)),
  707. ... [(1, 2), [3], {"a": 4}],
  708. ... top_down=False)
  709. [(1, 2), [3], {'a': 4}]
  710. >>> visited == [
  711. ... ((0, 0), 1),
  712. ... ((0, 1), 2),
  713. ... ((0,), (1, 2)),
  714. ... ((1, 0), 3),
  715. ... ((1,), [3]),
  716. ... ((2, 'a'), 4),
  717. ... ((2,), {'a': 4}),
  718. ... ((), [(1, 2), [3], {'a': 4}])]
  719. True
  720. Args:
  721. fn: The function to be applied to the path to each sub-nest of the structure
  722. and the sub-nest value.
  723. When traversing top-down: If ``fn(path, subtree) is None`` the traversal
  724. continues into the sub-tree. If ``fn(path, subtree) is not None`` the
  725. traversal does not continue into the sub-tree. The sub-tree will be
  726. replaced by ``fn(path, subtree)`` in the returned structure (to replace
  727. the sub-tree with None, use the special
  728. value :data:`MAP_TO_NONE`).
  729. When traversing bottom-up: If ``fn(path, subtree) is None`` the traversed
  730. sub-tree is returned unaltered. If ``fn(path, subtree) is not None`` the
  731. sub-tree will be replaced by ``fn(path, subtree)`` in the returned
  732. structure (to replace the sub-tree
  733. with None, use the special value :data:`MAP_TO_NONE`).
  734. structure: The structure to traverse.
  735. top_down: If True, parent structures will be visited before their children.
  736. Returns:
  737. The structured output from the traversal.
  738. """
  739. def traverse_impl(path, structure):
  740. """Recursive traversal implementation."""
  741. def subtree_fn(item):
  742. subtree_path, subtree = item
  743. return traverse_impl(path + (subtree_path,), subtree)
  744. def traverse_subtrees():
  745. if is_nested(structure):
  746. return _sequence_like(structure,
  747. map(subtree_fn, _yield_sorted_items(structure)))
  748. else:
  749. return structure
  750. if top_down:
  751. ret = fn(path, structure)
  752. if ret is None:
  753. return traverse_subtrees()
  754. elif ret is MAP_TO_NONE:
  755. return None
  756. else:
  757. return ret
  758. else:
  759. traversed_structure = traverse_subtrees()
  760. ret = fn(path, traversed_structure)
  761. if ret is None:
  762. return traversed_structure
  763. elif ret is MAP_TO_NONE:
  764. return None
  765. else:
  766. return ret
  767. return traverse_impl((), structure)