Skip to content

Commit

Permalink
Refactor MultiBlock and slice_along_axis (#1506)
Browse files Browse the repository at this point in the history
* Simplify test helper, refactor multiblock volume and test

* Refactor DataSetFilters.slice_along_axis

* Refactor MultiBlock.bounds to use reduce

* Remove stray hyphen
  • Loading branch information
adeak committed Jul 10, 2021
1 parent 2b9af0b commit 398ac09
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 41 deletions.
32 changes: 7 additions & 25 deletions pyvista/core/composite.py
Expand Up @@ -135,25 +135,12 @@ def bounds(self) -> List[float]:
[-0.5, 2.5, -0.5, 2.5, -0.5, 0.5]
"""
bounds = [np.inf, -np.inf, np.inf, -np.inf, np.inf, -np.inf]

def update_bounds(ax, nb, bounds):
"""Update bounds while keeping track (internal helper)."""
if nb[2*ax] < bounds[2*ax]:
bounds[2*ax] = nb[2*ax]
if nb[2*ax+1] > bounds[2*ax+1]:
bounds[2*ax+1] = nb[2*ax+1]
return bounds

# get bounds for each block and update
for i in range(self.n_blocks):
if self[i] is None:
continue
bnds = self[i].bounds # type: ignore
for a in range(3):
bounds = update_bounds(a, bnds, bounds)

return bounds
# apply reduction of min and max over each block
all_bounds = [block.bounds for block in self if block]
minima = np.minimum.reduce(all_bounds)[::2]
maxima = np.maximum.reduce(all_bounds)[1::2]
# interleave minima and maxima for bounds
return np.stack([minima, maxima]).ravel('F').tolist()

@property
def center(self) -> Any:
Expand Down Expand Up @@ -224,12 +211,7 @@ def volume(self) -> float:
1.7348
"""
volume = 0.0
for block in self:
if block is None:
continue
volume += block.volume
return volume
return sum(block.volume for block in self if block)

def get_data_range(self, name: str) -> Tuple[float, float]: # type: ignore
"""Get the min/max of an array given its name across all blocks."""
Expand Down
47 changes: 33 additions & 14 deletions pyvista/core/filters/data_set.py
Expand Up @@ -511,17 +511,30 @@ def slice_along_axis(dataset, n=5, axis='x', tolerance=None,
axis index (``0``, ``1``, or ``2``).
tolerance : float, optional
The tolerance to the edge of the dataset bounds to create the
slices.
The tolerance to the edge of the dataset bounds to create
the slices. The ``n`` slices are placed equidistantly with
an absolute padding of ``tolerance`` inside each side of the
``bounds`` along the specified axis. Defaults to 1% of the
``bounds`` along the specified axis.
generate_triangles: bool, optional
If this is enabled (``False`` by default), the output will be
triangles. Otherwise the output will be the intersection
If this is enabled (``False`` by default), the output will
be triangles. Otherwise the output will be the intersection
polygons.
contour : bool, optional
If ``True``, apply a ``contour`` filter after slicing.
bounds : sequence, optional
A 6-length sequence overriding the bounds of the mesh.
The bounds along the specified axis define the extent
where slices are taken.
center : sequence, optional
A 3-length sequence specifying the position of the line
along which slices are taken. Defaults to the center of
the mesh.
Examples
--------
Slice the random hills dataset in the X direction.
Expand All @@ -541,35 +554,41 @@ def slice_along_axis(dataset, n=5, axis='x', tolerance=None,
See :ref:`slice_example` for more examples using this filter.
"""
axes = {'x': 0, 'y': 1, 'z': 2}
# parse axis input
labels = ['x', 'y', 'z']
label_to_index = {label: index for index, label in enumerate(labels)}
if isinstance(axis, int):
ax = axis
axis = list(axes.keys())[list(axes.values()).index(ax)]
ax_index = axis
ax_label = labels[ax_index]
elif isinstance(axis, str):
try:
ax = axes[axis]
ax_index = label_to_index[axis.lower()]
except KeyError:
raise ValueError(f'Axis ({axis}) not understood')
raise ValueError(f'Axis ({axis!r}) not understood. '
f'Choose one of {labels}.') from None
ax_label = axis
# get the locations along that axis
if bounds is None:
bounds = dataset.bounds
if center is None:
center = dataset.center
if tolerance is None:
tolerance = (bounds[ax*2+1] - bounds[ax*2]) * 0.01
rng = np.linspace(bounds[ax*2]+tolerance, bounds[ax*2+1]-tolerance, n)
tolerance = (bounds[ax_index*2 + 1] - bounds[ax_index*2]) * 0.01
rng = np.linspace(bounds[ax_index*2] + tolerance,
bounds[ax_index*2 + 1] - tolerance,
n)
center = list(center)
# Make each of the slices
output = pyvista.MultiBlock()
if isinstance(dataset, pyvista.MultiBlock):
for i in range(dataset.n_blocks):
output[i] = dataset[i].slice_along_axis(n=n, axis=axis,
output[i] = dataset[i].slice_along_axis(n=n, axis=ax_label,
tolerance=tolerance, generate_triangles=generate_triangles,
contour=contour, bounds=bounds, center=center)
return output
for i in range(n):
center[ax] = rng[i]
slc = DataSetFilters.slice(dataset, normal=axis, origin=center,
center[ax_index] = rng[i]
slc = DataSetFilters.slice(dataset, normal=ax_label, origin=center,
generate_triangles=generate_triangles,
contour=contour)
output[i, f'slice{i}'] = slc
Expand Down
5 changes: 3 additions & 2 deletions tests/test_composite.py
Expand Up @@ -23,7 +23,7 @@ def pyvista_multi():

def multi_from_datasets(*datasets):
"""Return pyvista multiblock composed of any number of datasets."""
return MultiBlock([*datasets])
return MultiBlock(datasets)


def test_multi_block_init_vtk():
Expand Down Expand Up @@ -358,7 +358,8 @@ def test_multi_block_list_index(ant, sphere, uniform, airplane, globe):

def test_multi_block_volume(ant, airplane, sphere, uniform):
multi = multi_from_datasets(ant, sphere, uniform, airplane, None)
assert multi.volume
vols = ant.volume + sphere.volume + uniform.volume + airplane.volume
assert multi.volume == pytest.approx(vols)


def test_multi_block_length(ant, sphere, uniform, airplane):
Expand Down

0 comments on commit 398ac09

Please sign in to comment.