# Examples from pyvista.MultiBlock.recursive_iterator
# ===================================================

# Load a `MultiBlock` with nested datasets.
import pyvista as pv
from pyvista import examples
multi = examples.download_exodus()

# The dataset has eight `MultiBlock` blocks.
multi.n_blocks

all(isinstance(block, pv.MultiBlock) for block in multi)

# Get the iterator and show the count of all recursively nested blocks.
iterator = multi.recursive_iterator()
iterator

len(list(iterator))

# Check if all blocks are `DataSet` objects. Note that `None`
# blocks are included by default, so this may not be `True` in all cases.
all(isinstance(item, pv.DataSet) for item in multi.recursive_iterator())

# Use the iterator to apply a filter inplace to all recursively nested datasets.
_ = [
    dataset.connectivity(inplace=True)
    for dataset in multi.recursive_iterator()
]

# Iterate through nested block names.
iterator = multi.recursive_iterator('names')
next(iterator)

# Prepend parent block names.
iterator = multi.recursive_iterator('names', prepend_names=True)
next(iterator)

# Iterate through name-block pairs. Prepend parent block names again using a
# custom separator.
iterator = multi.recursive_iterator(
    'items', prepend_names=True, separator='->'
)
next(iterator)

# Iterate through ids. The ids are returned as a tuple by default.
iterator = multi.recursive_iterator('ids')
next(iterator)

# Use `get_block()` and get the next block indicated by the nested ids.
multi.get_block(next(iterator))

# Use the iterator to `replace` all blocks with new blocks. Similar to a previous
# example, we use a filter but this time the operation is not performed in place.
iterator = multi.recursive_iterator('all', nested_ids=True)
for ids, _, block in iterator:
    multi.replace(ids, block.connectivity())

# Use `node_type='parent'` to get information about `MultiBlock` nodes.
iterator = multi.recursive_iterator(node_type='parent')

# The iterator has `8` items. In this case this matches the number of blocks
# in the root block.
len(list(iterator))

# Use `skip_empty` to skip `MultiBlock` nodes which have length `0`
# and return their block ids.
iterator = multi.recursive_iterator(
    'ids', node_type='parent', skip_empty=True
)
ids = list(iterator)

# There are two non-empty blocks at index `0` and `4`.
len(ids)
ids

# ----------------------------------------------------------------------
# Generated by sphinx-examples-as-code https://github.com/pyvista/sphinx-examples-as-code

