MOAB: Mesh Oriented datABase  (version 5.3.1)
element_tree.hpp
Go to the documentation of this file.
00001 /**
00002  * element_tree.hpp
00003  * Ryan H. Lewis
00004  * (C) 2012
00005  *
00006  * An element tree partitions a mesh composed of elements.
00007  * We subdivide the bounding box of a mesh, and each element is
00008  * either entirely on the left, entirely on the right, or crossing
00009  * the diving line. We build a tree on the mesh with this property.
00010  */
00011 #include <vector>
00012 #include <set>
00013 #include <iostream>
00014 #include <map>
00015 #include <algorithm>
00016 #include <bitset>
00017 #include <numeric>
00018 #include <cmath>
00019 #include <tr1/unordered_map>
00020 #include <limits>
00021 
00022 #include "common_tree.hpp"
00023 
00024 #ifndef ELEMENT_TREE_HPP
00025 #define ELEMENT_TREE_HPP
00026 namespace moab
00027 {
00028 // forward declarations
00029 
00030 template < typename _Entity_handles, typename _Box, typename _Moab, typename _Parametrizer >
00031 class Element_tree;
00032 
00033 // non-exported functionality
00034 namespace
00035 {
00036     namespace _element_tree
00037     {
00038         template < typename Iterator >
00039         struct Iterator_comparator
00040         {
00041             typedef typename Iterator::value_type Value;
00042             bool operator()( const Value& a, const Value& b )
00043             {
00044                 return a->second.second.to_ulong() < b->second.second.to_ulong();
00045             }
00046         };  // Iterator_comparator
00047 
00048         template < typename Data >
00049         struct Split_comparator
00050         {
00051             // we minimizes ||left| - |right|| + |middle|^2
00052             double split_objective( const Data& a ) const
00053             {
00054                 if( a.second.sizes[2] == 0 || a.second.sizes[0] == 0 )
00055                 {
00056                     return std::numeric_limits< std::size_t >::max();
00057                 }
00058                 const double total = a.second.sizes[0] + a.second.sizes[2];
00059                 const int max      = 2 * ( a.second.sizes[2] > a.second.sizes[0] );
00060 
00061                 return ( a.second.sizes[max] - a.second.sizes[2 * ( 1 - ( max == 2 ) )] ) / total;
00062             }
00063             bool operator()( const Data& a, const Data& b ) const
00064             {
00065                 return split_objective( a ) < split_objective( b );
00066             }
00067         };  // Split_comparator
00068 
00069         template < typename Partition_data, typename Box >
00070         void correct_bounding_box( const Partition_data& data, Box& box, const int child )
00071         {
00072             const int dim = data.dim;
00073             switch( child )
00074             {
00075                 case 0:
00076                     box.max[dim] = data.left_rightline;
00077                     break;
00078                 case 1:
00079                     box.max[dim] = data.right_line;
00080                     box.min[dim] = data.left_line;
00081                     break;
00082                 case 2:
00083                     box.min[dim] = data.right_leftline;
00084                     break;
00085             }
00086 #ifdef ELEMENT_TREE_DEBUG
00087             print_vector( data.bounding_box.max );
00088             print_vector( data.bounding_box.min );
00089             print_vector( box.max );
00090             print_vector( box.min );
00091 #endif
00092         }
00093 
00094         template < typename Box >
00095         struct _Partition_data
00096         {
00097             typedef _Partition_data< Box > Self;
00098             // default constructor
00099             _Partition_data() : sizes( 3, 0 ), dim( 0 ) {}
00100             _Partition_data( const Self& f )
00101             {
00102                 *this = f;
00103             }
00104             _Partition_data( const Box& _box, int _dim )
00105                 : sizes( 3, 0 ), bounding_box( _box ), split( ( _box.max[_dim] + _box.min[_dim] ) / 2.0 ),
00106                   left_line( split ), right_line( split ), dim( _dim )
00107             {
00108             }
00109             _Partition_data& operator=( const Self& f )
00110             {
00111                 sizes          = f.sizes;
00112                 bounding_box   = f.bounding_box;
00113                 split          = f.split;
00114                 left_line      = f.left_line;
00115                 right_line     = f.right_line;
00116                 right_leftline = f.right_leftline;
00117                 left_rightline = f.left_rightline;
00118                 dim            = f.dim;
00119                 return *this;
00120             }
00121             std::vector< std::size_t > sizes;
00122             Box bounding_box;
00123             double split;
00124             double left_line;
00125             double right_line;
00126             double right_leftline;
00127             double left_rightline;
00128             int dim;
00129             std::size_t left() const
00130             {
00131                 return sizes[0];
00132             }
00133             std::size_t middle() const
00134             {
00135                 return sizes[1];
00136             }
00137             std::size_t right() const
00138             {
00139                 return sizes[2];
00140             }
00141         };  // Partition_data
00142 
00143         template < typename _Entity_handles, typename _Entities >
00144         class _Node
00145         {
00146             // public types:
00147           public:
00148             typedef _Entity_handles Entity_handles;
00149             typedef _Entities Entities;
00150 
00151             // private types:
00152           private:
00153             typedef _Node< _Entity_handles, _Entities > Self;
00154 
00155             // Constructors
00156           public:
00157             // Default constructor
00158             _Node()
00159                 : children( 3, -1 ), left_( children[0] ), middle_( children[1] ), right_( children[2] ), dim( -1 ),
00160                   split( 0 ), left_line( 0 ), right_line( 0 ), entities( 0 )
00161             {
00162             }
00163 
00164             // Copy constructor
00165             _Node( const Self& from )
00166                 : children( from.children ), left_( children[0] ), middle_( children[1] ), right_( children[2] ),
00167                   dim( from.dim ), split( from.split ), left_line( from.left_line ), right_line( from.right_line ),
00168                   entities( from.entities )
00169             {
00170             }
00171 
00172           public:
00173             template < typename Iterator >
00174             void assign_entities( const Iterator& begin, const Iterator& end )
00175             {
00176                 entities.reserve( std::distance( begin, end ) );
00177                 for( Iterator i = begin; i != end; ++i )
00178                 {
00179                     entities.push_back( std::make_pair( ( *i )->second.first, ( *i )->first ) );
00180                 }
00181             }
00182 
00183             // Functionality
00184           public:
00185             bool leaf() const
00186             {
00187                 return children[0] == -1 && children[1] == -1 && children[2] == -1;
00188             }
00189             Self& operator=( const Self& from )
00190             {
00191                 children   = from.children;
00192                 dim        = from.dim;
00193                 left_      = from.left_;
00194                 middle_    = from.middle_;
00195                 right_     = from.right_;
00196                 split      = from.split;
00197                 left_line  = from.left_line;
00198                 right_line = from.right_line;
00199                 entities   = from.entities;
00200                 return *this;
00201             }
00202             template < typename Box >
00203             Self& operator=( const _Partition_data< Box >& from )
00204             {
00205                 dim        = from.dim;
00206                 split      = from.split;
00207                 left_line  = from.left_line;
00208                 right_line = from.right_line;
00209                 return *this;
00210             }
00211             // private data members:
00212           private:
00213             // indices of children
00214             std::vector< int > children;
00215             int &left_, middle_, right_;
00216             int dim;       // split dimension
00217             double split;  // split position
00218             double left_line;
00219             double right_line;
00220             Entities entities;
00221 
00222             // Element_tree can touch my privates.
00223             template < Entity_handles, typename B >
00224             friend class moab::Element_tree;
00225         };  // class Node
00226 
00227     }  // namespace _element_tree
00228 }  // namespace
00229 
00230 template < typename _Entity_handles, typename _Box, typename _Moab, typename _Parametrizer >
00231 class Element_tree
00232 {
00233 
00234     // public types
00235   public:
00236     typedef _Entity_handles Entity_handles;
00237     typedef _Box Box;
00238     typedef _Moab Moab;
00239     typedef _Parametrizer Parametrizer;
00240     typedef typename Entity_handles::value_type Entity_handle;
00241 
00242     // private types
00243   private:
00244     typedef Element_tree< _Entity_handles, _Box, _Moab, _Parametrizer > Self;
00245     typedef std::pair< Box, Entity_handle > Leaf_element;
00246     typedef _element_tree::_Node< Entity_handles, std::vector< Leaf_element > > Node;
00247 // int is because we only need to store
00248 #define MAX_ITERATIONS 2
00249     typedef common_tree::_Element_data< Box, std::bitset< NUM_DIM * MAX_ITERATIONS * 2 > > Element_data;
00250     typedef std::vector< Node > Nodes;
00251     // TODO: we really want an unordered map here, make sure this is kosher..
00252     typedef std::tr1::unordered_map< Entity_handle, Element_data > Element_map;
00253     typedef typename std::vector< typename Element_map::iterator > Element_list;
00254     typedef _element_tree::_Partition_data< Box > Partition_data;
00255     // public methods
00256   public:
00257     // Constructor
00258     Element_tree( Entity_handles& _entities, Moab& _moab, Box& _bounding_box, Parametrizer& _entity_contains )
00259         : entity_handles_( _entities ), tree_(), moab( _moab ), bounding_box( _bounding_box ),
00260           entity_contains( _entity_contains )
00261     {
00262         tree_.reserve( _entities.size() );
00263         Element_map element_map( _entities.size() );
00264         Partition_data _data;
00265         common_tree::construct_element_map( entity_handles_, element_map, _data.bounding_box, moab );
00266         bounding_box  = _data.bounding_box;
00267         _bounding_box = bounding_box;
00268         Element_list element_ordering( element_map.size() );
00269         std::size_t index = 0;
00270         for( typename Element_map::iterator i = element_map.begin(); i != element_map.end(); ++i, ++index )
00271         {
00272             element_ordering[index] = i;
00273         }
00274         // We only build nonempty trees
00275         if( element_ordering.size() )
00276         {
00277             // initially all bits are set
00278             std::bitset< 3 > directions( 7 );
00279             tree_.push_back( Node() );
00280             int depth = 0;
00281             build_tree( element_ordering.begin(), element_ordering.end(), 0, directions, _data, depth );
00282             std::cout << "depth: " << depth << std::endl;
00283         }
00284     }
00285 
00286     // Copy constructor
00287     Element_tree( Self& s )
00288         : entity_handles_( s.entity_handles_ ), tree_( s.tree_ ), moab( s.moab ), bounding_box( s.bounding_box )
00289     {
00290     }
00291 
00292     // private functionality
00293   private:
00294     template < typename Iterator, typename Split_data >
00295     void compute_split( Iterator& begin, Iterator& end, Split_data& split_data, bool iteration = false )
00296     {
00297         typedef typename Iterator::value_type::value_type Map_value_type;
00298         typedef typename Map_value_type::second_type::second_type Bitset;
00299         // we will update the left/right line
00300         double& left_line  = split_data.left_line;
00301         double& right_line = split_data.right_line;
00302         double& split      = split_data.split;
00303         const int& dim     = split_data.dim;
00304 #ifdef ELEMENT_TREE_DEBUG
00305         std::cout << std::endl;
00306         std::cout << "-------------------" << std::endl;
00307         std::cout << "dim: " << dim << " split: " << split << std::endl;
00308         std::cout << "bounding_box min: ";
00309         print_vector( split_data.bounding_box.min );
00310         std::cout << "bounding_box max: ";
00311         print_vector( split_data.bounding_box.max );
00312 #endif
00313         // for each elt determine if left/middle/right
00314         for( Iterator i = begin; i != end; ++i )
00315         {
00316             const Box& box = ( *i )->second.first;
00317             Bitset& bits   = ( *i )->second.second;
00318             // will be 0 if on left, will be 1 if in the middle
00319             // and 2 if on the right;
00320             const bool on_left   = ( box.max[dim] < split );
00321             const bool on_right  = ( box.min[dim] > split );
00322             const bool in_middle = !on_left && !on_right;
00323             // set the corresponding bits in the bit vector
00324             // looks like: [x_1 = 00 | x_2 = 00 | .. | z_1 = 00 | z_2 = 00]
00325             // two bits, left = 00, middle = 01, right = 10
00326             const int index = 4 * dim + 2 * iteration;
00327             if( on_left ) { split_data.sizes[0]++; }
00328             else if( in_middle )
00329             {
00330                 split_data.sizes[1]++;
00331                 bits.set( index, 1 );
00332                 left_line  = std::min( left_line, box.min[dim] );
00333                 right_line = std::max( right_line, box.max[dim] );
00334             }
00335             else if( on_right )
00336             {
00337                 bits.set( index + 1, 1 );
00338                 split_data.sizes[2]++;
00339             }
00340         }
00341 #ifdef ELEMENT_TREE_DEBUG
00342         std::size_t _count = std::accumulate( split_data.sizes.begin(), split_data.sizes.end(), 0 );
00343         std::size_t total  = std::distance( begin, end );
00344         if( total != _count ) { std::cout << total << "vs. " << _count << std::endl; }
00345         std::cout << " left_line: " << left_line;
00346         std::cout << " right_line: " << right_line << std::endl;
00347         std::cout << "co/mputed partition size: ";
00348         print_vector( split_data.sizes );
00349         std::cout << "-------------------" << std::endl;
00350 #endif
00351     }
00352 
00353     template < typename Split_data >
00354     bool update_split_line( Split_data& data ) const
00355     {
00356         const int max        = 2 * ( data.sizes[2] > data.sizes[0] );
00357         const int min        = 2 * ( 1 - ( max == 2 ) );
00358         bool one_side_empty  = data.sizes[max] == 0 || data.sizes[min] == 0;
00359         double balance_ratio = data.sizes[max] - data.sizes[min];
00360         // if ( !one_side_empty && balance_ratio < .05*total){ return false; }
00361         if( !one_side_empty )
00362         {
00363             // if we have some imbalance on left/right
00364             // try to fix the situation
00365             balance_ratio /= data.sizes[max];
00366             data.split += ( max - 1 ) * balance_ratio * ( data.split / 2.0 );
00367         }
00368         else
00369         {
00370             // if the (left) side is empty move the split line just past the
00371             // extent of the (left) line of the middle box.
00372             // if middle encompasses everything then wiggle
00373             // the split line a bit and hope for the best..
00374             const double left_distance  = std::abs( data.left_line - data.split );
00375             const double right_distance = std::abs( data.right_line - data.split );
00376             if( ( data.sizes[0] == 0 ) && ( data.sizes[2] != 0 ) ) { data.split += right_distance; }
00377             else if( data.sizes[2] == 0 && data.sizes[0] != 0 )
00378             {
00379                 data.split -= left_distance;
00380             }
00381             else
00382             {
00383                 data.split *= 1.05;
00384             }
00385         }
00386         data.left_line = data.right_line = data.split;
00387         data.sizes.assign( data.sizes.size(), 0 );
00388         return true;
00389     }
00390 
00391     template < typename Iterator, typename Split_data, typename Directions >
00392     void determine_split( Iterator& begin, Iterator& end, Split_data& data, const Directions& directions )
00393     {
00394         typedef typename Iterator::value_type Pair;
00395         typedef typename Pair::value_type Map_value_type;
00396         typedef typename Map_value_type::second_type::second_type Bitset;
00397         typedef typename Map_value_type::second_type::first_type Box;
00398         typedef typename std::map< std::size_t, Split_data > Splits;
00399         typedef typename Splits::value_type Split;
00400         typedef _element_tree::Split_comparator< Split > Comparator;
00401         Splits splits;
00402         for( std::size_t dir = 0; dir < directions.size(); ++dir )
00403         {
00404             if( directions.test( dir ) )
00405             {
00406                 Split_data split_data( data.bounding_box, dir );
00407                 compute_split( begin, end, split_data );
00408                 splits.insert( std::make_pair( 2 * dir, split_data ) );
00409                 if( update_split_line( split_data ) )
00410                 {
00411                     compute_split( begin, end, split_data, true );
00412                     splits.insert( std::make_pair( 2 * dir + 1, split_data ) );
00413                 }
00414             }
00415         }
00416         Split best = *std::min_element( splits.begin(), splits.end(), Comparator() );
00417 #ifdef ELEMENT_TREE_DEBUG
00418         std::cout << "best: " << Comparator().split_objective( best ) << " ";
00419         print_vector( best.second.sizes );
00420 #endif
00421         const int dir          = best.first / 2;
00422         const int iter         = best.first % 2;
00423         double& left_rightline = best.second.left_rightline = best.second.bounding_box.min[dir];
00424         double& right_leftline = best.second.right_leftline = best.second.bounding_box.max[dir];
00425         Bitset mask( 0 );
00426         mask.flip( 4 * dir + 2 * iter ).flip( 4 * dir + 2 * iter + 1 );
00427         for( Iterator i = begin; i != end; ++i )
00428         {
00429             Bitset& bits   = ( *i )->second.second;
00430             const Box& box = ( *i )->second.first;
00431             // replace 12 bits with just two.
00432             bits &= mask;
00433             bits >>= 4 * dir + 2 * iter;
00434             // if box is labeled left/right but properly contained
00435             // in the middle, move the element into the middle.
00436             // we can shrink the size of left/right
00437             switch( bits.to_ulong() )
00438             {
00439                 case 0:
00440                     if( box.max[dir] > best.second.left_line )
00441                     {
00442                         left_rightline = std::max( left_rightline, box.max[dir] );
00443                     }
00444                     break;
00445                 case 2:
00446                     if( box.min[dir] < best.second.right_line )
00447                     {
00448                         right_leftline = std::min( right_leftline, box.max[dir] );
00449                     }
00450                     break;
00451             }
00452         }
00453         data = best.second;
00454     }
00455 
00456 // define here for now.
00457 #define ELEMENTS_PER_LEAF 30
00458 #define MAX_DEPTH         30
00459 #define EPSILON           1e-1
00460     template < typename Iterator, typename Node_index, typename Directions, typename Partition_data >
00461     void build_tree( Iterator begin, Iterator end, const Node_index node, const Directions& directions,
00462                      Partition_data& _data, int& depth, const bool is_middle = false )
00463     {
00464         std::size_t number_elements = std::distance( begin, end );
00465         if( depth < MAX_DEPTH && number_elements > ELEMENTS_PER_LEAF && ( !is_middle || directions.any() ) )
00466         {
00467             determine_split( begin, end, _data, directions );
00468             // count_sort( begin, end, _data);
00469             std::sort( begin, end, _element_tree::Iterator_comparator< Iterator >() );
00470             // update the tree
00471             tree_[node] = _data;
00472             Iterator middle_begin( begin + _data.left() );
00473             Iterator middle_end( middle_begin + _data.middle() );
00474             std::vector< int > depths( 3, depth );
00475             // left subtree
00476             if( _data.left() > 0 )
00477             {
00478                 Partition_data data( _data );
00479                 tree_.push_back( Node() );
00480                 tree_[node].children[0] = tree_.size() - 1;
00481                 correct_bounding_box( _data, data.bounding_box, 0 );
00482                 Directions new_directions( directions );
00483                 const bool axis_is_very_small =
00484                     ( data.bounding_box.max[_data.dim] - data.bounding_box.min[_data.dim] < EPSILON );
00485                 new_directions.set( _data.dim, axis_is_very_small );
00486                 build_tree( begin, middle_begin, tree_[node].children[0], new_directions, data, ++depths[0],
00487                             is_middle );
00488             }
00489             // middle subtree
00490             if( _data.middle() > 0 )
00491             {
00492                 Partition_data data( _data );
00493                 tree_.push_back( Node() );
00494                 tree_[node].children[1] = tree_.size() - 1;
00495                 correct_bounding_box( _data, data.bounding_box, 1 );
00496                 // force the middle subtree to split
00497                 // in a different direction from this one
00498                 Directions new_directions( directions );
00499                 new_directions.flip( tree_[node].dim );
00500                 bool axis_is_very_small =
00501                     ( data.bounding_box.max[_data.dim] - data.bounding_box.min[_data.dim] < EPSILON );
00502                 new_directions.set( _data.dim, axis_is_very_small );
00503                 build_tree( middle_begin, middle_end, tree_[node].children[1], new_directions, data, ++depths[1],
00504                             true );
00505             }
00506             // right subtree
00507             if( _data.right() > 0 )
00508             {
00509                 Partition_data data( _data );
00510                 tree_.push_back( Node() );
00511                 tree_[node].children[2] = tree_.size() - 1;
00512                 correct_bounding_box( _data, data.bounding_box, 2 );
00513                 Directions new_directions( directions );
00514                 const bool axis_is_very_small =
00515                     ( data.bounding_box.max[_data.dim] - data.bounding_box.min[_data.dim] < EPSILON );
00516                 new_directions.set( _data.dim, axis_is_very_small );
00517 
00518                 build_tree( middle_end, end, tree_[node].children[2], directions, data, ++depths[2], is_middle );
00519             }
00520             depth = *std::max_element( depths.begin(), depths.end() );
00521         }
00522         if( tree_[node].leaf() ) { common_tree::assign_entities( tree_[node].entities, begin, end ); }
00523     }
00524 
00525     template < typename Vector, typename Node_index, typename Result >
00526     Result& _find_point( const Vector& point, const Node_index& index, Result& result ) const
00527     {
00528         typedef typename Node::Entities::const_iterator Entity_iterator;
00529         typedef typename std::pair< bool, Vector > Return_type;
00530         const Node& node = tree_[index];
00531         if( node.leaf() )
00532         {
00533             // check each node
00534             for( Entity_iterator i = node.entities.begin(); i != node.entities.end(); ++i )
00535             {
00536                 if( common_tree::box_contains_point( i->first, point ) )
00537                 {
00538                     Return_type r = entity_contains( moab, i->second, point );
00539                     if( r.first ) { result = std::make_pair( i->second, r.second ); }
00540                     return result;
00541                 }
00542             }
00543             return Result( 0, point );
00544         }
00545         if( point[node.dim] < node.left_line ) { return _find_point( point, node.left_, result ); }
00546         else if( point[node.dim] > node.right_line )
00547         {
00548             return _find_point( point, node.right_, result );
00549         }
00550         else
00551         {
00552             Entity_handle middle = _find_point( point, node.middle_, result );
00553             if( middle != 0 ) { return result; }
00554             if( point[node.dim] < node.split ) { return _find_point( point, node.left_, result ); }
00555             return _find_point( point, node.right_, result );
00556         }
00557     }
00558 
00559     // public functionality
00560   public:
00561     template < typename Vector, typename Result >
00562     Result& find( const Vector& point, Result& result ) const
00563     {
00564         typedef typename Vector::const_iterator Point_iterator;
00565         typedef typename Box::Pair Pair;
00566         typedef typename Pair::first_type Box_iterator;
00567         return _find_point( point, 0, result );
00568     }
00569 
00570     // public accessor methods
00571   public:
00572     // private data members
00573   private:
00574     const Entity_handles& entity_handles_;
00575     Nodes tree_;
00576     Moab& moab;
00577     Box bounding_box;
00578     Parametrizer entity_contains;
00579 
00580 };  // class Element_tree
00581 
00582 }  // namespace moab
00583 
00584 #endif  // ELEMENT_TREE_HPP
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Defines