Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/tensorflow/python/util/nest.py: 51%

122 statements  

« prev     ^ index     » next       coverage.py v7.4.0, created at 2024-01-03 07:57 +0000

1# Copyright 2021 The TensorFlow Authors. 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 

16"""Functions that work with structures. 

17 

18A structure is either: 

19 

20* one of the recognized Python collections, holding _nested structures_; 

21* a value of any other type, typically a TensorFlow data type like Tensor, 

22 Variable, or of compatible types such as int, float, ndarray, etc. these are 

23 commonly referred to as _atoms_ of the structure. 

24 

25A structure of type `T` is a structure whose atomic items are of type `T`. 

26For example, a structure of `tf.Tensor` only contains `tf.Tensor` as its atoms. 

27 

28Historically a _nested structure_ was called a _nested sequence_ in TensorFlow. 

29A nested structure is sometimes called a _nest_ or a _tree_, but the formal 

30name _nested structure_ is preferred. 

31 

32Refer to [Nesting Data Structures] 

33(https://en.wikipedia.org/wiki/Nesting_(computing)#Data_structures). 

34 

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

36structures: 

37 

38* `collections.abc.Sequence` (except `string` and `bytes`). 

39 This includes `list`, `tuple`, and `namedtuple`. 

40* `collections.abc.Mapping` (with sortable keys). 

41 This includes `dict` and `collections.OrderedDict`. 

42* `collections.abc.MappingView` (with sortable keys). 

43* [`attr.s` classes](https://www.attrs.org/). 

44 

45Any other values are considered **atoms**. Not all collection types are 

46considered nested structures. For example, the following types are 

47considered atoms: 

48 

49* `set`; `{"a", "b"}` is an atom, while `["a", "b"]` is a nested structure. 

50* [`dataclass` classes](https://docs.python.org/library/dataclasses.html) 

51* `tf.Tensor` 

52* `numpy.array` 

53 

54`tf.nest.is_nested` checks whether an object is a nested structure or an atom. 

55For example: 

56 

57 >>> tf.nest.is_nested("1234") 

58 False 

59 >>> tf.nest.is_nested([1, 3, [4, 5]]) 

60 True 

61 >>> tf.nest.is_nested(((7, 8), (5, 6))) 

62 True 

63 >>> tf.nest.is_nested([]) 

64 True 

65 >>> tf.nest.is_nested({"a": 1, "b": 2}) 

66 True 

67 >>> tf.nest.is_nested({"a": 1, "b": 2}.keys()) 

68 True 

69 >>> tf.nest.is_nested({"a": 1, "b": 2}.values()) 

70 True 

71 >>> tf.nest.is_nested({"a": 1, "b": 2}.items()) 

72 True 

73 >>> tf.nest.is_nested(set([1, 2])) 

74 False 

75 >>> ones = tf.ones([2, 3]) 

76 >>> tf.nest.is_nested(ones) 

77 False 

78 

79Note: A proper structure shall form a tree. The user shall ensure there is no 

80cyclic references within the items in the structure, 

81i.e., no references in the structure of the input of these functions 

82should be recursive. The behavior is undefined if there is a cycle. 

83 

84""" 

85 

86import wrapt as _wrapt 

87 

88from tensorflow.python.util import _pywrap_nest 

89from tensorflow.python.util import _pywrap_utils 

90from tensorflow.python.util import nest_util 

91from tensorflow.python.util.compat import collections_abc as _collections_abc 

92from tensorflow.python.util.tf_export import tf_export 

93 

94 

95STRUCTURES_HAVE_MISMATCHING_LENGTHS = ( 

96 nest_util.STRUCTURES_HAVE_MISMATCHING_LENGTHS 

97) 

98 

99STRUCTURES_HAVE_MISMATCHING_TYPES = nest_util.STRUCTURES_HAVE_MISMATCHING_TYPES 

100 

101SHALLOW_TREE_HAS_INVALID_KEYS = nest_util.SHALLOW_TREE_HAS_INVALID_KEYS 

102 

103INPUT_TREE_SMALLER_THAN_SHALLOW_TREE = ( 

104 nest_util.INPUT_TREE_SMALLER_THAN_SHALLOW_TREE 

105) 

106 

107IF_SHALLOW_IS_SEQ_INPUT_MUST_BE_SEQ = ( 

108 "If shallow structure is a sequence, input must also be a sequence. " 

109 "Input has type: {}." 

110) 

111 

112is_namedtuple = nest_util.is_namedtuple 

113_is_namedtuple = nest_util.is_namedtuple 

114_is_attrs = _pywrap_utils.IsAttrs 

115_is_mapping = _pywrap_utils.IsMapping 

116same_namedtuples = nest_util.same_namedtuples 

117 

118 

119def _yield_value(iterable): 

120 return nest_util.yield_value(nest_util.Modality.CORE, iterable) 

121 

122 

123def _yield_sorted_items(iterable): 

124 return nest_util.yield_sorted_items(nest_util.Modality.CORE, iterable) 

125 

126 

127@tf_export("__internal__.nest.is_mapping", v1=[]) 

128def is_mapping(obj): 

129 """Returns a true if its input is a collections.Mapping.""" 

130 return _is_mapping(obj) 

131 

132 

133# TODO(b/225045380): Move to a "leaf" library to use in trace_type. 

134@tf_export("__internal__.nest.is_attrs", v1=[]) 

135def is_attrs(obj): 

136 """Returns a true if its input is an instance of an attr.s decorated class.""" 

137 return _is_attrs(obj) 

138 

139 

140@tf_export("__internal__.nest.sequence_like", v1=[]) 

141def _sequence_like(instance, args): 

142 """Converts the sequence `args` to the same type as `instance`. 

143 

144 Args: 

145 instance: an instance of `tuple`, `list`, `namedtuple`, `dict`, 

146 `collections.OrderedDict`, or `composite_tensor.Composite_Tensor` 

147 or `type_spec.TypeSpec`. 

148 args: items to be converted to the `instance` type. 

149 

150 Returns: 

151 `args` with the type of `instance`. 

152 """ 

153 return nest_util.sequence_like(instance, args) 

154 

155 

156_is_nested_or_composite = _pywrap_utils.IsNestedOrComposite 

157 

158 

159@tf_export("nest.is_nested") 

160def is_nested(seq): 

161 """Returns true if its input is a nested structure. 

162 

163 Refer to [tf.nest](https://www.tensorflow.org/api_docs/python/tf/nest) 

164 for the definition of a nested structure. 

165 

166 Args: 

167 seq: the value to test. 

168 

169 Returns: 

170 True if the input is a nested structure. 

171 """ 

172 return nest_util.is_nested(nest_util.Modality.CORE, seq) 

173 

174 

175def is_nested_or_composite(seq): 

176 """Returns true if its input is a nested structure or a composite. 

177 

178 Refer to [tf.nest](https://www.tensorflow.org/api_docs/python/tf/nest) 

179 for the definition of a nested structure. 

180 

181 Args: 

182 seq: the value to test. 

183 

184 Returns: 

185 True if the input is a nested structure or a composite. 

186 """ 

187 return _is_nested_or_composite(seq) 

188 

189 

190def is_sequence_or_composite(seq): 

191 return _is_nested_or_composite(seq) 

192 

193 

194@tf_export("nest.flatten") 

195def flatten(structure, expand_composites=False): 

196 """Returns a flat list from a given structure. 

197 

198 Refer to [tf.nest](https://www.tensorflow.org/api_docs/python/tf/nest) 

199 for the definition of a structure. 

200 

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

202 

203 This is the inverse of the `nest.pack_sequence_as` method that takes in a 

204 flattened list and re-packs it into the nested structure. 

205 

206 In the case of dict instances, the sequence consists of the values, sorted by 

207 key to ensure deterministic behavior. This is true also for OrderedDict 

208 instances: their sequence order is ignored, the sorting order of keys is used 

209 instead. The same convention is followed in `nest.pack_sequence_as`. This 

210 correctly repacks dicts and OrderedDicts after they have been flattened, and 

211 also allows flattening an OrderedDict and then repacking it back using a 

212 corresponding plain dict, or vice-versa. Dictionaries with non-sortable keys 

213 cannot be flattened. 

214 

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

216 running. 

217 

218 Examples: 

219 

220 1. Python dict (ordered by key): 

221 

222 >>> dict = { "key3": "value3", "key1": "value1", "key2": "value2" } 

223 >>> tf.nest.flatten(dict) 

224 ['value1', 'value2', 'value3'] 

225 

226 2. For a nested python tuple: 

227 

228 >>> tuple = ((1.0, 2.0), (3.0, 4.0, 5.0), 6.0) 

229 >>> tf.nest.flatten(tuple) 

230 [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] 

231 

232 3. For a nested dictionary of dictionaries: 

233 

234 >>> dict = { "key3": {"c": (1.0, 2.0), "a": (3.0)}, 

235 ... "key1": {"m": "val1", "g": "val2"} } 

236 >>> tf.nest.flatten(dict) 

237 ['val2', 'val1', 3.0, 1.0, 2.0] 

238 

239 4. Numpy array (will not flatten): 

240 

241 >>> array = np.array([[1, 2], [3, 4]]) 

242 >>> tf.nest.flatten(array) 

243 [array([[1, 2], 

244 [3, 4]])] 

245 

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

247 

248 >>> tensor = tf.constant([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]) 

249 >>> tf.nest.flatten(tensor) 

250 [<tf.Tensor: shape=(3, 3), dtype=float32, numpy= 

251 array([[1., 2., 3.], 

252 [4., 5., 6.], 

253 [7., 8., 9.]], dtype=float32)>] 

254 

255 6. `tf.RaggedTensor`: This is a composite tensor thats representation consists 

256 of a flattened list of 'values' and a list of 'row_splits' which indicate how 

257 to chop up the flattened list into different rows. For more details on 

258 `tf.RaggedTensor`, please visit 

259 https://www.tensorflow.org/api_docs/python/tf/RaggedTensor. 

260 

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

262 

263 >>> tensor = tf.ragged.constant([[3, 1, 4, 1], [], [5, 9, 2]]) 

264 >>> tf.nest.flatten(tensor, expand_composites=False) 

265 [<tf.RaggedTensor [[3, 1, 4, 1], [], [5, 9, 2]]>] 

266 

267 with `expand_composites=True`, we return the component Tensors that make up 

268 the RaggedTensor representation (the values and row_splits tensors) 

269 

270 >>> tensor = tf.ragged.constant([[3, 1, 4, 1], [], [5, 9, 2]]) 

271 >>> tf.nest.flatten(tensor, expand_composites=True) 

272 [<tf.Tensor: shape=(7,), dtype=int32, numpy=array([3, 1, 4, 1, 5, 9, 2], 

273 dtype=int32)>, 

274 <tf.Tensor: shape=(4,), dtype=int64, numpy=array([0, 4, 4, 7])>] 

275 

276 Args: 

277 structure: an atom or a nested structure. Note, numpy arrays are considered 

278 atoms and are not flattened. 

279 expand_composites: If true, then composite tensors such as 

280 `tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their 

281 component tensors. 

282 

283 Returns: 

284 A Python list, the flattened version of the input. 

285 

286 Raises: 

287 TypeError: The nest is or contains a dict with non-sortable keys. 

288 """ 

289 return nest_util.flatten( 

290 nest_util.Modality.CORE, structure, expand_composites 

291 ) 

292 

293 

294@tf_export("nest.assert_same_structure") 

295def assert_same_structure(nest1, nest2, check_types=True, 

296 expand_composites=False): 

297 """Asserts that two structures are nested in the same way. 

298 

299 Refer to [tf.nest](https://www.tensorflow.org/api_docs/python/tf/nest) 

300 for the definition of a structure. 

301 

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

303 

304 Examples: 

305 

306 * These atom vs. atom comparisons will pass: 

307 

308 >>> tf.nest.assert_same_structure(1.5, tf.Variable(1, tf.uint32)) 

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

310 

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

312 

313 >>> structure1 = (((1, 2), 3), 4, (5, 6)) 

314 >>> structure2 = ((("foo1", "foo2"), "foo3"), "foo4", ("foo5", "foo6")) 

315 >>> structure3 = [(("a", "b"), "c"), "d", ["e", "f"]] 

316 >>> tf.nest.assert_same_structure(structure1, structure2) 

317 >>> tf.nest.assert_same_structure(structure1, structure3, check_types=False) 

318 

319 >>> import collections 

320 >>> tf.nest.assert_same_structure( 

321 ... collections.namedtuple("bar", "a b")(1, 2), 

322 ... collections.namedtuple("foo", "a b")(2, 3), 

323 ... check_types=False) 

324 

325 >>> tf.nest.assert_same_structure( 

326 ... collections.namedtuple("bar", "a b")(1, 2), 

327 ... { "a": 1, "b": 2 }, 

328 ... check_types=False) 

329 

330 >>> tf.nest.assert_same_structure( 

331 ... { "a": 1, "b": 2, "c": 3 }, 

332 ... { "c": 6, "b": 5, "a": 4 }) 

333 

334 >>> ragged_tensor1 = tf.RaggedTensor.from_row_splits( 

335 ... values=[3, 1, 4, 1, 5, 9, 2, 6], 

336 ... row_splits=[0, 4, 4, 7, 8, 8]) 

337 >>> ragged_tensor2 = tf.RaggedTensor.from_row_splits( 

338 ... values=[3, 1, 4], 

339 ... row_splits=[0, 3]) 

340 >>> tf.nest.assert_same_structure( 

341 ... ragged_tensor1, 

342 ... ragged_tensor2, 

343 ... expand_composites=True) 

344 

345 * These examples will raise exceptions: 

346 

347 >>> tf.nest.assert_same_structure([0, 1], np.array([0, 1])) 

348 Traceback (most recent call last): 

349 ... 

350 ValueError: The two structures don't have the same nested structure 

351 

352 >>> tf.nest.assert_same_structure( 

353 ... collections.namedtuple('bar', 'a b')(1, 2), 

354 ... collections.namedtuple('foo', 'a b')(2, 3)) 

355 Traceback (most recent call last): 

356 ... 

357 TypeError: The two structures don't have the same nested structure 

358 

359 Args: 

360 nest1: an atom or a nested structure. 

361 nest2: an atom or a nested structure. 

362 check_types: if `True` (default) types of structures are checked as well, 

363 including the keys of dictionaries. If set to `False`, for example a list 

364 and a tuple of objects will look the same if they have the same size. Note 

365 that namedtuples with identical name and fields are always considered to 

366 have the same shallow structure. Two types will also be considered the 

367 same if they are both list subtypes (which allows "list" and 

368 "_ListWrapper" from trackable dependency tracking to compare equal). 

369 `check_types=True` only checks type of sub-structures. The types of atoms 

370 are not checked. 

371 expand_composites: If true, then composite tensors such as 

372 `tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their 

373 component tensors. 

374 

375 Raises: 

376 ValueError: If the two structures do not have the same number of atoms or 

377 if the two structures are not nested in the same way. 

378 TypeError: If the two structures differ in the type of sequence in any of 

379 their substructures. Only possible if `check_types` is `True`. 

380 """ 

381 nest_util.assert_same_structure( 

382 nest_util.Modality.CORE, nest1, nest2, check_types, expand_composites 

383 ) 

384 

385 

386def flatten_dict_items(dictionary): 

387 """Returns a dictionary with flattened keys and values. 

388 

389 This function flattens the keys and values of a dictionary, which can be 

390 arbitrarily nested structures, and returns the flattened version of such 

391 structures: 

392 

393 ```python 

394 example_dictionary = {(4, 5, (6, 8)): ("a", "b", ("c", "d"))} 

395 result = {4: "a", 5: "b", 6: "c", 8: "d"} 

396 flatten_dict_items(example_dictionary) == result 

397 ``` 

398 

399 The input dictionary must satisfy two properties: 

400 

401 1. Its keys and values should have the same exact nested structure. 

402 2. The set of all flattened keys of the dictionary must not contain repeated 

403 keys. 

404 

405 Args: 

406 dictionary: the dictionary to zip 

407 

408 Returns: 

409 The zipped dictionary. 

410 

411 Raises: 

412 TypeError: If the input is not a dictionary. 

413 ValueError: If any key and value do not have the same structure layout, or 

414 if keys are not unique. 

415 """ 

416 return _pywrap_nest.FlattenDictItems(dictionary) 

417 

418 

419@tf_export("nest.pack_sequence_as") 

420def pack_sequence_as(structure, flat_sequence, expand_composites=False): 

421 """Returns a given flattened sequence packed into a given structure. 

422 

423 Refer to [tf.nest](https://www.tensorflow.org/api_docs/python/tf/nest) 

424 for the definition of a structure. 

425 

426 If `structure` is an atom, `flat_sequence` must be a single-item list; 

427 in this case the return value is `flat_sequence[0]`. 

428 

429 If `structure` is or contains a dict instance, the keys will be sorted to 

430 pack the flat sequence in deterministic order. This is true also for 

431 `OrderedDict` instances: their sequence order is ignored, the sorting order of 

432 keys is used instead. The same convention is followed in `flatten`. 

433 This correctly repacks dicts and `OrderedDict`s after they have been 

434 flattened, and also allows flattening an `OrderedDict` and then repacking it 

435 back using a corresponding plain dict, or vice-versa. 

436 Dictionaries with non-sortable keys cannot be flattened. 

437 

438 Examples: 

439 

440 1. Python dict: 

441 

442 >>> structure = { "key3": "", "key1": "", "key2": "" } 

443 >>> flat_sequence = ["value1", "value2", "value3"] 

444 >>> tf.nest.pack_sequence_as(structure, flat_sequence) 

445 {'key3': 'value3', 'key1': 'value1', 'key2': 'value2'} 

446 

447 2. For a nested python tuple: 

448 

449 >>> structure = (('a','b'), ('c','d','e'), 'f') 

450 >>> flat_sequence = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] 

451 >>> tf.nest.pack_sequence_as(structure, flat_sequence) 

452 ((1.0, 2.0), (3.0, 4.0, 5.0), 6.0) 

453 

454 3. For a nested dictionary of dictionaries: 

455 

456 >>> structure = { "key3": {"c": ('alpha', 'beta'), "a": ('gamma')}, 

457 ... "key1": {"e": "val1", "d": "val2"} } 

458 >>> flat_sequence = ['val2', 'val1', 3.0, 1.0, 2.0] 

459 >>> tf.nest.pack_sequence_as(structure, flat_sequence) 

460 {'key3': {'c': (1.0, 2.0), 'a': 3.0}, 'key1': {'e': 'val1', 'd': 'val2'}} 

461 

462 4. Numpy array (considered a scalar): 

463 

464 >>> structure = ['a'] 

465 >>> flat_sequence = [np.array([[1, 2], [3, 4]])] 

466 >>> tf.nest.pack_sequence_as(structure, flat_sequence) 

467 [array([[1, 2], 

468 [3, 4]])] 

469 

470 5. tf.Tensor (considered a scalar): 

471 

472 >>> structure = ['a'] 

473 >>> flat_sequence = [tf.constant([[1., 2., 3.], [4., 5., 6.]])] 

474 >>> tf.nest.pack_sequence_as(structure, flat_sequence) 

475 [<tf.Tensor: shape=(2, 3), dtype=float32, 

476 numpy= array([[1., 2., 3.], [4., 5., 6.]], dtype=float32)>] 

477 

478 6. `tf.RaggedTensor`: This is a composite tensor thats representation consists 

479 of a flattened list of 'values' and a list of 'row_splits' which indicate how 

480 to chop up the flattened list into different rows. For more details on 

481 `tf.RaggedTensor`, please visit 

482 https://www.tensorflow.org/api_docs/python/tf/RaggedTensor. 

483 

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

485 

486 >>> structure = { "foo": tf.ragged.constant([[1, 2], [3]]), 

487 ... "bar": tf.constant([[5]]) } 

488 >>> flat_sequence = [ "one", "two" ] 

489 >>> tf.nest.pack_sequence_as(structure, flat_sequence, 

490 ... expand_composites=False) 

491 {'foo': 'two', 'bar': 'one'} 

492 

493 With `expand_composites=True`, we expect that the flattened input contains 

494 the tensors making up the ragged tensor i.e. the values and row_splits 

495 tensors. 

496 

497 >>> structure = { "foo": tf.ragged.constant([[1., 2.], [3.]]), 

498 ... "bar": tf.constant([[5.]]) } 

499 >>> tensors = tf.nest.flatten(structure, expand_composites=True) 

500 >>> print(tensors) 

501 [<tf.Tensor: shape=(1, 1), dtype=float32, numpy=array([[5.]], 

502 dtype=float32)>, 

503 <tf.Tensor: shape=(3,), dtype=float32, numpy=array([1., 2., 3.], 

504 dtype=float32)>, 

505 <tf.Tensor: shape=(3,), dtype=int64, numpy=array([0, 2, 3])>] 

506 >>> verified_tensors = [tf.debugging.check_numerics(t, 'invalid tensor: ') 

507 ... if t.dtype==tf.float32 else t 

508 ... for t in tensors] 

509 >>> tf.nest.pack_sequence_as(structure, verified_tensors, 

510 ... expand_composites=True) 

511 {'foo': <tf.RaggedTensor [[1.0, 2.0], [3.0]]>, 

512 'bar': <tf.Tensor: shape=(1, 1), dtype=float32, numpy=array([[5.]], 

513 dtype=float32)>} 

514 

515 Args: 

516 structure: Nested structure, whose structure is given by nested lists, 

517 tuples, and dicts. Note: numpy arrays and strings are considered 

518 scalars. 

519 flat_sequence: flat sequence to pack. 

520 expand_composites: If true, then composite tensors such as 

521 `tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their 

522 component tensors. 

523 

524 Returns: 

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

526 `structure`. 

527 

528 Raises: 

529 ValueError: If `flat_sequence` and `structure` have different 

530 atom counts. 

531 TypeError: `structure` is or contains a dict with non-sortable keys. 

532 """ 

533 return nest_util.pack_sequence_as( 

534 nest_util.Modality.CORE, structure, flat_sequence, expand_composites 

535 ) 

536 

537 

538@tf_export("nest.map_structure") 

539def map_structure(func, *structure, **kwargs): 

540 """Creates a new structure by applying `func` to each atom in `structure`. 

541 

542 Refer to [tf.nest](https://www.tensorflow.org/api_docs/python/tf/nest) 

543 for the definition of a structure. 

544 

545 Applies `func(x[0], x[1], ...)` where x[i] enumerates all atoms in 

546 `structure[i]`. All items in `structure` must have the same arity, 

547 and the return value will contain results with the same structure layout. 

548 

549 Examples: 

550 

551 * A single Python dict: 

552 

553 >>> a = {"hello": 24, "world": 76} 

554 >>> tf.nest.map_structure(lambda p: p * 2, a) 

555 {'hello': 48, 'world': 152} 

556 

557 * Multiple Python dictionaries: 

558 

559 >>> d1 = {"hello": 24, "world": 76} 

560 >>> d2 = {"hello": 36, "world": 14} 

561 >>> tf.nest.map_structure(lambda p1, p2: p1 + p2, d1, d2) 

562 {'hello': 60, 'world': 90} 

563 

564 * A single Python list: 

565 

566 >>> a = [24, 76, "ab"] 

567 >>> tf.nest.map_structure(lambda p: p * 2, a) 

568 [48, 152, 'abab'] 

569 

570 * Scalars: 

571 

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

573 7 

574 

575 * Empty structures: 

576 

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

578 () 

579 

580 * Check the types of iterables: 

581 

582 >>> s1 = (((1, 2), 3), 4, (5, 6)) 

583 >>> s1_list = [[[1, 2], 3], 4, [5, 6]] 

584 >>> tf.nest.map_structure(lambda x, y: None, s1, s1_list) 

585 Traceback (most recent call last): 

586 ... 

587 TypeError: The two structures don't have the same nested structure 

588 

589 * Type check is set to False: 

590 

591 >>> s1 = (((1, 2), 3), 4, (5, 6)) 

592 >>> s1_list = [[[1, 2], 3], 4, [5, 6]] 

593 >>> tf.nest.map_structure(lambda x, y: None, s1, s1_list, check_types=False) 

594 (((None, None), None), None, (None, None)) 

595 

596 Args: 

597 func: A callable that accepts as many arguments as there are structures. 

598 *structure: atom or nested structure. 

599 **kwargs: Valid keyword args are: 

600 * `check_types`: If set to `True` (default) the types of iterables within 

601 the structures have to be same (e.g. `map_structure(func, [1], (1,))` 

602 raises a `TypeError` exception). To allow this set this argument to 

603 `False`. Note that namedtuples with identical name and fields are always 

604 considered to have the same shallow structure. 

605 * `expand_composites`: If set to `True`, then composite tensors such as 

606 `tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their 

607 component tensors. If `False` (the default), then composite tensors are 

608 not expanded. 

609 

610 Returns: 

611 A new structure with the same arity as `structure[0]`, whose atoms 

612 correspond to `func(x[0], x[1], ...)` where `x[i]` is the atom in the 

613 corresponding location in `structure[i]`. If there are different structure 

614 types and `check_types` is `False` the structure types of the first 

615 structure will be used. 

616 

617 Raises: 

618 TypeError: If `func` is not callable or if the structures do not match 

619 each other by depth tree. 

620 ValueError: If no structure is provided or if the structures do not match 

621 each other by type. 

622 ValueError: If wrong keyword arguments are provided. 

623 """ 

624 return nest_util.map_structure( 

625 nest_util.Modality.CORE, func, *structure, **kwargs 

626 ) 

627 

628 

629def map_structure_with_paths(func, *structure, **kwargs): 

630 """Applies `func` to each entry in `structure` and returns a new structure. 

631 

632 Applies `func(path, x[0], x[1], ..., **kwargs)` where x[i] is an entry in 

633 `structure[i]` and `path` is the common path to x[i] in the structures. All 

634 structures in `structure` must have the same arity, and the return value will 

635 contain the results with the same structure layout. Special kwarg 

636 `check_types` determines whether the types of iterables within the structure 

637 must be the same-- see **kwargs definition below. 

638 

639 Args: 

640 func: A callable with the signature func(path, *values, **kwargs) that is 

641 evaluated on the leaves of the structure. 

642 *structure: A variable number of compatible structures to process. 

643 **kwargs: Optional kwargs to be passed through to func. Special kwarg 

644 `check_types` is not passed to func, but instead determines whether the 

645 types of iterables within the structures have to be same (e.g., 

646 `map_structure(func, [1], (1,))` raises a `TypeError` exception). By 

647 default, the types must match. To allow iteration over structures of 

648 different types (but common arity), set this kwarg to `False`. 

649 

650 Returns: 

651 A structure of the same form as the input structures whose leaves are the 

652 result of evaluating func on corresponding leaves of the input structures. 

653 

654 Raises: 

655 TypeError: If `func` is not callable or if the structures do not match 

656 each other by depth tree. 

657 TypeError: If `check_types` is not `False` and the two structures differ in 

658 the type of sequence in any of their substructures. 

659 ValueError: If no structures are provided. 

660 """ 

661 def wrapper_func(tuple_path, *inputs, **kwargs): 

662 string_path = "/".join(str(s) for s in tuple_path) 

663 return func(string_path, *inputs, **kwargs) 

664 

665 return nest_util.map_structure_up_to( 

666 nest_util.Modality.CORE, structure[0], wrapper_func, *structure, **kwargs 

667 ) 

668 

669 

670def map_structure_with_tuple_paths(func, *structure, **kwargs): 

671 """Applies `func` to each entry in `structure` and returns a new structure. 

672 

673 Applies `func(tuple_path, x[0], x[1], ..., **kwargs)` where `x[i]` is an entry 

674 in `structure[i]` and `tuple_path` is a tuple of indices and/or dictionary 

675 keys (as returned by `nest.yield_flat_paths`), which uniquely specifies the 

676 common path to x[i] in the structures. All structures in `structure` must have 

677 the same arity, and the return value will contain the results in the same 

678 structure. Special kwarg `check_types` determines whether the types of 

679 iterables within the structure must be the same-- see **kwargs definition 

680 below. 

681 

682 Args: 

683 func: A callable with the signature `func(tuple_path, *values, **kwargs)` 

684 that is evaluated on the leaves of the structure. 

685 *structure: A variable number of compatible structures to process. 

686 **kwargs: Optional kwargs to be passed through to func. Special kwarg 

687 `check_types` is not passed to func, but instead determines whether the 

688 types of iterables within the structures have to be same (e.g. 

689 `map_structure(func, [1], (1,))` raises a `TypeError` exception). To allow 

690 this set this argument to `False`. 

691 

692 Returns: 

693 A structure of the same form as the input structures whose leaves are the 

694 result of evaluating func on corresponding leaves of the input structures. 

695 

696 Raises: 

697 TypeError: If `func` is not callable or if the structures do not match 

698 each other by depth tree. 

699 TypeError: If `check_types` is not `False` and the two structures differ in 

700 the type of sequence in any of their substructures. 

701 ValueError: If no structures are provided. 

702 """ 

703 return nest_util.map_structure_up_to( 

704 nest_util.Modality.CORE, structure[0], func, *structure, **kwargs 

705 ) 

706 

707 

708def assert_shallow_structure(shallow_tree, 

709 input_tree, 

710 check_types=True, 

711 expand_composites=False): 

712 """Asserts that `shallow_tree` is a shallow structure of `input_tree`. 

713 

714 That is, this function tests if the `input_tree` structure can be created from 

715 the `shallow_tree` structure by replacing its leaf nodes with deeper 

716 tree structures. 

717 

718 Examples: 

719 

720 The following code will raise an exception: 

721 ```python 

722 shallow_tree = {"a": "A", "b": "B"} 

723 input_tree = {"a": 1, "c": 2} 

724 assert_shallow_structure(shallow_tree, input_tree) 

725 ``` 

726 

727 The following code will raise an exception: 

728 ```python 

729 shallow_tree = ["a", "b"] 

730 input_tree = ["c", ["d", "e"], "f"] 

731 assert_shallow_structure(shallow_tree, input_tree) 

732 ``` 

733 

734 Args: 

735 shallow_tree: an arbitrarily nested structure. 

736 input_tree: an arbitrarily nested structure. 

737 check_types: if `True` (default) the sequence types of `shallow_tree` and 

738 `input_tree` have to be the same. Note that even with check_types==True, 

739 this function will consider two different namedtuple classes with the same 

740 name and _fields attribute to be the same class. 

741 expand_composites: If true, then composite tensors such as 

742 `tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their 

743 component tensors. 

744 Raises: 

745 TypeError: If `shallow_tree` is a sequence but `input_tree` is not. 

746 TypeError: If the sequence types of `shallow_tree` are different from 

747 `input_tree`. Only raised if `check_types` is `True`. 

748 ValueError: If the sequence lengths of `shallow_tree` are different from 

749 `input_tree`. 

750 """ 

751 nest_util.assert_shallow_structure( 

752 nest_util.Modality.CORE, 

753 shallow_tree, 

754 input_tree, 

755 check_types, 

756 expand_composites, 

757 ) 

758 

759 

760@tf_export("__internal__.nest.flatten_up_to", v1=[]) 

761def flatten_up_to(shallow_tree, input_tree, check_types=True, 

762 expand_composites=False): 

763 """Flattens `input_tree` up to `shallow_tree`. 

764 

765 Refer to [tf.nest](https://www.tensorflow.org/api_docs/python/tf/nest) 

766 for the definition of a structure. 

767 

768 Any further depth in structure in `input_tree` is retained as structures in 

769 the partially flatten output. 

770 

771 If `shallow_tree` and `input_tree` are atoms, this returns a 

772 single-item list: `[input_tree]`. 

773 

774 Use Case: 

775 

776 Sometimes we may wish to partially flatten a structure, retaining some 

777 of the nested structure. We achieve this by specifying a shallow structure, 

778 `shallow_tree`, we wish to flatten up to. 

779 

780 The input, `input_tree`, can be thought of as having the same structure layout 

781 as `shallow_tree`, but with leaf nodes that are themselves tree structures. 

782 

783 Examples: 

784 

785 ```python 

786 input_tree = [[[2, 2], [3, 3]], [[4, 9], [5, 5]]] 

787 shallow_tree = [[True, True], [False, True]] 

788 

789 flattened_input_tree = flatten_up_to(shallow_tree, input_tree) 

790 flattened_shallow_tree = flatten_up_to(shallow_tree, shallow_tree) 

791 

792 # Output is: 

793 # [[2, 2], [3, 3], [4, 9], [5, 5]] 

794 # [True, True, False, True] 

795 ``` 

796 

797 ```python 

798 input_tree = [[('a', 1), [('b', 2), [('c', 3), [('d', 4)]]]]] 

799 shallow_tree = [['level_1', ['level_2', ['level_3', ['level_4']]]]] 

800 

801 input_tree_flattened_as_shallow_tree = flatten_up_to(shallow_tree, input_tree) 

802 input_tree_flattened = flatten(input_tree) 

803 

804 # Output is: 

805 # [('a', 1), ('b', 2), ('c', 3), ('d', 4)] 

806 # ['a', 1, 'b', 2, 'c', 3, 'd', 4] 

807 ``` 

808 

809 Edge Cases for atoms: 

810 

811 ```python 

812 flatten_up_to(0, 0) # Output: [0] 

813 flatten_up_to(0, [0, 1, 2]) # Output: [[0, 1, 2]] 

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

815 flatten_up_to([0, 1, 2], [0, 1, 2]) # Output: [0, 1, 2] 

816 ``` 

817 

818 Args: 

819 shallow_tree: a possibly pruned structure of input_tree. 

820 input_tree: an atom or a nested structure. 

821 Note, numpy arrays are considered atoms. 

822 check_types: bool. If True, check that each node in shallow_tree has the 

823 same type as the corresponding node in input_tree. 

824 expand_composites: If true, then composite tensors such as 

825 `tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their 

826 component tensors. 

827 

828 Returns: 

829 A Python list, the partially flattened version of `input_tree` according to 

830 the structure of `shallow_tree`. 

831 

832 Raises: 

833 TypeError: If `shallow_tree` is a nested structure but `input_tree` is not. 

834 TypeError: If the structure types of `shallow_tree` are different from 

835 `input_tree`. 

836 ValueError: If the structure lengths of `shallow_tree` are different from 

837 `input_tree`. 

838 """ 

839 return nest_util.flatten_up_to( 

840 nest_util.Modality.CORE, 

841 shallow_tree, 

842 input_tree, 

843 check_types, 

844 expand_composites, 

845 ) 

846 

847 

848def flatten_with_tuple_paths_up_to(shallow_tree, 

849 input_tree, 

850 check_types=True, 

851 expand_composites=False): 

852 """Flattens `input_tree` up to `shallow_tree`. 

853 

854 Any further depth in structure in `input_tree` is retained as structures in 

855 the partially flattened output. 

856 

857 Returns a list of (path, value) pairs, where value a leaf node in the 

858 flattened tree, and path is the tuple path of that leaf in input_tree. 

859 

860 If `shallow_tree` and `input_tree` are not sequences, this returns a 

861 single-item list: `[((), input_tree)]`. 

862 

863 Use Case: 

864 

865 Sometimes we may wish to partially flatten a nested sequence, retaining some 

866 of the nested structure. We achieve this by specifying a shallow structure, 

867 `shallow_tree`, we wish to flatten up to. 

868 

869 The input, `input_tree`, can be thought of as having the same structure layout 

870 as `shallow_tree`, but with leaf nodes that are themselves tree structures. 

871 

872 Examples: 

873 

874 ```python 

875 input_tree = [[[2, 2], [3, 3]], [[4, 9], [5, 5]]] 

876 shallow_tree = [[True, True], [False, True]] 

877 

878 flattened_input_tree = flatten_with_tuple_paths_up_to(shallow_tree, 

879 input_tree) 

880 flattened_shallow_tree = flatten_with_tuple_paths_up_to(shallow_tree, 

881 shallow_tree) 

882 

883 # Output is: 

884 # [((0, 0), [2, 2]), 

885 # ((0, 1), [3, 3]), 

886 # ((1, 0), [4, 9]), 

887 # ((1, 1), [5, 5])] 

888 # 

889 # [((0, 0), True), 

890 # ((0, 1), True), 

891 # ((1, 0), False), 

892 # ((1, 1), True)] 

893 ``` 

894 

895 ```python 

896 input_tree = [[('a', 1), [('b', 2), [('c', 3), [('d', 4)]]]]] 

897 shallow_tree = [['level_1', ['level_2', ['level_3', ['level_4']]]]] 

898 

899 input_tree_flattened_as_shallow_tree = flatten_up_to(shallow_tree, input_tree) 

900 input_tree_flattened = flatten(input_tree) 

901 

902 # Output is: 

903 # [((0, 0), ('a', 1)), 

904 # ((0, 1, 0), ('b', 2)), 

905 # ((0, 1, 1, 0), ('c', 3)), 

906 # ((0, 1, 1, 1), ('d', 4))] 

907 # ['a', 1, 'b', 2, 'c', 3, 'd', 4] 

908 ``` 

909 

910 Non-Sequence Edge Cases: 

911 

912 ```python 

913 flatten_with_tuple_paths_up_to(0, 0) # Output: [(), 0] 

914 

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

916 

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

918 

919 flatten_with_tuple_paths_up_to([0, 1, 2], [0, 1, 2]) 

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

921 ``` 

922 

923 Args: 

924 shallow_tree: a possibly pruned structure of input_tree. 

925 input_tree: an atom or a nested structure. 

926 Note, numpy arrays are considered atoms. 

927 check_types: bool. If True, check that each node in shallow_tree has the 

928 same type as the corresponding node in input_tree. 

929 expand_composites: If true, then composite tensors such as 

930 `tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their 

931 component tensors. 

932 

933 Returns: 

934 A Python list, the partially flattened version of `input_tree` according to 

935 the structure of `shallow_tree`. 

936 

937 Raises: 

938 TypeError: If `shallow_tree` is a nested structure but `input_tree` is not. 

939 TypeError: If the structure types of `shallow_tree` are different from 

940 `input_tree`. 

941 ValueError: If the structure lengths of `shallow_tree` are different from 

942 `input_tree`. 

943 """ 

944 is_nested_fn = _is_nested_or_composite if expand_composites else is_nested 

945 assert_shallow_structure(shallow_tree, 

946 input_tree, 

947 check_types=check_types, 

948 expand_composites=expand_composites) 

949 return list( 

950 nest_util.yield_flat_up_to( 

951 nest_util.Modality.CORE, shallow_tree, input_tree, is_nested_fn 

952 ) 

953 ) 

954 

955 

956@tf_export("__internal__.nest.map_structure_up_to", v1=[]) 

957def map_structure_up_to(shallow_tree, func, *inputs, **kwargs): 

958 """Applies a function or op to a number of partially flattened inputs. 

959 

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

961 

962 Use Case: 

963 

964 Sometimes we wish to apply a function to a partially flattened 

965 structure (for example when the function itself takes structure inputs). We 

966 achieve this by specifying a shallow structure, `shallow_tree` we wish to 

967 flatten up to. 

968 

969 The `inputs`, can be thought of as having the same structure layout as 

970 `shallow_tree`, but with leaf nodes that are themselves tree structures. 

971 

972 This function therefore will return something with the same base structure as 

973 `shallow_tree`. 

974 

975 Examples: 

976 

977 ```python 

978 shallow_tree = [None, None] 

979 inp_val = [1, 2, 3] 

980 out = map_structure_up_to(shallow_tree, lambda x: 2 * x, inp_val) 

981 

982 # Output is: [2, 4] 

983 ``` 

984 

985 ```python 

986 ab_tuple = collections.namedtuple("ab_tuple", "a, b") 

987 op_tuple = collections.namedtuple("op_tuple", "add, mul") 

988 inp_val = ab_tuple(a=2, b=3) 

989 inp_ops = ab_tuple(a=op_tuple(add=1, mul=2), b=op_tuple(add=2, mul=3)) 

990 out = map_structure_up_to(inp_val, lambda val, ops: (val + ops.add) * ops.mul, 

991 inp_val, inp_ops) 

992 

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

994 ``` 

995 

996 ```python 

997 data_list = [[2, 4, 6, 8], [[1, 3, 5, 7, 9], [3, 5, 7]]] 

998 name_list = ['evens', ['odds', 'primes']] 

999 out = map_structure_up_to( 

1000 name_list, 

1001 lambda name, sec: "first_{}_{}".format(len(sec), name), 

1002 name_list, data_list) 

1003 

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

1005 ``` 

1006 

1007 Args: 

1008 shallow_tree: a shallow structure, common to all the inputs. 

1009 func: callable which will be applied to each input individually. 

1010 *inputs: structures that are compatible with shallow_tree. The function 

1011 `func` is applied to corresponding structures due to partial flattening 

1012 of each input, so the function must support arity of `len(inputs)`. 

1013 **kwargs: kwargs to feed to func(). Special kwarg 

1014 `check_types` is not passed to func, but instead determines whether the 

1015 types of iterables within the structures have to be same (e.g. 

1016 `map_structure(func, [1], (1,))` raises a `TypeError` exception). To allow 

1017 this set this argument to `False`. 

1018 

1019 Raises: 

1020 TypeError: If `shallow_tree` is a nested structure but `input_tree` is not. 

1021 TypeError: If the structure types of `shallow_tree` are different from 

1022 `input_tree`. 

1023 ValueError: If the structure lengths of `shallow_tree` are different from 

1024 `input_tree`. 

1025 

1026 Returns: 

1027 result of repeatedly applying `func`, with the same structure layout as 

1028 `shallow_tree`. 

1029 """ 

1030 return nest_util.map_structure_up_to( 

1031 nest_util.Modality.CORE, 

1032 shallow_tree, 

1033 lambda _, *values: func(*values), # Discards the path arg. 

1034 *inputs, 

1035 **kwargs, 

1036 ) 

1037 

1038 

1039def map_structure_with_tuple_paths_up_to(shallow_tree, func, *inputs, **kwargs): 

1040 """Applies a function or op to a number of partially flattened inputs. 

1041 

1042 Like map_structure_up_to(), except that the 'func' argument takes a path 

1043 tuple as its first argument, followed by the corresponding values from 

1044 *inputs. 

1045 

1046 Example: 

1047 

1048 ```python 

1049 lowercase = {'a': 'a', 'b': ('b0', 'b1')} 

1050 uppercase = {'a': 'A', 'b': ('B0', 'B1')} 

1051 

1052 def print_path_and_values(path, *values): 

1053 print("path: {}, values: {}".format(path, values)) 

1054 

1055 shallow_tree = {'a': None} 

1056 map_structure_with_tuple_paths_up_to(shallow_tree, 

1057 print_path_and_values, 

1058 lowercase, 

1059 uppercase) 

1060 path: ('a',), values: ('a', 'A') 

1061 path: ('b', 0), values: ('b0', 'B0') 

1062 path: ('b', 1), values: ('b1', 'B1') 

1063 

1064 shallow_tree = {'b': None} 

1065 map_structure_with_tuple_paths_up_to(shallow_tree, 

1066 print_path_and_values, 

1067 lowercase, 

1068 uppercase, 

1069 check_types=False) 

1070 path: ('b', 1), values: (('bo', 'b1'), ('B0', 'B1')) 

1071 

1072 shallow_tree = {'a': None, 'b': {1: None}} 

1073 map_structure_with_tuple_paths_up_to(shallow_tree, 

1074 print_path_and_values, 

1075 lowercase, 

1076 uppercase, 

1077 check_types=False) 

1078 path: ('a',), values: ('a', 'A') 

1079 path: ('b', 1), values: ('b1', B1') 

1080 ``` 

1081 

1082 Args: 

1083 shallow_tree: a shallow structure, common to all the inputs. 

1084 func: callable that takes args (path, inputs_0_value, ... , inputs_N_value), 

1085 where path is a tuple path to an atom in shallow_tree, and inputs_i_value 

1086 is the corresponding value from inputs[i]. 

1087 *inputs: structures that are all structurally compatible with shallow_tree. 

1088 **kwargs: kwargs to feed to func(). Special kwarg `check_types` is not 

1089 passed to func, but instead determines whether the types of iterables 

1090 within the structures have to be same (e.g. `map_structure(func, [1], 

1091 (1,))` raises a `TypeError` exception). To allow this set this argument to 

1092 `False`. 

1093 

1094 Raises: 

1095 TypeError: If `shallow_tree` is a nested structure but one of `*inputs` is 

1096 not. 

1097 TypeError: If the structure types of `shallow_tree` are different from 

1098 `input_tree`. 

1099 ValueError: If the structure lengths of `shallow_tree` are different from 

1100 `input_tree`. 

1101 

1102 Returns: 

1103 Result of repeatedly applying `func`. Has the same structure layout as 

1104 `shallow_tree`. 

1105 """ 

1106 return nest_util.map_structure_up_to( 

1107 nest_util.Modality.CORE, shallow_tree, func, *inputs, **kwargs 

1108 ) 

1109 

1110 

1111@tf_export("__internal__.nest.get_traverse_shallow_structure", v1=[]) 

1112def get_traverse_shallow_structure(traverse_fn, structure, 

1113 expand_composites=False): 

1114 """Generates a shallow structure from a `traverse_fn` and `structure`. 

1115 

1116 `traverse_fn` must accept any possible subtree of `structure` and return 

1117 a depth=1 structure containing `True` or `False` values, describing which 

1118 of the top-level subtrees may be traversed. It may also 

1119 return scalar `True` or `False` "traversal is OK / not OK for all subtrees." 

1120 

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

1122 

1123 Args: 

1124 traverse_fn: Function taking a substructure and returning either a scalar 

1125 `bool` (whether to traverse that substructure or not) or a depth=1 

1126 shallow structure of the same type, describing which parts of the 

1127 substructure to traverse. 

1128 structure: The structure to traverse. 

1129 expand_composites: If true, then composite tensors such as 

1130 `tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their 

1131 component tensors. 

1132 

1133 Returns: 

1134 A shallow structure containing python bools, which can be passed to 

1135 `map_structure_up_to` and `flatten_up_to`. 

1136 

1137 Raises: 

1138 TypeError: if `traverse_fn` returns a nested structure for an atom input. 

1139 or a structure with depth higher than 1 for a nested structure input, 

1140 or if any leaf values in the returned structure or scalar are not type 

1141 `bool`. 

1142 """ 

1143 is_nested_fn = _is_nested_or_composite if expand_composites else is_nested 

1144 to_traverse = traverse_fn(structure) 

1145 if not is_nested_fn(structure): 

1146 if not isinstance(to_traverse, bool): 

1147 raise TypeError("traverse_fn returned structure: %s for non-structure: %s" 

1148 % (to_traverse, structure)) 

1149 return to_traverse 

1150 level_traverse = [] 

1151 if isinstance(to_traverse, bool): 

1152 if not to_traverse: 

1153 # Do not traverse this substructure at all. Exit early. 

1154 return False 

1155 else: 

1156 # Traverse the entire substructure. 

1157 for branch in nest_util.yield_value(nest_util.Modality.CORE, structure): 

1158 level_traverse.append( 

1159 get_traverse_shallow_structure(traverse_fn, branch, 

1160 expand_composites=expand_composites)) 

1161 elif not is_nested_fn(to_traverse): 

1162 raise TypeError("traverse_fn returned a non-bool scalar: %s for input: %s" 

1163 % (to_traverse, structure)) 

1164 else: 

1165 # Traverse some subset of this substructure. 

1166 assert_shallow_structure(to_traverse, structure, 

1167 expand_composites=expand_composites) 

1168 for t, branch in zip( 

1169 nest_util.yield_value(nest_util.Modality.CORE, to_traverse), 

1170 nest_util.yield_value(nest_util.Modality.CORE, structure), 

1171 ): 

1172 if not isinstance(t, bool): 

1173 raise TypeError( 

1174 "traverse_fn didn't return a depth=1 structure of bools. saw: %s " 

1175 " for structure: %s" % (to_traverse, structure)) 

1176 if t: 

1177 level_traverse.append( 

1178 get_traverse_shallow_structure(traverse_fn, branch)) 

1179 else: 

1180 level_traverse.append(False) 

1181 return nest_util.sequence_like(structure, level_traverse) 

1182 

1183 

1184@tf_export("__internal__.nest.yield_flat_paths", v1=[]) 

1185def yield_flat_paths(nest, expand_composites=False): 

1186 """Yields paths for some nested structure. 

1187 

1188 Refer to [tf.nest](https://www.tensorflow.org/api_docs/python/tf/nest) 

1189 for the definition of a structure. 

1190 

1191 Paths are lists of objects which can be str-converted, which may include 

1192 integers or other types which are used as indices in a dict. 

1193 

1194 The flat list will be in the corresponding order as if you called 

1195 `nest.flatten` on the structure. This is handy for naming Tensors such 

1196 the TF scope structure matches the tuple structure. 

1197 

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

1199 

1200 ```shell 

1201 nest.flatten(value) 

1202 [3, 23, 42] 

1203 list(nest.yield_flat_paths(value)) 

1204 [('a',), ('b', 'c'), ('b', 'd')] 

1205 ``` 

1206 

1207 ```shell 

1208 list(nest.yield_flat_paths({'a': [3]})) 

1209 [('a', 0)] 

1210 list(nest.yield_flat_paths({'a': 3})) 

1211 [('a',)] 

1212 ``` 

1213 

1214 Args: 

1215 nest: the value to produce a flattened paths list for. 

1216 expand_composites: If true, then composite tensors such as 

1217 `tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their 

1218 component tensors. 

1219 

1220 Yields: 

1221 Tuples containing index or key values which form the path to a specific 

1222 leaf value in the nested structure. 

1223 """ 

1224 is_nested_fn = _is_nested_or_composite if expand_composites else is_nested 

1225 for k, _ in nest_util.yield_flat_up_to( 

1226 nest_util.Modality.CORE, nest, nest, is_nested_fn 

1227 ): 

1228 yield k 

1229 

1230 

1231def flatten_with_joined_string_paths(structure, separator="/", 

1232 expand_composites=False): 

1233 """Returns a list of (string path, atom) tuples. 

1234 

1235 The order of tuples produced matches that of `nest.flatten`. This allows you 

1236 to flatten a nested structure while keeping information about where in the 

1237 structure each atom was located. See `nest.yield_flat_paths` 

1238 for more information. 

1239 

1240 Args: 

1241 structure: the nested structure to flatten. 

1242 separator: string to separate levels of hierarchy in the results, defaults 

1243 to '/'. 

1244 expand_composites: If true, then composite tensors such as 

1245 `tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their 

1246 component tensors. 

1247 

1248 Returns: 

1249 A list of (string, atom) tuples. 

1250 """ 

1251 flat_paths = yield_flat_paths(structure, expand_composites=expand_composites) 

1252 def stringify_and_join(path_elements): 

1253 return separator.join(str(path_element) for path_element in path_elements) 

1254 

1255 flat_string_paths = (stringify_and_join(path) for path in flat_paths) 

1256 return list(zip(flat_string_paths, 

1257 flatten(structure, expand_composites=expand_composites))) 

1258 

1259 

1260def flatten_with_tuple_paths(structure, expand_composites=False): 

1261 """Returns a list of `(tuple_path, atom)` tuples. 

1262 

1263 The order of pairs produced matches that of `nest.flatten`. This allows you 

1264 to flatten a nested structure while keeping information about where in the 

1265 structure each atom was located. See `nest.yield_flat_paths` 

1266 for more information about tuple paths. 

1267 

1268 Args: 

1269 structure: the nested structure to flatten. 

1270 expand_composites: If true, then composite tensors such as 

1271 `tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their 

1272 component tensors. 

1273 

1274 Returns: 

1275 A list of `(tuple_path, atom)` tuples. Each `tuple_path` is a tuple 

1276 of indices and/or dictionary keys that uniquely specify the path to 

1277 `atom` within `structure`. 

1278 """ 

1279 return list(zip(yield_flat_paths(structure, 

1280 expand_composites=expand_composites), 

1281 flatten(structure, expand_composites=expand_composites))) 

1282 

1283 

1284@tf_export("__internal__.nest.list_to_tuple", v1=[]) 

1285def list_to_tuple(structure): 

1286 """Replace all lists with tuples. 

1287 

1288 The fork of nest that tf.data uses treats lists as atoms, while 

1289 tf.nest treats them as structures to recurse into. Keras has chosen to adopt 

1290 the latter convention, and must therefore deeply replace all lists with tuples 

1291 before passing structures to Dataset.from_generator. 

1292 

1293 Args: 

1294 structure: A nested structure to be remapped. 

1295 

1296 Returns: 

1297 structure mapped to replace all lists with tuples. 

1298 """ 

1299 def sequence_fn(instance, args): 

1300 if isinstance(instance, list): 

1301 return tuple(args) 

1302 return nest_util.sequence_like(instance, args) 

1303 

1304 return nest_util.pack_sequence_as( 

1305 nest_util.Modality.CORE, 

1306 structure, 

1307 flatten(structure), 

1308 False, 

1309 sequence_fn=sequence_fn, 

1310 ) 

1311 

1312 

1313_pywrap_utils.RegisterType("Mapping", _collections_abc.Mapping) 

1314_pywrap_utils.RegisterType("MutableMapping", _collections_abc.MutableMapping) 

1315_pywrap_utils.RegisterType("Sequence", _collections_abc.Sequence) 

1316_pywrap_utils.RegisterType("MappingView", _collections_abc.MappingView) 

1317_pywrap_utils.RegisterType("ObjectProxy", _wrapt.ObjectProxy)