# Examples from pyvista.DataSetFilters.connectivity
# =================================================

# Create a single mesh with three disconnected regions where each
# region has a different cell count.
import numpy as np
import pyvista as pv
large = pv.Sphere(
    center=(-4, 0, 0), phi_resolution=40, theta_resolution=40
)
medium = pv.Sphere(
    center=(-2, 0, 0), phi_resolution=15, theta_resolution=15
)
small = pv.Sphere(center=(0, 0, 0), phi_resolution=7, theta_resolution=7)
mesh = large + medium + small

# Compute connectivity. There are three regions, one for each sphere.
conn = mesh.connectivity('all')
np.unique(conn['RegionId'])

# Plot the connectivity labels using `color_labels()`.
def labels_plotter(dataset: pv.DataSet) -> pv.Plotter:
    rgb = ['red', 'green', 'blue']
    colored, color_dict = dataset.color_labels(rgb, return_dict=True)
    pl = pv.Plotter()
    pl.add_mesh(colored, show_edges=True)
    pl.add_legend(color_dict)
    pl.camera_position = pv.CameraPosition(
        position=(3.8, 5.8, 5.8),
        focal_point=(-2.0, 0.0, 0.0),
        viewup=(0.0, 0.0, 1.0),
    )
    return pl

pl = labels_plotter(conn)
pl.show()

# Restrict connectivity to a scalar range.
mesh['y_coordinates'] = mesh.points[:, 1]
conn = mesh.connectivity('all', scalar_range=[-1, 0])
pl = labels_plotter(conn)
pl.show()

# Extract the region closest to the origin.
conn = mesh.connectivity('closest', (0, 0, 0))
pl = labels_plotter(conn)
pl.show()

# Extract a region using a cell ID `3100` as a seed.
conn = mesh.connectivity('cell_seed', 3100)
pl = labels_plotter(conn)
pl.show()

# Extract the largest region.
conn = mesh.connectivity('largest')
pl = labels_plotter(conn)
pl.show()

# Extract the largest and smallest regions by specifying their
# region IDs. Note that the region IDs of the output differ from
# the specified IDs since the input has three regions but the output
# only has two.
large_id = 0  # largest always has ID '0'
small_id = 2  # smallest has ID 'N-1' with N=3 regions
conn = mesh.connectivity('specified', (small_id, large_id))
pl = labels_plotter(conn)
pl.show()

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

