Skip to content
test_tree.py 36.2 KiB
Newer Older
from __future__ import division, absolute_import, print_function
Andreas Klöckner's avatar
Andreas Klöckner committed

__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.
"""

import six
from six.moves import range
Andreas Klöckner's avatar
Andreas Klöckner committed
import numpy as np
import sys
Andreas Klöckner's avatar
Andreas Klöckner committed

import pyopencl as cl
Andreas Klöckner's avatar
Andreas Klöckner committed
from pyopencl.tools import (  # noqa
        pytest_generate_tests_for_pyopencl as pytest_generate_tests)
from boxtree.tools import make_normal_particle_array
logger = logging.getLogger(__name__)
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(ctx_getter, dtype, dims, nparticles):
    logging.basicConfig(level=logging.INFO)

    ctx = ctx_getter()
    queue = cl.CommandQueue(ctx)

    from boxtree.tools import AXIS_NAMES
    from boxtree.bounding_box import BoundingBoxFinder

    bbf = BoundingBoxFinder(ctx)

    axis_names = AXIS_NAMES[:dims]
    logger.info("%s - %s %s" % (dtype, dims, nparticles))
    particles = make_normal_particle_array(queue, nparticles, dims, dtype)
    bbox_min = [np.min(x.get()) for x in particles]
    bbox_max = [np.max(x.get()) for x in particles]
    bbox_cl, evt = bbf(particles, radii=None)
    bbox_cl = bbox_cl.get()
    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["min_"+ax]
        bbox_max_cl[i] = bbox_cl["max_"+ax]
    assert (bbox_min == bbox_min_cl).all()
    assert (bbox_max == bbox_max_cl).all()
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

Andreas Klöckner's avatar
Andreas Klöckner committed
def run_build_test(builder, queue, dims, dtype, nparticles, do_plot,
        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)

    if (dtype == np.float32
            and dims == 2
            and queue.device.platform.name == "Portable Computing Language"):
Andreas Klöckner's avatar
Andreas Klöckner committed
        # arg list lenghts disagree
        pytest.xfail("2D float doesn't work on POCL")

    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,
Andreas Klöckner's avatar
Andreas Klöckner committed
            " - ".join("%s: %s" % (k, v) for k, v in six.iteritems(kwargs))))
    else:
        logger.info("%dD %s - %d particles - max leaf weight %d  - %s" % (
            dims, dtype.type.__name__, nparticles, max_leaf_refine_weight,
            " - ".join("%s: %s" % (k, v) for k, v in six.iteritems(kwargs))))
    particles = make_normal_particle_array(queue, nparticles, dims, dtype)
Andreas Klöckner's avatar
Andreas Klöckner committed

    if do_plot:
        import matplotlib.pyplot as pt
        pt.plot(particles[0].get(), particles[1].get(), "x")
Andreas Klöckner's avatar
Andreas Klöckner committed

    queue.finish()
    tree, _ = builder(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)
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([pi.get() for pi in particles])
    assert (sorted_particles
            == unsorted_particles[:, tree.user_source_ids]).all()
Andreas Klöckner's avatar
Andreas Klöckner committed

    if refine_weights is not None:
        refine_weights_reordered = refine_weights.get()[tree.user_source_ids]

    all_good_so_far = True
Andreas Klöckner's avatar
Andreas Klöckner committed

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

        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)
                (extent_low[:, np.newaxis] - scaled_tol <= box_particles)
Andreas Klöckner's avatar
Andreas Klöckner committed

        all_good_here = good.all()
        if do_plot 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_CHILDREN):
            # Check that leaf particle density is as promised.
            nparticles_in_box = tree.box_source_counts_cumul[ibox]
            if max_particles_in_box is not None:
                if nparticles_in_box > max_particles_in_box:
                    print("too many particles ({0} > {1}); box {2}".format(
                        nparticles_in_box, max_particles_in_box, ibox))
                    all_good_here = False
            else:
                assert refine_weights is not None
                box_weight = np.sum(
                    refine_weights_reordered[start:start+nparticles_in_box])
Loading
Loading full blame...