Example #1
0
	void pool::mutate_node(genome& g){
		if (g.genes.size() == 0)
			return ;

		g.max_neuron++;

		// randomly choose a gene to mutate
		std::uniform_int_distribution<unsigned int> distributor(0, g.genes.size()-1);
		unsigned int gene_id = distributor(this->generator);
		auto it = g.genes.begin();
		std::advance(it, gene_id);

		if ((*it).second.enabled == false)
			return ;

		(*it).second.enabled = false;

		gene new_gene1;
		new_gene1.from_node = (*it).second.from_node;
		new_gene1.to_node = g.max_neuron-1; // to the last created neuron
		new_gene1.weight = 1.0;
		new_gene1.innovation_num = this->innovation.add_gene(new_gene1);
		new_gene1.enabled = true;

		gene new_gene2;
		new_gene2.from_node = g.max_neuron-1; // from the last created neuron
		new_gene2.to_node = (*it).second.to_node;
		new_gene2.weight = (*it).second.weight;
		new_gene2.innovation_num = this->innovation.add_gene(new_gene2);
		new_gene2.enabled = true;

		g.genes[new_gene1.innovation_num] = new_gene1;
		g.genes[new_gene2.innovation_num] = new_gene2;
	}
Example #2
0
	void pool::mutate_enable_disable(genome& g, bool enable){

		// that shit is safe because there's no changings in map
		// during this function
		std::vector<gene*> v;

		for (auto it = g.genes.begin(); it != g.genes.end(); it++)
			if ((*it).second.enabled != enable)
				v.push_back(&((*it).second));

		if (v.size() == 0)
			return ;

		std::uniform_int_distribution<int> distributor(0, v.size()-1);
		v[distributor(this->generator)]->enabled = enable;
	}
 void operator()(const rstd::string &listen_endpoint) {
   work_distributor_type distributor(NP1_TEST_UNIT_NP1_RELIABLE_STORAGE_LOCAL_ROOT,
                                     NP1_TEST_UNIT_NP1_RELIABLE_STORAGE_REMOTE_ROOT, listen_endpoint, false);
   reliable_storage_type rs(NP1_TEST_UNIT_NP1_RELIABLE_STORAGE_LOCAL_ROOT,
                             NP1_TEST_UNIT_NP1_RELIABLE_STORAGE_REMOTE_ROOT);
   distributed_worker_processor_fn fn;
     
   distributor.process_requests(fn);
 }
Example #4
0
    std::vector<shortcut> simplify_monotone_line(const poly_line& l, const std::vector<point>& points) const
    {
        tangent_splitter splitter(l);
        point_distributor distributor(l, points);
        shortcut_acceptor acceptor(l);

        std::vector<shortcut> all_shortcuts;

        // note: no edges after last coordinate
        for (auto i = 0u; i < l.coordinates.size() - 1; ++i)
        {
            auto tangents = splitter(i);
            auto assignments = distributor(i, tangents);
            auto partial_shortcuts = acceptor(i, tangents, assignments);
            all_shortcuts.insert(all_shortcuts.end(), partial_shortcuts.begin(), partial_shortcuts.end());
        }

        return all_shortcuts;
    }
Example #5
0
	genome pool::breed_child(specie &s){
		genome child(this->network_info, this->mutation_rates);
		std::uniform_real_distribution<double> distributor(0.0, 1.0);
		std::uniform_int_distribution<unsigned int> choose_genome(0, s.genomes.size()-1);
		if (distributor(this->generator) < this->mutation_rates.crossover_chance){
			unsigned int g1id, g2id;
			genome& g1 = s.genomes[g1id = choose_genome(this->generator)];
			genome& g2 = s.genomes[g2id = choose_genome(this->generator)];
			
			// QUESTION: if g1 == g2, then you can make a baby by fapping?			
			child = this->crossover(g1, g2);
		}
		else 
		{
			genome& g = s.genomes[choose_genome(this->generator)];
			child = g;
		}

		this->mutate(child);		
		return child;
	}
Example #6
0
int main(int argc, char *argv[])
{

    World world(QColor(0,180,180));

    int samples = 1;

    Material *material = new Reflective (QColor(2,255,255), 0.4, 1, 300, 0.6);
    PinholeCamera camera(Vector3(0,0,0),Vector3(0,0,1),Vector3(0,-1,0),Vector2(1,0.75),1);


    world.add(new Sphere(Vector3(-2,-1.15,1), 2,  material));
    world.add(new Sphere(Vector3(2,-1.15,1), 2,  material));
    world.add(new Sphere(Vector3(0,3.45-1.15,1), 2,  material));
    world.add(new Sphere(Vector3(0,1.15-1.15,3.45+1), 2,  material));

    JitteredGenerator gener(0);
    SquareDistributor dist;
    Sampler distributor(gener,dist,samples,60,0);




    world.add_light(PointLight(Vector3(0,0,3.45-2), MyColor(1,1,1)));

    Raytracer tracer(5);
    QImage image;
    image = tracer.ray_trace(world, camera, QSize(800, 600), &distributor);




    QApplication a(argc, argv);
    MainWindow w;

    w.copy_world(image, world);
    w.show_image();
   // w.new_world();
    w.show();
    
    return a.exec();
}
void test_ordered_work_distributor_send_receive() {
  rstd::string client_peer_endpoint = write_client_peer_strings_list();  
  rstd::vector<rstd::string> worker_peer_strings = write_worker_peer_strings_list();  

  rstd::vector<pid_t> children = fork_distributed_workers(worker_peer_strings,
                                                          run_distributed_worker());

  // We can only get to here if we are the parent, which acts as the client.
  ordered_work_distributor_type distributor(NP1_TEST_UNIT_NP1_RELIABLE_STORAGE_LOCAL_ROOT,
                                            NP1_TEST_UNIT_NP1_RELIABLE_STORAGE_REMOTE_ROOT, 
                                            client_peer_endpoint);
  
  
  static const size_t NUMBER_WORK_ITEMS = 500;

  // Send out all the requests.
  size_t i;
  for (i = 0; i < NUMBER_WORK_ITEMS; ++i) {
    reliable_storage_type::id req_resource_id(reliable_storage_type::id::generate());
    create_reliable_storage_file(req_resource_id, ::np1::str::to_dec_str(i));
    distributor.send_request(req_resource_id, ::np1::str::ref(" " + ::np1::str::to_dec_str(i)));    
  }

  // Receive all the responses.  They should be returned to us in order.
  reliable_storage_type::id resp_resource_id;
  for (i = 0; (i < NUMBER_WORK_ITEMS) && distributor.receive_response(resp_resource_id); ++i) {
    rstd::string resp_data = read_reliable_storage_file(resp_resource_id);
    NP1_TEST_ASSERT(resp_data == (::np1::str::to_dec_str(i) + " " + ::np1::str::to_dec_str(i)));
  }

  printf("  number_sinbins: %lu  number_retries: %lu\n",
        (unsigned long)distributor.number_sinbins(),
        (unsigned long)distributor.number_retries());

  kill_distributed_workers(children);

  NP1_TEST_ASSERT(i == NUMBER_WORK_ITEMS);
  NP1_TEST_ASSERT(!distributor.receive_response(resp_resource_id));

}
    static void
    checkSendAcrossNetwork( Teuchos::RCP<Teuchos::Comm<int> const> const &comm,
                            View1 const &ranks, View2 const &v_exp,
                            View2 const &v_ref, bool &success,
                            Teuchos::FancyOStream &out )
    {
        Tpetra::Distributor distributor( comm );
        distributor.createFromSends( toArray( ranks ) );

        // NOTE here we assume that the reference solution is sized properly
        auto v_imp =
            Kokkos::create_mirror( typename View2::memory_space(), v_ref );

        DataTransferKit::Details::DistributedSearchTreeImpl<
            DeviceType>::sendAcrossNetwork( distributor, v_exp, v_imp );

        // FIXME not sure why I need that guy but I do get a bus error when it
        // is not here...
        Kokkos::fence();

        TEST_COMPARE_ARRAYS( toArray( v_imp ), toArray( v_ref ) );
    }
Example #9
0
void plPluginResManager::IPreLoadTextures(plRegistryPageNode* pageNode, int32_t origSeqNumber)
{
    // For common pages, we want to kinda-maybe-load all the objects so they don't get wiped when we
    // re-export them. However, we don't have a good way of telling whether a page is a common page,
    // which is where this hack comes in
    bool common = false;
    for (int i = 0; i < plAgeDescription::kNumCommonPages; i++)
    {
        if (strcmpi(plAgeDescription::GetCommonPage(i), pageNode->GetPageInfo().GetPage()) == 0)
        {
            common = true;
            break;
        }
    }

    if (common)
    {
        // Iterate through all the keys in our page, scattering them to various objectLibs if they're
        // interested. If nobody likes them, they get unreffed and disappear.
        plCommonKeyDistributor distributor(this);
        pageNode->IterateKeys(&distributor);
    }

    // Clear out all the unwanted keys in the page we just loaded (by implication; they won't clear if we already
    // stored the keys via our objectLibs above)
    {
        class plEmptyIterator : public plRegistryKeyIterator
        {
        public:
            virtual bool EatKey(const plKey& key) { return true; }
        } empty;

        pageNode->IterateKeys(&empty);
    }

    // We've loaded anything we needed from this page now, so set it as new so
    // that we won't try loading again
    pageNode->SetNewPage();

    // Get our texture page now, if we're not a texture page
    if (!common)
    {
        // Make sure it's not a global page we're handling either
        if (!pageNode->GetPageInfo().GetLocation().IsReserved())
        {
            int32_t texSeqNum = -1;
            if (origSeqNumber != -1)
                texSeqNum = plPageInfoUtils::GetCommonSeqNumFromNormal(origSeqNumber, plAgeDescription::kTextures);

            // Note: INameToPage will turn around and call us again, so no need to do the call twice
            plRegistryPageNode* texturePage = INameToPage(pageNode->GetPageInfo().GetAge(), 
                                                            plAgeDescription::GetCommonPage(plAgeDescription::kTextures), texSeqNum);
            hsAssert(texturePage != nil, "Unable to get or create the shared textures page? Shouldn't be possible.");

            // Do the other one
            int32_t commonSeqNum = -1;
            if (origSeqNumber != -1)
                commonSeqNum = plPageInfoUtils::GetCommonSeqNumFromNormal(origSeqNumber, plAgeDescription::kGlobal);

            // Note: INameToPage will turn around and call us again, so no need to do the call twice
            plRegistryPageNode* commonPage = INameToPage(pageNode->GetPageInfo().GetAge(), 
                                                            plAgeDescription::GetCommonPage(plAgeDescription::kGlobal),
                                                            commonSeqNum);
            hsAssert(commonPage != nil, "Unable to get or create the shared built-in page? Shouldn't be possible.");
        }
    }
}
void MovingLeastSquareReconstructionOperator<Scalar,Basis,DIM>::setup(
    const Teuchos::RCP<const typename Base::TpetraMap>& domain_map,
    const Teuchos::RCP<FunctionSpace>& domain_space,
    const Teuchos::RCP<const typename Base::TpetraMap>& range_map,
    const Teuchos::RCP<FunctionSpace>& range_space,
    const Teuchos::RCP<Teuchos::ParameterList>& parameters )
{
    DTK_REQUIRE( Teuchos::nonnull(domain_map) );
    DTK_REQUIRE( Teuchos::nonnull(domain_space) );
    DTK_REQUIRE( Teuchos::nonnull(range_map) );
    DTK_REQUIRE( Teuchos::nonnull(range_space) );
    DTK_REQUIRE( Teuchos::nonnull(parameters) );

    // Get the parallel communicator.
    Teuchos::RCP<const Teuchos::Comm<int> > comm = domain_map->getComm();

    // Determine if we have range and domain data on this process.
    bool nonnull_domain = Teuchos::nonnull( domain_space->entitySet() );
    bool nonnull_range = Teuchos::nonnull( range_space->entitySet() );

    // Make sure we are applying the map to nodes.
    DTK_REQUIRE( domain_space->entitySelector()->entityType() ==
		 ENTITY_TYPE_NODE );
    DTK_REQUIRE( range_space->entitySelector()->entityType() ==
		 ENTITY_TYPE_NODE );

    // Extract the DOF maps.
    this->b_domain_map = domain_map;
    this->b_range_map = range_map;

    // Extract the source centers and their ids.
    EntityIterator domain_iterator;
    if ( nonnull_domain )
    {
	domain_iterator = domain_space->entitySet()->entityIterator( 
	    domain_space->entitySelector()->entityType(),
	    domain_space->entitySelector()->selectFunction() );
    }
    int local_num_src = domain_iterator.size();
    Teuchos::ArrayRCP<double> source_centers( DIM*local_num_src);
    Teuchos::ArrayRCP<GO> source_gids( local_num_src );
    EntityIterator domain_begin = domain_iterator.begin();
    EntityIterator domain_end = domain_iterator.end();
    int entity_counter = 0;
    for ( EntityIterator domain_entity = domain_begin;
	  domain_entity != domain_end;
	  ++domain_entity, ++entity_counter )
    {
	source_gids[entity_counter] = domain_entity->id();
	domain_space->localMap()->centroid(
	    *domain_entity, source_centers(DIM*entity_counter,DIM) );
    }

    // Extract the target centers and their ids.
    EntityIterator range_iterator;
    if ( nonnull_range )
    {
	range_iterator = range_space->entitySet()->entityIterator( 
	    range_space->entitySelector()->entityType(),
	    range_space->entitySelector()->selectFunction() );
    } 
    int local_num_tgt = range_iterator.size();
    Teuchos::ArrayRCP<double> target_centers( DIM*local_num_tgt );
    Teuchos::ArrayRCP<GO> target_gids( local_num_tgt );
    EntityIterator range_begin = range_iterator.begin();
    EntityIterator range_end = range_iterator.end();
    entity_counter = 0;
    for ( EntityIterator range_entity = range_begin;
	  range_entity != range_end;
	  ++range_entity, ++entity_counter )
    {
	target_gids[entity_counter] = range_entity->id();
	range_space->localMap()->centroid(
	    *range_entity, target_centers(DIM*entity_counter,DIM) );
    }

    // Build the basis.
    Teuchos::RCP<Basis> basis = BP::create( d_radius );

    // Gather the source centers that are within a radius of the target
    // centers on this proc.
    Teuchos::Array<double> dist_sources;
    CenterDistributor<DIM> distributor( 
	comm, source_centers(), target_centers(), d_radius, dist_sources );

    // Gather the global ids of the source centers that are within a radius of
    // the target centers on this proc.
    Teuchos::Array<GO> dist_source_gids( distributor.getNumImports() );
    Teuchos::ArrayView<const GO> source_gids_view = source_gids();
    distributor.distribute( source_gids_view, dist_source_gids() );

    // Build the source/target pairings.
    SplineInterpolationPairing<DIM> pairings( 
	dist_sources, target_centers(), d_radius );

    // Build the interpolation matrix.
    Teuchos::ArrayRCP<std::size_t> children_per_parent =
	pairings.childrenPerParent();
    std::size_t max_entries_per_row = *std::max_element( 
	children_per_parent.begin(), children_per_parent.end() );
    Teuchos::RCP<Tpetra::CrsMatrix<Scalar,int,GO> > H = 
	Teuchos::rcp( new Tpetra::CrsMatrix<Scalar,int,GO>( 
			  this->b_range_map,
			  max_entries_per_row) );
    Teuchos::ArrayView<const Scalar> target_view;
    Teuchos::Array<GO> indices( max_entries_per_row );
    Teuchos::ArrayView<const Scalar> values;
    Teuchos::ArrayView<const unsigned> pair_gids;
    int nn = 0;
    for ( int i = 0; i < local_num_tgt; ++i )
    {
	// If there is no support for this target center then do not build a
	// local basis.
	if ( 0 < pairings.childCenterIds(i).size() )
	{
	    // Get a view of this target center.
	    target_view = target_centers(i*DIM,DIM);

	    // Build the local interpolation problem. 
	    LocalMLSProblem<Basis,DIM> local_problem(
		target_view, pairings.childCenterIds(i),
		dist_sources, *basis );

	    // Get MLS shape function values for this target point.
	    values = local_problem.shapeFunction();
	    nn = values.size();

	    // Populate the interpolation matrix row.
	    pair_gids = pairings.childCenterIds(i);
	    for ( int j = 0; j < nn; ++j )
	    {
		indices[j] = dist_source_gids[ pair_gids[j] ];
	    }
	    H->insertGlobalValues( target_gids[i], indices(0,nn), values );
	}
    }
    H->fillComplete( this->b_domain_map, this->b_range_map );
    DTK_ENSURE( H->isFillComplete() );
    
    // Wrap the interpolation matrix in a Thyra wrapper.
    Teuchos::RCP<const Thyra::VectorSpaceBase<Scalar> > thyra_range_vector_space =
    	Thyra::createVectorSpace<Scalar>( H->getRangeMap() );
    Teuchos::RCP<const Thyra::VectorSpaceBase<Scalar> > thyra_domain_vector_space =
    	Thyra::createVectorSpace<Scalar>( H->getDomainMap() );
    Teuchos::RCP<Thyra::TpetraLinearOp<Scalar,LO,GO> > thyra_H =
    	Teuchos::rcp( new Thyra::TpetraLinearOp<Scalar,LO,GO>() );
    thyra_H->initialize( thyra_range_vector_space, thyra_domain_vector_space, H );

    // Set the coupling matrix with the base class.
    this->b_coupling_matrix = thyra_H;
    DTK_ENSURE( Teuchos::nonnull(this->b_coupling_matrix) );
}
void MovingLeastSquareReconstructionOperator<Basis,DIM>::setupImpl(
    const Teuchos::RCP<FunctionSpace>& domain_space,
    const Teuchos::RCP<FunctionSpace>& range_space )
{
    DTK_REQUIRE( Teuchos::nonnull(domain_space) );
    DTK_REQUIRE( Teuchos::nonnull(range_space) );

    // Extract the Support maps.
    const Teuchos::RCP<const typename Base::TpetraMap> domain_map
	= this->getDomainMap();
    const Teuchos::RCP<const typename Base::TpetraMap> range_map
	= this->getRangeMap();

    // Get the parallel communicator.
    Teuchos::RCP<const Teuchos::Comm<int> > comm = domain_map->getComm();

    // Determine if we have range and domain data on this process.
    bool nonnull_domain = Teuchos::nonnull( domain_space->entitySet() );
    bool nonnull_range = Teuchos::nonnull( range_space->entitySet() );

    // We will only operate on entities that are locally-owned.
    LocalEntityPredicate local_predicate( comm->getRank() );

    // Extract the source centers from the nodes and their ids.
    EntityIterator domain_iterator;
    if ( nonnull_domain )
    {
	PredicateFunction domain_predicate =
	    PredicateComposition::And(
		domain_space->selectFunction(),	local_predicate.getFunction() );
	domain_iterator =
	    domain_space->entitySet()->entityIterator( d_domain_entity_dim, domain_predicate );
    }
    int local_num_src = domain_iterator.size();
    Teuchos::ArrayRCP<double> source_centers( DIM*local_num_src);
    Teuchos::ArrayRCP<GO> source_support_ids( local_num_src );
    Teuchos::Array<SupportId> source_node_supports;
    EntityIterator domain_begin = domain_iterator.begin();
    EntityIterator domain_end = domain_iterator.end();
    int entity_counter = 0;
    for ( EntityIterator domain_entity = domain_begin;
	  domain_entity != domain_end;
	  ++domain_entity, ++entity_counter )
    {
	domain_space->shapeFunction()->entitySupportIds(
	    *domain_entity, source_node_supports );
	DTK_CHECK( 1 == source_node_supports.size() );
	source_support_ids[entity_counter] = source_node_supports[0];
	domain_space->localMap()->centroid(
	    *domain_entity, source_centers(DIM*entity_counter,DIM) );
    }

    // Extract the target centers and their ids.
    EntityIterator range_iterator;
    if ( nonnull_range )
    {
	PredicateFunction range_predicate =
	    PredicateComposition::And(
		range_space->selectFunction(), local_predicate.getFunction() );
	range_iterator =
	    range_space->entitySet()->entityIterator( d_range_entity_dim, range_predicate );
    } 
    int local_num_tgt = range_iterator.size();
    Teuchos::ArrayRCP<double> target_centers( DIM*local_num_tgt );
    Teuchos::ArrayRCP<GO> target_support_ids( local_num_tgt );
    Teuchos::Array<SupportId> target_node_supports;
    EntityIterator range_begin = range_iterator.begin();
    EntityIterator range_end = range_iterator.end();
    entity_counter = 0;
    for ( EntityIterator range_entity = range_begin;
	  range_entity != range_end;
	  ++range_entity, ++entity_counter )
    {
	range_space->shapeFunction()->entitySupportIds(
	    *range_entity, target_node_supports );
	DTK_CHECK( 1 == target_node_supports.size() );
	target_support_ids[entity_counter] = target_node_supports[0];
	range_space->localMap()->centroid(
	    *range_entity, target_centers(DIM*entity_counter,DIM) );
    }

    // Build the basis.
    Teuchos::RCP<Basis> basis = BP::create( d_radius );

    // Gather the source centers that are within a d_radius of the target
    // centers on this proc.
    Teuchos::Array<double> dist_sources;
    CenterDistributor<DIM> distributor( 
	comm, source_centers(), target_centers(), d_radius, dist_sources );

    // Gather the global ids of the source centers that are within a d_radius of
    // the target centers on this proc.
    Teuchos::Array<GO> dist_source_support_ids( distributor.getNumImports() );
    Teuchos::ArrayView<const GO> source_support_ids_view = source_support_ids();
    distributor.distribute( source_support_ids_view, dist_source_support_ids() );

    // Build the source/target pairings.
    SplineInterpolationPairing<DIM> pairings( 
	dist_sources, target_centers(), d_radius );

    // Build the interpolation matrix.
    Teuchos::ArrayRCP<SupportId> children_per_parent =
	pairings.childrenPerParent();
    SupportId max_entries_per_row = *std::max_element( 
	children_per_parent.begin(), children_per_parent.end() );
    d_coupling_matrix = Teuchos::rcp( new Tpetra::CrsMatrix<Scalar,LO,GO>( 
					  range_map,
					  max_entries_per_row) );
    Teuchos::ArrayView<const double> target_view;
    Teuchos::Array<GO> indices( max_entries_per_row );
    Teuchos::ArrayView<const double> values;
    Teuchos::ArrayView<const unsigned> pair_gids;
    int nn = 0;
    for ( int i = 0; i < local_num_tgt; ++i )
    {
	// If there is no support for this target center then do not build a
	// local basis.
	if ( 0 < pairings.childCenterIds(i).size() )
	{
	    // Get a view of this target center.
	    target_view = target_centers(i*DIM,DIM);

	    // Build the local interpolation problem. 
	    LocalMLSProblem<Basis,DIM> local_problem(
		target_view, pairings.childCenterIds(i),
		dist_sources, *basis );

	    // Get MLS shape function values for this target point.
	    values = local_problem.shapeFunction();
	    nn = values.size();

	    // Populate the interpolation matrix row.
	    pair_gids = pairings.childCenterIds(i);
	    for ( int j = 0; j < nn; ++j )
	    {
		indices[j] = dist_source_support_ids[ pair_gids[j] ];
	    }
	    d_coupling_matrix->insertGlobalValues( 
		target_support_ids[i], indices(0,nn), values );
	}
    }
    d_coupling_matrix->fillComplete( domain_map, range_map );
    DTK_ENSURE( d_coupling_matrix->isFillComplete() );
}
//---------------------------------------------------------------------------//
// Redistribute a set of range entity centroid coordinates with their owner
// ranks to the owning domain process.
void CoarseGlobalSearch::search( const EntityIterator& range_iterator,
				 const Teuchos::RCP<EntityLocalMap>& range_local_map,
				 const Teuchos::ParameterList& parameters,
				 Teuchos::Array<EntityId>& range_entity_ids,
				 Teuchos::Array<int>& range_owner_ranks,
				 Teuchos::Array<double>& range_centroids ) const
{
    // Assemble the local range bounding box.
    Teuchos::Tuple<double,6> range_box;
    assembleBoundingBox( range_iterator, range_box );

    // Find the domain boxes it intersects with.
    Teuchos::Array<int> neighbor_ranks;
    Teuchos::Array<Teuchos::Tuple<double,6> > neighbor_boxes;
    int num_domains = d_domain_boxes.size();
    for ( int n = 0; n < num_domains; ++n )
    {
	if ( boxesIntersect(range_box,d_domain_boxes[n],d_inclusion_tol) )
	{
	    neighbor_ranks.push_back(n);
	    neighbor_boxes.push_back( d_domain_boxes[n] );
	}
    }

    // For each local range entity, find the neighbors we should send it to.
    int num_neighbors = neighbor_boxes.size();
    EntityIterator range_begin = range_iterator.begin();
    EntityIterator range_end = range_iterator.end();
    EntityIterator range_it;
    Teuchos::Array<EntityId> send_ids;
    Teuchos::Array<int> send_ranks;
    Teuchos::Array<double> send_centroids;
    Teuchos::Array<double> centroid(d_space_dim);
    bool found_entity = false;
    for ( range_it = range_begin; range_it != range_end; ++range_it )
    {
	// Get the centroid.
	range_local_map->centroid( *range_it, centroid() );

	// Check the neighbors.
	found_entity = false;
	for ( int n = 0; n < num_neighbors; ++n )
	{
	    // If the centroid is in the box, add it to the send list.
	    if ( pointInBox(centroid(),neighbor_boxes[n],d_inclusion_tol) )
	    {
		found_entity = true;
		send_ids.push_back( range_it->id() );
		send_ranks.push_back( neighbor_ranks[n] );
		for ( int d = 0; d < d_space_dim; ++d )
		{
		    send_centroids.push_back( centroid[d] );
		}
	    }
	}

	// If we are tracking missed range entities, add the entity to the
	// list.
	if ( d_track_missed_range_entities && !found_entity )
	{
	    d_missed_range_entity_ids.push_back( range_it->id() );
	}
    }
    int num_send = send_ranks.size();
    Teuchos::Array<int> range_ranks( num_send, d_comm->getRank() );

    // Create a distributor.
    Tpetra::Distributor distributor(d_comm);
    int num_range_import = distributor.createFromSends( send_ranks() );

    // Redistribute the range entity ids.
    Teuchos::ArrayView<const EntityId> send_ids_view = send_ids();
    range_entity_ids.resize( num_range_import );
    distributor.doPostsAndWaits( send_ids_view, 1, range_entity_ids() );

    // Redistribute the range entity owner ranks.
    Teuchos::ArrayView<const int> range_ranks_view = range_ranks();
    range_owner_ranks.resize( num_range_import );
    distributor.doPostsAndWaits( range_ranks_view, 1, range_owner_ranks() );

    // Redistribute the range entity centroids.
    range_centroids.resize( d_space_dim*num_range_import );
    Teuchos::ArrayView<const double> send_centroids_view = send_centroids();
    distributor.doPostsAndWaits( 
	send_centroids_view, d_space_dim, range_centroids() );
}