# Examples from pyvista.CompositeFilters.generic_filter
# =====================================================

# Create a `MultiBlock` with various mesh types.
import pyvista as pv
from pyvista import examples
import numpy as np
volume = examples.load_uniform()
poly = examples.load_ant()
unstructured = examples.load_tetbeam()
multi = pv.MultiBlock([volume, poly, unstructured])

[type(block) for block in multi]

# Use the generic filter to apply `cast_to_unstructured_grid()`
# to all blocks.
filtered = multi.generic_filter('cast_to_unstructured_grid')

[type(block) for block in filtered]

# Use the `partition()` filter on all blocks.
# Any arguments can be specified as though the filter is being used directly.
filtered = multi.generic_filter('partition', 4, as_composite=True)

# Any function can be used as long as it returns a `DataSet` or
# `MultiBlock`. For example, we can normalize each block
# independently to have bounds between `-0.5` and `0.5`.
def normalize_bounds(dataset):
    # Center the dataset
    dataset = dataset.translate(-np.array(dataset.center))
    # Scale the dataset
    factor = 1 / np.array(dataset.bounds_size)
    return dataset.scale(factor)

filtered = multi.generic_filter(normalize_bounds)
filtered

# The generic filter will fail if the filter can only be applied to some blocks
# but not others. For example, it is not possible to use the
# `resample()` filter generically since the
# `MultiBlock` above is heterogeneous and contains some blocks which are not
# `ImageData`.
multi.generic_filter('resample', 0.5)

# Use a custom function instead to apply the generic filter conditionally. Here we
# filter the image blocks but simply pass-through a copy of any other blocks.
def conditional_resample(dataset, *args, **kwargs):
    if isinstance(dataset, pv.ImageData):
        return dataset.resample(*args, **kwargs)
    return dataset.copy()

filtered = multi.generic_filter(conditional_resample, 0.5)

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