FNode.hpp 32.3 KB
Newer Older
1 2 3
#ifndef SCALFMM_NODE_HPP_
#define SCALFMM_NODE_HPP_

4
#include <algorithm>
5
#include <cmath>
6
#include <cassert>
7 8
#include <functional>
#include <memory>
9
#include <ostream>
10
#include <iomanip>
11 12 13 14 15
#include <stdexcept>
#include <string>
#include <vector>
#include <unordered_set>

16
#include "Utils/Contribs/inria/ostream_joiner.hpp"
17
#include "Utils/Contribs/inria/detection_idiom.hpp"
18

19 20 21
#include "FBox.hpp"
#include "Utils/FPoint.hpp"
#include "Utils/FConstFuncs.hpp"
22
#include "Utils/FOstreamTuple.hpp"
23

24
#include "Components/FSymbolicData.hpp"
25 26
#include "Components/FBasicCell.hpp"

27
namespace scalfmm {
28

29 30 31 32 33 34
namespace tests {
struct test_Node;
struct test_NodeIterator;
struct test_InOrderNodeIterator;
struct test_PreOrderNodeIterator;
struct test_PostOrderNodeIterator;
35
} // close namespace [scalfmm]::tests
36 37


38
namespace meta {
39 40
/**
 * \brief Sink in type for SFINAE purpose
41 42 43 44 45 46 47
 *
 * Derives from std::true_type.
 *
 * \tparam Ts Type parameter pack
 */
template<typename... Ts>
struct exist_t : std::true_type {};
48

49 50
/**
 * \brief Compile check that `T::push(Args...)` exists
51 52 53 54 55
 *
 * This does not check the return type
 */
template<typename T, typename... Args>
class has_push {
56 57
    /**
     * \brief Overload found if `T::push(Args...)` exists
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
     *
     * If `T::push(Args...)` exists, this overload is found when
     * computing #value at compile time.
     *
     * \tparam U used as T
     * \tparam unnamed Default parameter dependent on U, fails
     * compilation if `U::push(Args...)` does not exist.
     */
    template<typename U,
             typename std::enable_if<
                 exist_t<decltype(std::declval<U>().push(std::declval<Args>()...))>::value
                 >::type* = nullptr>
    static std::true_type get(U);

    /// SFINAE fallback
    static std::false_type get(...);
public:
    /// True if `T::push(Args...)` exists, false otherwise
    constexpr static const bool value = decltype(get(std::declval<T>()))::value;
};
78

79

80 81
/**
 * \brief Compile check that `T::push_back(Args...)` exists
82 83 84 85 86
 *
 * This does not check the return type
 */
template<typename T, typename... Args>
class has_push_back {
87 88
    /**
     * \brief Overload found if `T::push_back(Args...)` exists
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
     *
     * If `T::push_back(Args...)` exists, this overload is found when
     * computing #value at compile time.
     *
     * \tparam U used as T
     * \tparam unnamed Default parameter dependent on U, fails
     * compilation if `U::push_back(Args...)` does not exist.
     */
    template<typename U,
             typename std::enable_if<
                 exist_t<decltype(std::declval<U>().push_back(std::declval<Args>()...))>::value
                 >::type* = nullptr>
    static std::true_type get(U);

    /// SFINAE fallback
    static std::false_type get(...);
public:
    /// True if `T::push_back(Args...)` exists, false otherwise
    constexpr static const bool value = decltype(get(std::declval<T>()))::value;
};
109 110

} // close [scalfmm]::meta
111

112

113
namespace sfinae {
114

115 116
template<bool value, template<class...> class Checker, typename... Args>
using use_if = typename std::enable_if<value == Checker<Args...>::value >::type*;
117 118


119 120
/**
 * \brief Exists (as void*) if T derives from Base
121 122 123 124 125 126 127 128 129 130
 *
 * Type alias for use in SFINAE. Is a void* if Derived is derived from
 * Base, does not exist otherwise.
 *
 * \tparam Base Wanted base type
 * \tparam T Type to check against Base for derivation
 */
template<typename Base, typename T>
using derived_from = use_if<true, std::is_base_of, Base,T >;
}
131

132 133
struct fmt {
    enum : long {TERM, OBJ};
134

135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
    /// Get the stream flag index for the output format
    static const int& node_os_format_id() {
        static const int i = std::ios_base::xalloc();
        return i;
    }

    /// Get the stream flag index for the particle output in terminal format
    static const int& node_os_particle_id() {
        static const int i = std::ios_base::xalloc();
        return i;
    }

    static std::ostream& term(std::ostream& os) {
        os.iword(node_os_format_id()) = TERM;
        return os;
150 151
    };

152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
    static std::ostream& obj(std::ostream& os) {
        os.iword(node_os_format_id()) = OBJ;
        return os;
    };

    static std::ostream& parts(std::ostream& os) {
        os.iword(node_os_particle_id()) = true;
        return os;
    };

    static std::ostream& no_parts(std::ostream& os) {
        os.iword(node_os_particle_id()) = false;
        return os;
    };


};

170 171 172 173
}

struct NodeEmptyData {};

174 175


176 177
/**
 * \brief Tree node implementation
178 179 180 181 182 183 184
 */
template<class _Tree, class _ParticleContainer, class NodeData>
class FNode {
public:
    /// Tree type this class belongs to
    using tree_t = _Tree;
    /// Type used to represent real numbers
185
    using FReal = typename tree_t::FReal;
186 187 188
    /// Space dimension count
    constexpr static const std::size_t Dim = _Tree::Dim;
    /// Child count if the node is not a leaf
189
    constexpr static const std::size_t child_count = 1 << Dim;
190 191

    /// Node position type
192
    using position_t = FPoint<FReal, Dim>;
193 194 195 196 197 198 199 200
    /// Node bounding box type
    using box_t =  FBox<position_t>;
    /// Interaction lists type
    using interaction_list_t = std::unordered_set<FNode*>;
    /// Children array type
    using child_node_array_t = std::array<FNode*, child_count>;
    /// Particle container type
    using particle_container_t = _ParticleContainer;
201 202
    /**
     * \brief Particle type
203 204 205 206 207 208
     * The particle must satisfy the following conditions:
     *   - Default constructible
     *   - Constructible from particle_container_t::value_type
     *   - position_t position() const method must exist
     *
     */
209 210 211 212
    using particle_t = typename particle_container_t::value_type;
    /// Node data structure
    using data_t = NodeData;

213

214 215
    /**
     * \brief Node structural data
216 217
     * Keeps data about the node that may be read by kernels or algorithms.
     */
218 219 220 221
    using symbolic_data_t
    = typename extract_symbolic_data_t_or_fallback_to_default<FSymbolicData,data_t>::type;

    static_assert(models_symbolic_data<symbolic_data_t>::value,
222
                  "The symbolic_data_t type does not model the required symbolic data interface.");
223

224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
private:

    friend struct scalfmm::tests::test_Node;
    friend struct scalfmm::tests::test_NodeIterator;
    friend struct scalfmm::tests::test_InOrderNodeIterator;
    friend struct scalfmm::tests::test_PreOrderNodeIterator;
    friend struct scalfmm::tests::test_PostOrderNodeIterator;
    friend tree_t;

    /// Children array, filled with nullptr is Node is a leaf
    child_node_array_t _children{{}};
    /// Node parent, nullptr if the node is a root
    FNode* _parent = nullptr;
    /// Node spatial bounding box
    box_t _box;
    /// Particle container
240
    particle_container_t _p_container;
241 242 243 244 245 246 247 248 249
    /// Node data
    data_t _data = data_t();

    /// Tree the Node belongs to
    tree_t* _tree;

    /// Indicates whether node is a leaf
    bool _is_leaf = true;

250
    /// Node data that may be of use to algorithms and kernels
251
    symbolic_data_t _symbolic_data;
252

253 254 255 256 257 258 259 260 261 262
public:
    /// Near-field leaves interaction list
    interaction_list_t U;
    /// Mid-field node interaction list
    interaction_list_t V;
    /// Near-field node interaction list
    interaction_list_t W;
    /// Mid-field leaf interaction list
    interaction_list_t X;

263 264 265 266
    /**
     * \brief Constructor called from parent
     *
     * This constructor is meant to be called from a parent node.
267 268 269 270 271 272 273
     *
     * \param parent The parent node
     * \param child_index The index of this node in the parent children array
     */
    FNode(FNode& parent, const std::size_t& child_index) :
        _parent(&parent),
        _box   (parent.getBox().center(), parent.getBox().corner(child_index) ),
274
        _tree  (parent._tree ),
275
        _symbolic_data{static_cast<int>(parent.getDepth()+1), (parent.getIndex() << Dim) + child_index}
276 277 278 279 280 281 282 283
    {
        if (child_index >= child_count) {
            throw std::invalid_argument(std::string("Wrong child index in node contructor: got ")
                                        + std::to_string(child_index)
                                        + std::string(", expected at most ")
                                        + std::to_string(Dim)
                                        + ".");
        }
284 285

        this->common_init();
286 287
    }

288 289 290 291 292
    /**
     * \brief Root constructor called from tree
     *
     * This constructor must be called when building the tree root.
     */
293 294
    FNode(tree_t* tree) :
        _box(tree->box()),
295 296
        _tree(tree),
        _symbolic_data{}
297 298
    {
        tree->leaves().insert(this);
299
        // `this` belongs to its own U list, not done in the other constructors
300 301
        // because managed by split or fuse
        this->U.insert(this);
302
        this->common_init();
303 304
    }

305 306 307
    /**
     * \brief Deleted default constructor
     */
308 309
    FNode() = delete;

310 311 312
    /**
     * \brief Deleted copy constructor
     */
313 314
    FNode(const FNode& other) = delete;

315 316 317
    /**
     * \brief Deleted copy operator
     */
318 319
    FNode& operator=(const FNode& other) = delete;

320 321 322
    /**
     * \brief Deleted move constructor
     */
323 324
    FNode(FNode&& other) = delete;

325 326 327
    /**
     * \brief Deleted move operator
     */
328 329
    FNode& operator=(FNode&& other) = delete;

330 331 332
    /**
     * \brief Deleted destructor
     */
333
    ~FNode() {
334
        this->delete_children();
335 336 337 338
    }


    /// Data accessor
339
    data_t* getData() noexcept {
340
        return &_data;
341 342
    }
    /// Data const accessor
343
    const data_t* getData() const noexcept {
344
        return &_data;
345 346
    }

347 348 349 350 351 352 353 354 355 356
    /// Symbolic data accessor
    symbolic_data_t& getSymbolicData() noexcept {
        return this->_symbolic_data;
    }
    /// Symbolic data const accessor
    const symbolic_data_t& getSymbolicData() const noexcept {
        return this->_symbolic_data;
    }


357 358 359 360 361 362 363 364 365
    /// Children container accessor
    child_node_array_t& getChildren() noexcept {
        return _children;
    }
    /// Children const container accessor
    const child_node_array_t& getChildren() const noexcept {
        return _children;
    }

366 367
    /**
     * \brief Child container accessor
368 369 370 371 372 373
     *
     * \param index Child index
     */
    FNode* getChild(const std::size_t& index) noexcept {
        return getChildren()[index];
    }
374 375
    /**
     * \brief Child container const accessor
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
     *
     * \param index Child index
     */
    const FNode* getChild(const std::size_t& index) const noexcept {
        return getChildren()[index];
    }

    /// Parent accessor
    FNode* getParent() noexcept {
        return _parent;
    }
    /// Parent const accessor
    const FNode* getParent() const noexcept {
        return _parent;
    }

    /// Depth accessor
393
    std::size_t getDepth() const noexcept {
394
        return _symbolic_data.depth;
395 396 397
    }

    /// Morton index accessor
398
    std::size_t getIndex() const noexcept {
399
        return _symbolic_data.m_idx;
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
    }

    /// Tree accessor
    tree_t& getTree() noexcept {
        return *_tree;
    }
    /// Tree const accessor
    const tree_t& getTree() const noexcept {
        return *_tree;
    }

    /// Box const accessor
    const box_t& getBox() const noexcept {
        return _box;
    }

    /// Particle container accessor
    particle_container_t* getParticleContainer() noexcept {
418
        return &_p_container;
419 420 421
    }
    /// Particle container accessor
    const particle_container_t* getParticleContainer() const noexcept {
422
        return &_p_container;
423 424
    }

425 426
    /// Particle container accessor
    particle_container_t* getTargets() noexcept {
427
        return &_p_container;
428 429 430
    }
    /// Particle container accessor
    const particle_container_t* getTargets() const noexcept {
431
        return &_p_container;
432 433
    }

434 435
    /// Particle count for the container
    std::size_t getParticleCount() const noexcept {
436
        return getParticleContainer()->size();
437 438
    }

439 440
    /**
     * \brief Find out whether this node and the 'other' node are adjacent
441 442 443 444 445 446 447 448 449 450 451
     *
     * The nodes are assumed to belong to the same tree.
     *
     * To check whether nodes are adjacent, on each axis, the distance between
     * the nodes' center is compared to the sum of their half diameter. For at
     * least one of the axes, the two must be equal. For the others, the
     * distance must be less than or equal to the sum. This ensures that a node
     * is not adjacent to one of its descendants.
     *
     * \param other The node to test adjacency with.
     *
452
     * \return true if this FNode and the 'other' FNode are adjacent.
453 454 455 456
     */
    bool is_adjacent(const FNode& other) const noexcept {
        // Sum of the half side lengh of the two nodes boxes.
        // Boxes are cubes, we only need one side.
457 458
        FReal centers_distance = getBox().center()[0] - getBox().c1()[0]
            + other.getBox().center()[0] - other.getBox().c1()[0];
459 460 461 462 463 464 465
        // Used to check that the other box isn't overlapping with this box
        bool one_axis_is_at_exact_distance = false;

        position_t my_center = getBox().center();
        position_t other_center = other.getBox().center();

        for(std::size_t i = 0; i < Dim; ++i) {
466
            FReal distance = fabs(my_center[i] - other_center[i]);
467 468 469 470 471 472 473 474 475 476
            if( Ffeq(distance, centers_distance) ) {
                one_axis_is_at_exact_distance = true;
            } else if(distance > centers_distance) {
                return false;
            }
        }

        return one_axis_is_at_exact_distance;
    }

477 478
    /**
     * \brief Tests whether this node and the 'other' node are adjacent
479 480 481 482 483 484 485 486 487 488 489 490 491
     *
     * \return true if the nodes are adjacent.
     */
    bool is_adjacent(const FNode* other) const noexcept {
        if(nullptr == other) {
            return false;
        } else if (this == other){
            return true;
        }

        return is_adjacent(*other);
    }

492 493
    /**
     * \brief Tests whether this node is a leaf
494 495 496 497 498 499 500
     *
     * \return true if this node is a leaf.
     */
    bool is_leaf() const noexcept {
        return _is_leaf;
    }

501
private:
502 503
    /**
     * \brief Push particle in container if it has compatible 'push'
504 505 506 507 508 509 510 511 512
     *
     * \tparam T Container type
     * \tparam scalfmm::sfinae::use_if SFINAE default argument. Compilation of
     * this overload fails if the condition isn't true
     *
     * \param container Container to push into
     * \param p Particle to push
     */
    template<typename T,
513
             scalfmm::sfinae::use_if<true, scalfmm::meta::has_push, T, particle_t> = nullptr>
514 515
    void particle_push(T& container, const particle_t& p) {
        container.push(p);
516 517
    }

518 519
    /**
     * \brief Push particle in container if it has compatible `push_back` and
520 521 522 523 524 525 526 527 528 529
     * no `push`
     *
     * \tparam T Container type
     * \tparam scalfmm::sfinae::use_if SFINAE default argument
     * \tparam scalfmm::sfinae::use_if SFINAE default argument
     *
     * \param container Container to push into
     * \param p Particle to push
     */
    template<typename T,
530 531
             scalfmm::sfinae::use_if<true, scalfmm::meta::has_push_back, T, particle_t> = nullptr,
             scalfmm::sfinae::use_if<false, scalfmm::meta::has_push, T, particle_t> = nullptr>
532 533
    void particle_push(T& container, const particle_t& p) {
        container.push_back(p);
534 535 536
    }

public:
537 538
    /**
     * \brief Inserts a particle in the tree rooted at node
539
     *
540 541 542 543
     * Pushes a particle in the node particle container if it is a leaf. If it
     * isn't, the particle is forwarded to the relevant child.
     *
     * \note The `push_back` method of #particle_container_t is used to insert in a leaf
544 545 546
     */
    void insert(const particle_t& p) {
        if(! is_leaf()) {
547 548
            std::size_t child_index = box_t::space_filling_curve_t::index(p.position(), getBox().center());
            getChild(child_index)->insert(p);
549
        } else {
550
            this->getParticleContainer()->reserve(this->getTree().leaf_max_particle_count());
551
            particle_push(*(this->getParticleContainer()), p);
552 553 554 555 556 557
            if(getParticleContainer()->size() > getTree().leaf_max_particle_count()) {
                split();
            }
        }
    }

558 559
    /**
     * \brief Inserts a particle in the tree rooted at node
560 561 562 563 564 565 566 567
     *
     * Emplaces a particle in the node particle container if it is a leaf. If it
     * isn't, the particle is forwarded to the relevant child.
     *
     * \note The `emplace_back` method of #particle_container_t is used to insert in a leaf
     */
    template<typename... Args>
    void insert(const position_t& position, Args&&... args) {
568
        this->insert(particle_t(position, std::forward<Args>(args)...));
569 570 571
    }


572 573
    /**
     * \brief Extracts a particle from a leaf
574 575
     *
     * If the nodes is not a leaf, does nothing.
576 577 578
     *
     * \return If in a leaf, the corresponding particle, otherwise a default
     * constructed particle_t
579 580 581
     */
    particle_t extract(const std::size_t& idx) {
        if(getParticleContainer()) {
582
            particle_t p(*(getParticleContainer()->begin() + idx));
583
            getParticleContainer()->erase(getParticleContainer()->begin() + idx);
584
            return p;
585
        }
586
        return particle_t();
587 588
    }

589 590
    /**
     * \brief Splits or fuses nodes after tree modifications
591 592 593 594 595 596 597 598 599 600 601 602
     *
     * Iterates over all the sub-tree particles and splits the leafs that
     * hold too many particles or fuses those that hold too few.
     *
     * This may be necessary when the tree parameters have been changed
     * (leaf max particle count modified) or when particles have moved and
     * been reinserted in the tree to be in the right boxes.
     */
    void reshape() {
        if(is_leaf()) {
            if(getParticleCount() > getTree().leaf_max_particle_count()) {
                split();
603 604
            } else {
                update_tree_height(); // split will update the tree height otherwise
605 606 607 608 609 610 611 612 613 614 615 616 617 618
            }
        } else {
            std::size_t p_count = 0;
            for(auto child : getChildren()) {
                child->reshape();
                p_count += child->getParticleCount();
            }

            if(p_count <= getTree().leaf_max_particle_count()) {
                fuse();
            }
        }
    }

619 620 621 622 623 624 625 626 627 628
    void split_to_height(const std::size_t new_height) {
        assert(new_height < 30); // Trees cannot go this high, means an underflow happened
        if(new_height <= 1) {
            return;
        }

        if(this->is_leaf()) {
            this->split();
            for(auto& child : this->getChildren()) {
                child->split_to_height(new_height - 1);
629 630 631 632
            }
        }
    }

633 634 635
    /**
     * \brief Applies a function to the node and it descendants in order
     */
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
    void for_each_in_order(std::function<void(FNode*)> lambda) {
        std::size_t idx = 0;
        if(! is_leaf()) {
            for(; idx < getChildren().size()/2; ++idx) {
                getChildren()[idx]->for_each_in_order(lambda);
            }
        }
        lambda(this);
        if(! is_leaf()) {
            for(; idx < getChildren().size(); ++idx) {
                getChildren()[idx]->for_each_in_order(lambda);
            }
        }
    }

651 652 653
    /**
     * \brief Applies a function to the node and it descendants post order (children first)
     */
654 655 656 657 658 659 660 661 662
    void for_each_post_order(std::function<void(FNode*)> lambda) {
        if(! is_leaf()) {
            for(std::size_t idx = 0; idx < getChildren().size(); ++idx) {
                getChildren()[idx]->for_each_post_order(lambda);
            }
        }
        lambda(this);
    }

663 664 665
    /**
     * \brief Applies a function to the node and it descendants pre order (parent first)
     */
666 667 668 669 670 671 672 673 674
    void for_each_pre_order(std::function<void(FNode*)> lambda) {
        lambda(this);
        if(! is_leaf()) {
            for(std::size_t idx = 0; idx < getChildren().size(); ++idx) {
                getChildren()[idx]->for_each_pre_order(lambda);
            }
        }
    }

675 676 677
    /**
     * \brief Equality test operator
     */
678 679 680 681 682 683 684
    bool operator==(const FNode& other) const {
        return other.getParent() == getParent()
            && other.getDepth() == getDepth()
            && other.getIndex() == getIndex();
    }

private:
685 686


687 688
    /**
     * \brief Initialization of FNode cell data
689 690 691 692 693
     *
     * Encloses the init functions that are used to initializes cell data
     * according to their base class.
     */
    struct cell_data_initializer {
694 695
        /**
         * \brief Initializer when CellData is derived from FBasicCell
696 697 698 699 700
         *
         * \tparam CellData Type of the node data
         * \tparam Unnamed SFINAE type to check that CellData is derived from
         * FBasicCell
         */
701
        template<typename CellData, scalfmm::sfinae::derived_from<FBasicCell, CellData> = nullptr >
702 703
        static void init(CellData* data, FNode* const node) {
            data->setMortonIndex(node->getIndex());
704
            FTreeCoordinate coord(node->getIndex());
705
            data->setCoordinate(coord);
706
            data->setLevel(node->getDepth());
707 708
        }

709
        /**
710 711
         * \brief Catch-all initializer, no-op
         */
712 713 714 715
        static void init(...) {}

    };

716
    /**
717 718
     * \brief Common initialization done by constructors
     */
719 720 721 722
    void common_init() {
        cell_data_initializer::init(this->getData(), this);
    }

723 724 725
    /**
     * \brief Tree setter
     */
726 727 728 729 730 731 732 733 734
    void setTree(tree_t* t) {
        _tree = t;
        if(! is_leaf()) {
            for(FNode*& child : getChildren()) {
                child->setTree(t);
            }
        }
    }

735 736 737
    /**
     * \brief Updates the tree height when called from a leaf
     *
738 739 740 741 742 743 744
     * \warning Must be called from a leaf
     */
    void update_tree_height() {
        assert(is_leaf() == true);
        if(getDepth()+1 > getTree().height())
            getTree().set_height(getDepth() + 1);
    }
745

746 747 748
    /**
     * \brief Creates or allocates the particle container
     */
749
    void create_particle_container() {
750 751
        _p_container.clear();
        _p_container.reserve(this->getTree().leaf_max_particle_count());
752 753
    }

754 755 756
    /**
     * \brief Deletes the particle container to save space when it is not needed
     */
757
    void delete_particle_container() {
758
        _p_container.clear();
759 760
    }

761 762 763
    /**
     * \brief Allocates this node's children
     */
764 765
    void create_children() {
        std::size_t idx = 0;
766
        // Remove this node from tree leaf list
767
        getTree().leaves().erase(this);
768
        // Create the children, add them to tree leaf list
769
        FNode* tmp = this->getTree().node_memory_manager.provide(this->getDepth()+1, child_count);
770
        for(FNode*& child : getChildren()) {
771
            child = new(tmp+idx) FNode(*this, idx);
772 773 774
            getTree().leaves().insert(child);
            ++idx;
        }
775 776 777
        // Update tree height from child
        getChild(0)->update_tree_height();
        // Remove leaf status from this node
778 779 780
        _is_leaf = false;
    }

781 782 783
    /*
     * \brief Deletes this node's children
     */
784
    void delete_children() {
785
        // Remove children from tree leaf list, free them
786
        for(FNode*& child : getChildren()) {
787 788 789 790
            if(child) {
                getTree().leaves().erase(child);
                child->~FNode();
            }
791
        }
792
        std::fill_n(this->getChildren().data(), child_count, nullptr);
793
        // Insert this node in tree leaf list
794
        getTree().leaves().insert(this);
795
        // Set leaf status for this node
796 797 798
        _is_leaf = true;
    }

799 800
    /**
     * \brief Adds children to a leaf node
801 802 803 804 805
     *
     * Adds children to a leaf node and redistributes its particles among
     * the newly created leaves.
     */
    void split() {
806 807
        assert(this->is_leaf());

808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
        if(getDepth()+1 > getTree().max_height()) {
            // TODO: log that there were too many particles
            return;
        }

        create_children();

        // Update interaction lists
        this->U.erase(this);
        for(FNode* child : getChildren()) {
            // Children are adjacent to each other
            child->U.insert(getChildren().begin(), getChildren().end());
            // Find where to put U list items in child
            for(FNode* u_item : this->U) {
                if(child->is_adjacent(u_item)) {
                    // Adjacent to child
                    child->U.insert(u_item);
                    u_item->U.insert(child);
                } else if(u_item->getDepth() < child->getDepth()) {
                    // Adjacent to parent (this) but not to child
                    child->X.insert(u_item);
                    u_item->W.insert(child);
                } else { // u_item->getDepth() >= child->getDepth()
                    // Find ancestor of u_item that is adjacent to child
                    while(u_item->getDepth() > child->getDepth()) {
                        if(child->is_adjacent(u_item->getParent())) {
                            // Parent is adjacent -> W list
                            child->W.insert(u_item);
                            u_item->X.insert(child);
                            break;
                        } else {
                            u_item = u_item->getParent();
                        }
                    }
                    if(u_item->getDepth() == child->getDepth()) {
                        // No adjacent ancestor -> add a neighbour
                        child->V.insert(u_item);
                        u_item->V.insert(child);
                    }
                }
            }

            // Find where to put W list items in child
            for(FNode* w_item : this->W) {
                // Find first ancestor of w_item that is adjacent to child
                // not needed, done in U list treatment, only check parent
                if(child->getDepth() < w_item->getDepth()) {
                    if(child->is_adjacent(w_item->getParent())) {
                        child->W.insert(w_item);
                        w_item->X.insert(child);
                    }
                } else if(child->getDepth() == w_item->getDepth()) {
                    // No adjacent ancestor -> add a neighbour
                    child->V.insert(w_item);
                    w_item->V.insert(child);
                }
            }
        }
        // Remove this from other lists
        for(FNode* w_item : this->W) {
            w_item->X.erase(this);
        }
        for(FNode* u_item : this->U) {
            u_item->U.erase(this);
        }
        // Clear leaf-only lists
        this->U.clear();
        this->W.clear();

        move_particles_to_children();
    }

880

881 882
    /**
     * \brief Reinsert particles once children have been added
883 884 885
     *
     * The particle container is deleted afterwards.
     */
886 887
    void move_particles_to_children() {
        for(auto&& p : *getParticleContainer()) {
888
            this->insert(particle_t(p));
889 890 891 892 893
        }
        delete_particle_container();
    }


894 895 896
    /**
     * \brief Fuses the children nodes until this node becomes a leaf
     */
897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970
    void fuse() {
        if(is_leaf()) {
            return; // In a leaf, there's nothing to do
        }

        for(FNode* child : getChildren()) {
            child->fuse(); // Fuse children into leaves
        }

        create_particle_container();
        _is_leaf = true;

        // Remove children from U lists
        for(FNode* child_1 : getChildren()) {
            for(FNode* child_2 : getChildren()) {
                child_1->U.erase(child_2);
            }
        }
        // Use the children interaction lists to update this one
        for(FNode* child : getChildren()) {
            // Child U list items get into this U list
            for(FNode* u_item : child->U) {
                // Remove child from u_item U list
                u_item->U.erase(child);
                // Add this and u_item in each other's U lists
                this->U.insert(u_item);
                u_item->U.insert(this);
            }
            child->U.clear();

            // Child X list items get into the this U list
            for(FNode* x_item : child->X) {
                // Remove child from x_item W list
                x_item->W.erase(child);
                // Add this and x_item in each other's U lists
                this->U.insert(x_item);
                x_item->U.insert(this);
            }

            // Child W items get into this W list
            for(FNode* w_item : child->W) {
                // Remove child from w_item X list
                w_item->X.erase(child);
                // Add this and w_item in each other's W and X lists
                // when w_item is not adjacent to this
                if(! is_adjacent(w_item)) {
                    this->W.insert(w_item);
                    w_item->X.insert(this);
                }
            }

            // Child V list items get into this W list
            for(FNode* v_item : child->V) {
                // Remove child from the v_item V list
                v_item->V.erase(child);
                // Add this and v_item in each other's W and X lists
                // when v_item is not adjacent to this
                if(! is_adjacent(v_item)) {
                    this->W.insert(v_item);
                    v_item->X.insert(this);
                }
            }

            for(auto&& p : *(child->getParticleContainer())) {
                insert(p);
            }
        }
        // This belongs to its own U list
        this->U.insert(this);
        // Clear the children after everything is updated
        delete_children();

    }

971
    void terminal_print(std::ostream& os, bool print_particles) const {
972

973
        // Indentation
974
        if(! this->getParent()) {
975 976 977
            os << "└─ ";
        } else {
            std::string indent;
978
            const FNode* parent = this->getParent();
979 980 981 982 983 984 985 986 987
            while(parent) {
                if((parent->getIndex() & (child_count-1)) == child_count-1
                   || ! parent->getParent()) {
                    indent = "   " + indent;
                } else {
                    indent = "│  " + indent;
                }
                parent = parent->getParent();
            }
988
            if((this->getIndex() & (child_count-1)) == child_count-1) {
989 990 991 992 993 994 995
                os << indent << "└─ ";
            } else{
                os << indent << "├─ ";
            }
        }

        // Node data and recurrence
996 997
        auto index_width =
            std::setw(static_cast<int>(
998
                          std::log10(1 << (Dim * (this->getDepth()+1)))));
999 1000 1001 1002

        if(! this->is_leaf()) { // Internal node
            os << "node " << index_width << this->getIndex() << ":\n";
            for(auto&& child : this->getChildren()) {
1003
                child->terminal_print(os, print_particles);
1004
            }
1005
        } else { // Leaf
1006 1007 1008 1009
            os << "leaf "<< index_width << this->getIndex() <<": ";
            const auto& p_container = *(this->getParticleContainer());
            auto count_width =
                std::setw(static_cast<int>(
1010
                              std::log10(this->getTree().leaf_max_particle_count())));
1011 1012 1013
            os << count_width << p_container.size() << " particle";
            os << (p_container.size() > 1 ? "s" : "");

1014 1015 1016 1017 1018
            if(print_particles && p_container.size() > 0) {
                os << " [";
                auto it = inria::make_ostream_joiner(os, ", ");
                std::copy(p_container.begin(), p_container.end(), it);
                os << "]";
1019
            }
1020
            os << '\n';
1021 1022 1023 1024
        }
    }

    void obj_print(std::ostream& os) const {
1025 1026 1027
        if(Dim != 3 && Dim != 2) {
            return;
        }
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
        // When not on a leaf, recurse to leaf
        if(! this->is_leaf()) {
            for(auto& child : getChildren()) {
                child->obj_print(os);
            }
        } else {
            // Print each of the box vertices
            const box_t& box = this->getBox();
            // note, child_count is the box's corner count
            for(std::size_t i = 0; i < child_count; ++i) {
                const position_t p = box.corner(i);
                os << "v";
                for(auto c : p) {
                    os << ' ' << c;
                }
                os << '\n';
            }
Quentin Khan's avatar
Quentin Khan committed
1045

1046
            // Print the box faces
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
            if(Dim == 3) {
                os << "f -8 -7 -5 -6\n";
                os << "f -8 -7 -3 -4\n";
                os << "f -6 -5 -1 -2\n";
                os << "f -4 -3 -1 -2\n";
                os << "f -7 -5 -1 -3\n";
                os << "f -8 -6 -2 -4\n";
                os << '\n';
            } else if(Dim == 2) {
                os << "f -4 -3 -1 -2\n";
            }
1058 1059 1060 1061 1062
        }
    }

public:
    friend std::ostream& operator<<(std::ostream& os, const FNode& node) {
1063
        if(os.iword(scalfmm::fmt::node_os_format_id()) == scalfmm::fmt::OBJ) {
1064 1065
            node.obj_print(os);
        } else {
1066 1067
            bool p_parts = os.iword(scalfmm::fmt::node_os_particle_id());
            node.terminal_print(os, p_parts);
1068 1069 1070
        }
        return os;
    }
1071 1072 1073 1074
};


#endif