Skip to content
test_tree.py 37.1 KiB
Newer Older
__copyright__ = "Copyright (C) 2012 Andreas Kloeckner"

__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

Andreas Klöckner's avatar
Andreas Klöckner committed
import sys
Andreas Klöckner's avatar
Andreas Klöckner committed

import numpy as np

from arraycontext import pytest_generate_tests_for_array_contexts
from boxtree.array_context import (                                 # noqa: F401
        PytestPyOpenCLArrayContextFactory, _acf)
from boxtree.tools import make_normal_particle_array
import logging
logger = logging.getLogger(__name__)
pytest_generate_tests = pytest_generate_tests_for_array_contexts([
    PytestPyOpenCLArrayContextFactory,
    ])

Andreas Klöckner's avatar
Andreas Klöckner committed

# {{{ bounding box test

@pytest.mark.parametrize("dtype", [np.float32, np.float64])
Andreas Klöckner's avatar
Andreas Klöckner committed
@pytest.mark.parametrize("dims", [2, 3])
@pytest.mark.parametrize("nparticles", [9, 4096, 10**5])
def test_bounding_box(actx_factory, dtype, dims, nparticles):
    actx = actx_factory()
    from boxtree.tools import AXIS_NAMES
    from boxtree.bounding_box import BoundingBoxFinder
    bbf = BoundingBoxFinder(actx.context)
    axis_names = AXIS_NAMES[:dims]
    logger.info("%s - %s %s", dtype, dims, nparticles)
    particles = make_normal_particle_array(actx.queue, nparticles, dims, dtype)
    bbox_min = [np.min(actx.to_numpy(x)) for x in particles]
    bbox_max = [np.max(actx.to_numpy(x)) for x in particles]
    bbox_cl, evt = bbf(particles, radii=None)
    bbox_cl = actx.to_numpy(bbox_cl)
    bbox_min_cl = np.empty(dims, dtype)
    bbox_max_cl = np.empty(dims, dtype)
    for i, ax in enumerate(axis_names):
        bbox_min_cl[i] = bbox_cl[f"min_{ax}"]
        bbox_max_cl[i] = bbox_cl[f"max_{ax}"]
    assert np.all(bbox_min == bbox_min_cl)
    assert np.all(bbox_max == bbox_max_cl)
Andreas Klöckner's avatar
Andreas Klöckner committed

# {{{ test basic (no source/target distinction) tree build
Andreas Klöckner's avatar
Andreas Klöckner committed

def run_build_test(builder, actx, dims, dtype, nparticles, visualize,
        max_particles_in_box=None, max_leaf_refine_weight=None,
        refine_weights=None, **kwargs):
    dtype = np.dtype(dtype)
Andreas Klöckner's avatar
Andreas Klöckner committed

    if dtype == np.float32:
        tol = 1e-4
    elif dtype == np.float64:
        tol = 1e-12
    else:
        raise RuntimeError("unsupported dtype: %s" % dtype)

    logger.info(75 * "-")

    if max_particles_in_box is not None:
        logger.info("%dD %s - %d particles - max %d per box - %s",
            dims, dtype.type.__name__, nparticles, max_particles_in_box,
            " - ".join(f"{k}: {v}" for k, v in kwargs.items()))
        logger.info("%dD %s - %d particles - max leaf weight %d  - %s",
            dims, dtype.type.__name__, nparticles, max_leaf_refine_weight,
            " - ".join(f"{k}: {v}" for k, v in kwargs.items()))

    logger.info(75 * "-")
    particles = make_normal_particle_array(actx.queue, nparticles, dims, dtype)
Andreas Klöckner's avatar
Andreas Klöckner committed

    if visualize:
        import matplotlib.pyplot as pt
        np_particles = actx.to_numpy(particles)
        pt.plot(np_particles[0], np_particles[1], "x")
Andreas Klöckner's avatar
Andreas Klöckner committed

    actx.queue.finish()
    tree, _ = builder(actx.queue, particles,
                      max_particles_in_box=max_particles_in_box,
                      refine_weights=refine_weights,
                      max_leaf_refine_weight=max_leaf_refine_weight,
                      debug=True, **kwargs)
    tree = tree.get(queue=actx.queue)
Andreas Klöckner's avatar
Andreas Klöckner committed

    sorted_particles = np.array(list(tree.sources))
Andreas Klöckner's avatar
Andreas Klöckner committed

    unsorted_particles = np.array([actx.to_numpy(pi) for pi in particles])
    assert np.all(sorted_particles
            == unsorted_particles[:, tree.user_source_ids])
Andreas Klöckner's avatar
Andreas Klöckner committed

    if refine_weights is not None:
        refine_weights_reordered = (
                actx.to_numpy(refine_weights)[tree.user_source_ids])
    all_good_so_far = True
Andreas Klöckner's avatar
Andreas Klöckner committed

    if visualize:
        from boxtree.visualization import TreePlotter
        plotter = TreePlotter(tree)
        plotter.draw_tree(fill=False, edgecolor="black", zorder=10)
        plotter.set_bounding_box()
Andreas Klöckner's avatar
Andreas Klöckner committed

    from boxtree import box_flags_enum as bfe

    scaled_tol = tol*tree.root_extent
Andreas Klöckner's avatar
Andreas Klöckner committed
    for ibox in range(tree.nboxes):
        # Empty boxes exist in non-pruned trees--which themselves are undocumented.
        # These boxes will fail these tests.
        if not (tree.box_flags[ibox] & bfe.HAS_OWN_SRCNTGTS):
        extent_low, extent_high = tree.get_box_extent(ibox)
Andreas Klöckner's avatar
Andreas Klöckner committed

        assert np.all(extent_low >= tree.bounding_box[0] - scaled_tol), (
                ibox, extent_low, tree.bounding_box[0])
        assert np.all(extent_high <= tree.bounding_box[1] + scaled_tol), (
                ibox, extent_high, tree.bounding_box[1])
Andreas Klöckner's avatar
Andreas Klöckner committed

        center = tree.box_centers[:, ibox]

        for _, bbox_min, bbox_max in [
                (
                    "source",
                    tree.box_source_bounding_box_min[:, ibox],
                    tree.box_source_bounding_box_max[:, ibox]),
                (
                    "target",
                    tree.box_target_bounding_box_min[:, ibox],
                    tree.box_target_bounding_box_max[:, ibox]),
                ]:
            assert np.all(extent_low - scaled_tol <= bbox_min)
            assert np.all(bbox_min - scaled_tol <= center)
            assert np.all(bbox_max - scaled_tol <= extent_high)
            assert np.all(center - scaled_tol <= bbox_max)
        start = tree.box_source_starts[ibox]
        box_children = tree.box_child_ids[:, ibox]
        existing_children = box_children[box_children != 0]

        assert (tree.box_source_counts_nonchild[ibox]
                + np.sum(tree.box_source_counts_cumul[existing_children])
                == tree.box_source_counts_cumul[ibox])

        box_particles = sorted_particles[:,
                start:start+tree.box_source_counts_cumul[ibox]]
                (box_particles < extent_high[:, np.newaxis] + scaled_tol)
Andreas Klöckner's avatar
Andreas Klöckner committed
                & (extent_low[:, np.newaxis] - scaled_tol <= box_particles))
Andreas Klöckner's avatar
Andreas Klöckner committed

        all_good_here = np.all(good)
        if visualize and not all_good_here and all_good_so_far:
            pt.plot(
                    box_particles[0, np.where(~good)[1]],
                    box_particles[1, np.where(~good)[1]], "ro")
Andreas Klöckner's avatar
Andreas Klöckner committed

            plotter.draw_box(ibox, edgecolor="red")
Andreas Klöckner's avatar
Andreas Klöckner committed

        if not all_good_here:
Andreas Klöckner's avatar
Andreas Klöckner committed
            print("BAD BOX", ibox)
Andreas Klöckner's avatar
Andreas Klöckner committed

        if not (tree.box_flags[ibox] & bfe.HAS_CHILD_PARTICLES):
            # Check that leaf particle density is as promised.
            nparticles_in_box = tree.box_source_counts_cumul[ibox]
Loading
Loading full blame...