ParticleSpatialLayout.h 56.5 KB
Newer Older
gsell's avatar
gsell committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
// -*- C++ -*-
/***************************************************************************
 *
 * The IPPL Framework
 *
 *
 * Visit http://people.web.psi.ch/adelmann/ for more details
 *
 ***************************************************************************/

#ifndef PARTICLE_SPATIAL_LAYOUT_H
#define PARTICLE_SPATIAL_LAYOUT_H

/*
 * ParticleSpatialLayout - particle layout based on spatial decomposition.
 *
 * This is a specialized version of ParticleLayout, which places particles
 * on processors based on their spatial location relative to a fixed grid.
 * In particular, this can maintain particles on processors based on a
 * specified FieldLayout or RegionLayout, so that particles are always on
 * the same node as the node containing the Field region to which they are
 * local.  This may also be used if there is no associated Field at all,
 * in which case a grid is selected based on an even distribution of
 * particles among processors.
 */

// include files
#include "Particle/ParticleLayout.h"
29
#include "Particle/IpplParticleBase.h"
gsell's avatar
gsell committed
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
#include "Region/RegionLayout.h"
#include "Message/Message.h"
#include "FieldLayout/FieldLayoutUser.h"
#include <cstddef>

#include <vector>
#include <iostream>
#include <map>

#include "BoxParticleCachingPolicy.h"

#include "Message/Formatter.h"
#include <mpi.h>

// forward declarations
class UserList;
template <class T> class ParticleAttrib;
template <unsigned Dim, class T> class UniformCartesian;
template <class T, unsigned Dim, class Mesh, class CachingPolicy> class ParticleSpatialLayout;
template <class T, unsigned Dim, class Mesh, class CachingPolicy>
std::ostream& operator<<(std::ostream&, const ParticleSpatialLayout<T,Dim,Mesh,CachingPolicy>&);

// ParticleSpatialLayout class definition.  Template parameters are the type
// and dimension of the ParticlePos object used for the particles.  The
// dimension of the position must match the dimension of the FieldLayout
// object used in this particle layout, if any.
// Optional template parameter for the mesh type
template < class T, unsigned Dim, class Mesh=UniformCartesian<Dim,T>, class CachingPolicy=BoxParticleCachingPolicy<T,Dim,Mesh > >
class ParticleSpatialLayout : public ParticleLayout<T, Dim>,
        public FieldLayoutUser, public CachingPolicy
{
    /*
      Enable cashing of particles. The size is
      given in multiples of the mesh size in each dimension.
     */

public:
    // pair iterator definition ... this layout does not allow for pairlists
    typedef int pair_t;
    typedef pair_t* pair_iterator;
    typedef typename ParticleLayout<T, Dim>::SingleParticlePos_t
    SingleParticlePos_t;
    typedef typename ParticleLayout<T, Dim>::Index_t Index_t;

    // type of attributes this layout should use for position and ID
    typedef ParticleAttrib<SingleParticlePos_t> ParticlePos_t;
    typedef ParticleAttrib<Index_t>             ParticleIndex_t;
    typedef RegionLayout<T,Dim,Mesh>			  RegionLayout_t;

public:
    // constructor: The Field layout to which we match our particle's
    // locations.
    ParticleSpatialLayout(FieldLayout<Dim>&);

    // constructor: this one also takes a Mesh
    ParticleSpatialLayout(FieldLayout<Dim>&, Mesh&);

    // a similar constructor, but this one takes a RegionLayout.
    ParticleSpatialLayout(const RegionLayout<T,Dim,Mesh>&);

    // a default constructor ... in this case, no layout will
    // be assumed by this class.  A layout may be given later via the
    // 'setLayout' method, either as a FieldLayout or as a RegionLayout.
    ParticleSpatialLayout();

    // destructor
    ~ParticleSpatialLayout();

    //
    // spatial decomposition layout information
    //

    // retrieve a reference to the FieldLayout object in use.  This may be used,
    // e.g., to construct a Field with the same layout as the Particles.  Note
    // that if this object was constructed by providing a RegionLayout in the
    // constructor, then this generated FieldLayout will not necessarily match
    // up with the Region (it will be offset by some amount).  But, if this
    // object was either 1) created with a FieldLayout to begin with, or 2)
    // created with no layout, and one was generated internally, then the
    // returned FieldLayout will match and can be used to make new Fields or
    // Particles.
    FieldLayout<Dim>& getFieldLayout()
    {
        return RLayout.getFieldLayout();
    }

    // retrieve a reference to the RegionLayout object in use
    RegionLayout<T,Dim,Mesh>& getLayout()
    {
        return RLayout;
    }
    const RegionLayout<T,Dim,Mesh>& getLayout() const
    {
        return RLayout;
    }

    // get number of particles on a physical node
    int getNodeCount(unsigned i) const
    {
129
        PAssert_LT(i, (unsigned int) Ippl::getNodes());
gsell's avatar
gsell committed
130 131 132 133 134 135
        return NodeCount[i];
    }

    // get flag for empty node domain
    bool getEmptyNode(unsigned i) const
    {
136
        PAssert_LT(i, (unsigned int) Ippl::getNodes());
gsell's avatar
gsell committed
137 138 139 140 141 142 143
        return EmptyNode[i];
    }

    //
    // Particle swapping/update routines
    //

144
    // Update the location and indices of all atoms in the given IpplParticleBase
gsell's avatar
gsell committed
145 146 147
    // object.  This handles swapping particles among processors if
    // needed, and handles create and destroy requests.  When complete,
    // all nodes have correct layout information.
148
    void update(IpplParticleBase< ParticleSpatialLayout<T,Dim,Mesh,CachingPolicy> >& p,
gsell's avatar
gsell committed
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
                const ParticleAttrib<char>* canSwap=0);


    //
    // I/O
    //

    // Print out information for debugging purposes.
    void printDebug(Inform&);

    //
    // virtual functions for FieldLayoutUser's (and other UserList users)
    //

    // Repartition onto a new layout
    virtual void Repartition(UserList *);

    // Tell this object that an object is being deleted
    virtual void notifyUserOfDelete(UserList *);

    // Get the Neighbor Node for a given dimension
    int getNeighborNode(unsigned int d, unsigned int n)
    {
172 173
        PAssert_LT(d, Dim);
        PAssert_LT(n, (unsigned int) Ippl::getNodes());
gsell's avatar
gsell committed
174 175 176 177 178 179

        if (SwapNodeList[d][n])
            return n;
        else
            return -1;
    }
kraus's avatar
kraus committed
180

gsell's avatar
gsell committed
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
    void enableCaching() { caching = true; }
    void disableCaching() { caching = false; }

protected:
    // The RegionLayout which determines where our particles go.
    RegionLayout<T,Dim,Mesh> RLayout;

    // The number of particles located on each physical node.
    size_t *NodeCount;

    // Flag for which nodes have no local domain
    bool* EmptyNode;

    // a list of Message pointers used in swapping particles, and flags
    // for which nodes expect messages in each dimension
    bool* SwapNodeList[Dim];
    Message** SwapMsgList;
    unsigned NeighborNodes[Dim];
    std::vector<size_t>* PutList;

	bool caching;

    // perform common constructor tasks
    void setup();

    // for each dimension, calculate where neighboring Vnodes and physical
    // nodes are located, and create a list of this data.  This need only
    // be updated when the FieldLayout changes.
    void rebuild_neighbor_data();

    /////////////////////////////////////////////////////////////////////
    // Rebuild the RegionLayout entirely, by recalculating our min and max
    // domains, adding a buffer region, and then giving this new Domain to
    // our internal RegionLayout.  When this is done, we must rebuild all
    // our other data structures as well.
    template < class PB >
    void rebuild_layout(size_t haveLocal, PB& PData)
    {
        size_t i;
        unsigned d;			// loop variables

        //~ Inform dbgmsg("SpatialLayout::rebuild_layout", INFORM_ALL_NODES);
        //~ dbgmsg << "rebuild..." << endl;
        SingleParticlePos_t minpos = 0;
        SingleParticlePos_t maxpos = 0;
        int tag  = Ippl::Comm->next_tag(P_SPATIAL_RANGE_TAG, P_LAYOUT_CYCLE);
        int btag = Ippl::Comm->next_tag(P_SPATIAL_RANGE_TAG, P_LAYOUT_CYCLE);

        // if we have local particles, then find the min and max positions
        if (haveLocal > 0)
        {
            minpos = PData.R[0];
            maxpos = PData.R[0];
            for (i=1; i < haveLocal; ++i)
            {
                for (d=0; d < Dim; ++d)
                {
                    if (PData.R[i][d] < minpos[d])
                        minpos[d] = PData.R[i][d];
                    if (PData.R[i][d] > maxpos[d])
                        maxpos[d] = PData.R[i][d];
                }
            }
        }

        // if we're not on node 0, send data to node 0
        if (Ippl::myNode() != 0)
        {
            Message *msg = new Message;
            msg->put(haveLocal);
            if (haveLocal > 0)
            {
                minpos.putMessage(*msg);
                maxpos.putMessage(*msg);
            }
            Ippl::Comm->send(msg, 0, tag);

            // now receive back min and max range as provided by the master node.
            // These will include some buffer region, and will be integral values,
            // so we can make a FieldLayout and use it to initialize the RegionLayout.
            int node = 0;
            msg = Ippl::Comm->receive_block(node, btag);
            minpos.getMessage(*msg);
            maxpos.getMessage(*msg);
            delete msg;

        }
        else  			// on node 0, collect data and compute region
        {
            SingleParticlePos_t tmpminpos;
            SingleParticlePos_t tmpmaxpos;
kraus's avatar
kraus committed
272
            size_t tmphaveLocal = 0;
gsell's avatar
gsell committed
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
            unsigned unreceived = Ippl::getNodes() - 1;

            // collect data from other nodes
            while (unreceived > 0)
            {
                int node = COMM_ANY_NODE;
                Message *msg = Ippl::Comm->receive_block(node, tag);
                msg->get(tmphaveLocal);
                if (tmphaveLocal > 0)
                {
                    tmpminpos.getMessage(*msg);
                    tmpmaxpos.getMessage(*msg);
                    for (i=0; i < Dim; ++i)
                    {
                        if (tmpminpos[i] < minpos[i])
                            minpos[i] = tmpminpos[i];
                        if (tmpmaxpos[i] > maxpos[i])
                            maxpos[i] = tmpmaxpos[i];
                    }
                }
                delete msg;
                unreceived--;
            }

            // adjust min and max to include a buffer region and fall on integral
            // values
            SingleParticlePos_t extrapos = (maxpos - minpos) * ((T)0.125);
            maxpos += extrapos;
            minpos -= extrapos;
            for (i=0; i < Dim; ++i)
            {
                if (minpos[i] >= 0.0)
                    minpos[i] = (int)(minpos[i]);
                else
                    minpos[i] = (int)(minpos[i] - 1);
                maxpos[i] = (int)(maxpos[i] + 1);
            }

            // send these values out to the other nodes
            if (Ippl::getNodes() > 1)
            {
                Message *bmsg = new Message;
                minpos.putMessage(*bmsg);
                maxpos.putMessage(*bmsg);
                Ippl::Comm->broadcast_others(bmsg, btag);
            }
        }

        // determine the size of the new domain, and the number of blocks into
        // which it should be broken
        NDIndex<Dim> range;
        for (i=0; i < Dim; ++i)
            range[i] = Index((int)(minpos[i]), (int)(maxpos[i]));
        int vn = -1;
        if (RLayout.initialized())
            vn = RLayout.size_iv() + RLayout.size_rdv();

        // ask the RegionLayout to change the paritioning to match this size
        // and block count.  This will eventually end up by calling Repartition
        // here, which will lead to rebuilding the neighbor data, etc., so we
        // are done.
        RLayout.changeDomain(range, vn);
    }

    // swap particles to neighboring nodes if they have moved too far
338
    // PB is the type of IpplParticleBase which should have it's layout rebuilt.
gsell's avatar
gsell committed
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
    //mwerks  template<class PB>
    //mwerks  unsigned swap_particles(unsigned, PB&);
    /////////////////////////////////////////////////////////////////////
    // go through all our local particles, and send particles which must
    // be swapped to another node to that node.
    template < class PB >
    size_t swap_particles(size_t LocalNum, PB& PData)
    {

//~ Inform dbgmsg("SpatialLayout::swap_particles", INFORM_ALL_NODES);
        //~ dbgmsg << "swap..." << endl;

        Inform msg("ParticleSpatialLayout ERROR ", INFORM_ALL_NODES);

        unsigned d, i, j;			// loop variables
        size_t ip;
        unsigned N = Ippl::getNodes();
        unsigned myN = Ippl::myNode();

        // iterators used to search local domains
        typename RegionLayout<T,Dim,Mesh>::iterator_iv localV, localEnd = RLayout.end_iv();

        // iterators used to search remote domains
adelmann's avatar
adelmann committed
362
        typename RegionLayout<T,Dim,Mesh>::iterator_dv remoteV; //  remoteEnd = RLayout.end_rdv();
gsell's avatar
gsell committed
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535

        // JCC: This "nudge factor" stuff was added when we were experiencing
        // problems with particles getting lost in between PRegions on
        // neighboring nodes.  This problem has since been resolved by
        // fixing the way in which PRegion boundaries are computed, so I am
        // commenting this out for now.  We can bring it back later if the
        // need arises.

        /*

        // Calculate a 'nudge factor', an amount that can get added to a
        // particle position to determine where it should be located.  The nudge
        // factor equals 1/100th the smallest width of the rnodes in each dimension.
        // When we try to find where a particle is located, we check what vnode
        // contains this particle 'nudge region', a box around the particle's pos
        // of the size of the nudge factor.
        T pNudge[Dim];
        for (d=0; d < Dim; ++d) {
          // initialize to the first rnode's width
          T minval = (*(RLayout.begin_iv())).second->getDomain()[d].length();

          // check the local rnodes
          for (localV = RLayout.begin_iv(); localV != localEnd; ++localV) {
        T checkval = (*localV).second->getDomain()[d].length();
        if (checkval < minval)
          minval = checkval;
          }

          // check the remote rnodes
          for (remoteV = RLayout.begin_rdv(); remoteV != remoteEnd; ++remoteV) {
        T checkval = (*remoteV).second->getDomain()[d].length();
        if (checkval < minval)
          minval = checkval;
          }

          // now rescale the minval, and save it
          pNudge[d] = 0.00001 * minval;
        }

        */

        // An NDRegion object used to store a particle position.
        NDRegion<T,Dim> pLoc;

        // get new message tag for particle exchange with empty domains
        int etag = Ippl::Comm->next_tag(P_SPATIAL_RETURN_TAG,P_LAYOUT_CYCLE);

        if (!getEmptyNode(myN))
        {

            // Particles are swapped in multipple passes, one for each dimension.
            // The tasks completed here for each dimension are the following:
            //   1. For each local Vnode, find the remote Vnodes which exist along
            //      same axis as the current axis (i.e. all Vnodes along the x-axis).
            //   2. From this list, determine which nodes we send messages to.
            //      Steps 1 & 2 have been done already in rebuild_neighbor_data.
            //   3. Go through all the particles, finding those which have moved to
            //      an off-processor vnode, and store index in an array for that node
            //   4. Send off the particles to the nodes (if no particles are
            //      going to a node, send them a message with 0 in it)
            //   5. Delete the send particles from our local list
            //   6. Receive particles sent to us by other nodes (some messages may
            //      say that we're receiving 0 particles from that node).

            // Initialize NDRegion with a position inside the first Vnode.
            // We can skip dim 0, since it will be filled below.
            for (d = 1; d < Dim; ++d)
            {
                T first = (*(RLayout.begin_iv())).second->getDomain()[d].first();
                T last  = (*(RLayout.begin_iv())).second->getDomain()[d].last();
                T mid   = first + 0.5 * (last - first);
                pLoc[d] = PRegion<T>(mid, mid);
            }

            for (d = 0; d < Dim; ++d)
            {

                // get new message tag for particle exchange along this dimension
                int tag = Ippl::Comm->next_tag(P_SPATIAL_TRANSFER_TAG,P_LAYOUT_CYCLE);

                // we only need to do the rest if there are other nodes in this dim
                if (NeighborNodes[d] > 0)
                {
                    // create new messages to send to our neighbors
                    for (i = 0; i < N; i++)
                        if (SwapNodeList[d][i])
                            SwapMsgList[i] = new Message;

                    // Go through the particles and find those moving in the current dir.
                    // When one is found, copy it into outgoing message and delete it.
                    for (ip=0; ip<LocalNum; ++ip)
                    {
                        // get the position of particle ip, and find the closest grid pnt
                        // for just the dimensions 0 ... d
                        for (j = 0; j <= d; j++)
                            pLoc[j] = PRegion<T>(PData.R[ip][j], PData.R[ip][j]);

                        // first check local domains (in this dimension)
                        bool foundit = false;
                        // JCC:	  int nudged = 0;
                        while (!foundit)
                        {
                            for (localV = RLayout.begin_iv();
                                    localV != localEnd && !foundit; ++localV)
                            {
                                foundit= (((*localV).second)->getDomain())[d].touches(pLoc[d]);
                            }

                            // if not found, it might be remote
                            if (!foundit)
                            {
                                // see which Vnode this postion is in
                                typename RegionLayout<T,Dim,Mesh>::touch_range_dv touchingVN =
                                    RLayout.touch_range_rdv(pLoc);

#ifdef IPPL_USE_SINGLE_PRECISION
                                //FIXME: why does FLT_EPSILON not work?
                                float nudge = 1e-5;
                                int nudgeDim = 0;

                                //FIXME: it would be nice to remove the nudge if it has no effect
                                while (nudgeDim <= d && touchingVN.first == touchingVN.second)
                                {

                                    T val = PData.R[ip][nudgeDim];

                                    //ensure we nudge the particle back into LOCAL domain
                                    float lastidx  = RLayout.getDomain()[d].last();
                                    if (val >= lastidx)
                                        val -= nudge;
                                    else
                                        val += nudge;

                                    pLoc[nudgeDim] = PRegion<T>(val, val);
                                    touchingVN = RLayout.touch_range_rdv(pLoc);

                                    nudgeDim++;
                                }
#endif

                                // make sure we have a vnode to send it to
                                if (touchingVN.first == touchingVN.second)
                                {
                                    // JCC:		if (nudged >= Dim) {
                                    ERRORMSG("Local particle " << ip << " with ID=");
                                    ERRORMSG(PData.ID[ip] << " at ");
                                    ERRORMSG(PData.R[ip] << " is outside of global domain ");
                                    ERRORMSG(RLayout.getDomain() << endl);
                                    ERRORMSG("This occurred when searching for point " << pLoc);
                                    ERRORMSG(" in RegionLayout = " << RLayout << endl);
                                    Ippl::abort();

                                    // JCC:
                                    /*
                                    }
                                            else {
                                      DEBUGMSG("Local particle " << ip << " with ID=");
                                      DEBUGMSG(PData.ID[ip] << " at ");
                                      DEBUGMSG(PData.R[ip] << " might be outside of global domain ");
                                      DEBUGMSG(RLayout.getDomain() << endl);
                                      DEBUGMSG("Attempting to nudge it to the right to see if it ");
                                      DEBUGMSG("is in a crack, along dim = " << nudged << endl);
                                      DEBUGMSG("Previously checked  pos = " << pLoc << endl);
                                      T oldval = PData.R[ip][nudged];
                                      pLoc[nudged] = PRegion<T>(oldval, oldval + pNudge[nudged]);
                                      nudged++;
                                      DEBUGMSG("Will check with new pos = " << pLoc << endl);
                                    }
                                    */

                                }
                                else
                                {
536

537 538
				    // the node has been found - add index to put list
				    unsigned node = (*(touchingVN.first)).second->getNode();
539
				    PAssert_EQ(SwapNodeList[d][node], true);
540 541 542 543
				    PutList[node].push_back(ip);

				    // .. and then add to DestroyList
				    PData.destroy(1, ip);
544

545 546
				    // indicate we found it to quit this check
				    foundit = true;
gsell's avatar
gsell committed
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
                                }
                            }
                        }
                    }

                    // send the particles to their destination nodes
                    for (i = 0; i < N; i++)
                    {
                        if (SwapNodeList[d][i])
                        {
                            // put data for particles on this put list into message
                            PData.putMessage( *(SwapMsgList[i]), PutList[i] );

                            // add a final 'zero' number of particles to indicate the end
                            PData.putMessage(*(SwapMsgList[i]), (size_t) 0, (size_t) 0);

                            // send the message
                            // Inform dbgmsg("SpatialLayout", INFORM_ALL_NODES);
                            //dbgmsg << "Swapping "<<PutList[i].size() << " particles to node ";
                            //dbgmsg << i<<" with tag " << tag << " (" << 'x' + d << ")" << endl;
                            //dbgmsg << "  ... msg = " << *(SwapMsgList[i]) << endl;
                            int node = i;
                            Ippl::Comm->send(SwapMsgList[i], node, tag);

                            // clear the list
                            PutList[i].erase(PutList[i].begin(), PutList[i].end());
                        }
                    }

                    LocalNum -= PData.getDestroyNum();  // update local num
                    ADDIPPLSTAT(incParticlesSwapped, PData.getDestroyNum());
                    PData.performDestroy();

                    // receive particles from neighbor nodes, and add them to our list
                    unsigned sendnum = NeighborNodes[d];
                    while (sendnum-- > 0)
                    {
                        int node = Communicate::COMM_ANY_NODE;
                        Message *recmsg = Ippl::Comm->receive_block(node, tag);
                        size_t recvd;
                        while ((recvd = PData.getMessage(*recmsg)) > 0)
                            LocalNum += recvd;
                        delete recmsg;
                    }
                }  // end if (NeighborNodes[d] > 0)

                if (d == 0)
                {
                    // receive messages from any empty nodes
                    for (i = 0; i < N; ++i)
                    {
                        if (getEmptyNode(i))
                        {
                            int node = i;
                            Message *recmsg = Ippl::Comm->receive_block(node, etag);
                            size_t recvd;
                            while ((recvd = PData.getMessage(*recmsg)) > 0)
                                LocalNum += recvd;
                            delete recmsg;
                        }
                    }
                }

            }  // end for (d=0; d<Dim; ++d)

        }
        else   // empty node sends, but does not receive
        {
            msg << "case getEmptyNode(myN) " << endl;
            // create new messages to send to our neighbors along dim 0
            for (i = 0; i < N; i++)
                if (SwapNodeList[0][i])
                    SwapMsgList[i] = new Message;

            // Go through the particles and find those moving to other nodes.
            // When one is found, copy it into outgoing message and delete it.
            for (ip=0; ip<LocalNum; ++ip)
            {
                // get the position of particle ip, and find the closest grid pnt
                for (j = 0; j < Dim; j++)
                    pLoc[j] = PRegion<T>(PData.R[ip][j], PData.R[ip][j]);

                // see which remote Vnode this postion is in
                typename RegionLayout<T,Dim,Mesh>::touch_range_dv touchingVN =
                    RLayout.touch_range_rdv(pLoc);

                // make sure we have a vnode to send it to
                if (touchingVN.first == touchingVN.second)
                {
                    ERRORMSG("Local particle " << ip << " with ID=");
                    ERRORMSG(PData.ID[ip] << " at ");
                    ERRORMSG(PData.R[ip] << " is outside of global domain ");
                    ERRORMSG(RLayout.getDomain() << endl);
                    ERRORMSG("This occurred when searching for point " << pLoc);
                    ERRORMSG(" in RegionLayout = " << RLayout << endl);
                    Ippl::abort();
                }
                else
                {
646 647
		    // the node has been found - add index to put list
		    unsigned node = (*(touchingVN.first)).second->getNode();
648
		    PAssert_EQ(SwapNodeList[0][node], true);
649
		    PutList[node].push_back(ip);
gsell's avatar
gsell committed
650

651 652
		    // .. and then add to DestroyList
		    PData.destroy(1, ip);
gsell's avatar
gsell committed
653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
                }
            }

            // send the particles to their destination nodes
            for (i = 0; i < N; i++)
            {
                if (SwapNodeList[0][i])
                {
                    // put data for particles on this put list into message
                    PData.putMessage( *(SwapMsgList[i]), PutList[i] );

                    // add a final 'zero' number of particles to indicate the end
                    PData.putMessage(*(SwapMsgList[i]), (size_t) 0, (size_t) 0);

                    // send the message
                    int node = i;
                    Ippl::Comm->send(SwapMsgList[i], node, etag);

                    // clear the list
                    PutList[i].erase(PutList[i].begin(), PutList[i].end());
                }
            }

            LocalNum -= PData.getDestroyNum();  // update local num
            ADDIPPLSTAT(incParticlesSwapped, PData.getDestroyNum());
            PData.performDestroy();

        }

        // return how many particles we have now
        return LocalNum;
    }


/*
 * Simplified version for testing purposes.
kraus's avatar
kraus committed
689
 */
gsell's avatar
gsell committed
690 691 692 693 694

   template < class PB >
    size_t short_swap_particles(size_t LocalNum, PB& PData)
    {
    	static int sent = 0, old_sent=0;
kraus's avatar
kraus committed
695

gsell's avatar
gsell committed
696 697 698 699 700 701 702 703 704

        unsigned d, i, j;			// loop variables
        size_t ip;
        unsigned N = Ippl::getNodes();

        // iterators used to search local domains
        typename RegionLayout<T,Dim,Mesh>::iterator_iv localV, localEnd = RLayout.end_iv();

        // iterators used to search remote domains
adelmann's avatar
adelmann committed
705
        typename RegionLayout<T,Dim,Mesh>::iterator_dv remoteV; // remoteEnd = RLayout.end_rdv();
gsell's avatar
gsell committed
706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759


        // An NDRegion object used to store a particle position.
        NDRegion<T,Dim> pLoc;

            // Initialize NDRegion with a position inside the first Vnode.
            // We can skip dim 0, since it will be filled below.
            for (d = 1; d < Dim; ++d)
            {
                T first = (*(RLayout.begin_iv())).second->getDomain()[d].first();
                T last  = (*(RLayout.begin_iv())).second->getDomain()[d].last();
                T mid   = first + 0.5 * (last - first);
                pLoc[d] = PRegion<T>(mid, mid);
            }

            for (d = 0; d < Dim; ++d)
            {

                // get new message tag for particle exchange along this dimension
                int tag = Ippl::Comm->next_tag(P_SPATIAL_TRANSFER_TAG,P_LAYOUT_CYCLE);

                // we only need to do the rest if there are other nodes in this dim
                if (NeighborNodes[d] > 0)
                {
                    // create new messages to send to our neighbors
                    for (i = 0; i < N; i++)
                        if (SwapNodeList[d][i])
                            SwapMsgList[i] = new Message;

                    // Go through the particles and find those moving in the current dir.
                    // When one is found, copy it into outgoing message and delete it.
                    for (ip=0; ip<LocalNum; ++ip)
                    {
                        // get the position of particle ip, and find the closest grid pnt
                        // for just the dimensions 0 ... d
                        for (j = 0; j <= d; j++)
                            pLoc[j] = PRegion<T>(PData.R[ip][j], PData.R[ip][j]);

                        // first check local domains (in this dimension)
                        bool foundit = false;

                            for (localV = RLayout.begin_iv();
                                    localV != localEnd && !foundit; ++localV)
                            {
                                foundit= (((*localV).second)->getDomain())[d].touches(pLoc[d]);
                            }

                            // if not found, it might be remote
                            if (!foundit)
                            {
                                // see which Vnode this postion is in
                                typename RegionLayout<T,Dim,Mesh>::touch_range_dv touchingVN =
                                    RLayout.touch_range_rdv(pLoc);

kraus's avatar
kraus committed
760

gsell's avatar
gsell committed
761 762
                                    // the node has been found - add index to put list
                                    unsigned node = (*(touchingVN.first)).second->getNode();
763
                                    PAssert_EQ(SwapNodeList[d][node], true);
gsell's avatar
gsell committed
764 765 766 767 768 769
                                    PutList[node].push_back(ip);

                                    // .. and then add to DestroyList
                                    PData.destroy(1, ip);

                                    // indicate we found it to quit this check
kraus's avatar
kraus committed
770 771
                                    foundit = true;
                                    sent++;
gsell's avatar
gsell committed
772 773 774 775 776 777 778 779 780 781 782
                            }
                    }

					std::vector<MPI_Request> requests;
					std::vector<MsgBuffer*> buffers;

	                // send the particles to their destination nodes
                    for (i = 0; i < N; i++)
                    {
                        if (SwapNodeList[d][i])
                        {
kraus's avatar
kraus committed
783

gsell's avatar
gsell committed
784 785 786 787 788
                            // put data for particles on this put list into message
                            PData.putMessage( *(SwapMsgList[i]), PutList[i] );

                            // add a final 'zero' number of particles to indicate the end
                            PData.putMessage(*(SwapMsgList[i]), (size_t) 0, (size_t) 0);
kraus's avatar
kraus committed
789

gsell's avatar
gsell committed
790 791 792 793 794
                            int node = i;
                            Ippl::Comm->send(SwapMsgList[i], node, tag);

                            // clear the list
                            PutList[i].erase(PutList[i].begin(), PutList[i].end());
kraus's avatar
kraus committed
795 796 797



gsell's avatar
gsell committed
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815
                        }
                    }

                    LocalNum -= PData.getDestroyNum();  // update local num
                    ADDIPPLSTAT(incParticlesSwapped, PData.getDestroyNum());
                    PData.performDestroy();

                    // receive particles from neighbor nodes, and add them to our list
                    unsigned sendnum = NeighborNodes[d];
                    while (sendnum-- > 0)
                    {
                        int node = Communicate::COMM_ANY_NODE;
                        Message *recmsg = Ippl::Comm->receive_block(node, tag);
                        size_t recvd;
                        while ((recvd = PData.getMessage(*recmsg)) > 0)
                            LocalNum += recvd;
                        delete recmsg;
                    }
kraus's avatar
kraus committed
816

gsell's avatar
gsell committed
817
                }  // end if (NeighborNodes[d] > 0)
kraus's avatar
kraus committed
818

gsell's avatar
gsell committed
819 820 821 822 823 824 825 826 827 828 829 830 831
            }  // end for (d=0; d<Dim; ++d)

		//std::cout << "node " << Ippl::myNode() << " sent particles " << sent - old_sent << std::endl;
		old_sent = sent;

        // return how many particles we have now
        return LocalNum;
    }





832
    // PB is the type of IpplParticleBase which should have it's layout rebuilt.
gsell's avatar
gsell committed
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
    //mwerks  template<class PB>
    //mwerks  unsigned swap_particles(unsigned, PB&, const ParticleAttrib<char>&);
    /////////////////////////////////////////////////////////////////////
    // go through all our local particles, and send particles which must
    // be swapped to another node to that node.
    template < class PB >
    size_t swap_particles(size_t LocalNum, PB& PData,
                          const ParticleAttrib<char>& canSwap)
    {

        unsigned d, i, j;			// loop variables
        size_t ip;
        unsigned N = Ippl::getNodes();
        unsigned myN = Ippl::myNode();

        // iterators used to search local domains
        typename RegionLayout<T,Dim,Mesh>::iterator_iv localV, localEnd = RLayout.end_iv();

        // iterators used to search remote domains
adelmann's avatar
adelmann committed
852
        typename RegionLayout<T,Dim,Mesh>::iterator_dv remoteV; // remoteEnd = RLayout.end_rdv();
gsell's avatar
gsell committed
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 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 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 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003

        // JCC: This "nudge factor" stuff was added when we were experiencing
        // problems with particles getting lost in between PRegions on
        // neighboring nodes.  This problem has since been resolved by
        // fixing the way in which PRegion boundaries are computed, so I am
        // commenting this out for now.  We can bring it back later if the
        // need arises.

        /*

        // Calculate a 'nudge factor', an amount that can get added to a
        // particle position to determine where it should be located.  The nudge
        // factor equals 1/100th the smallest width of the rnodes in each dimension.
        // When we try to find where a particle is located, we check what vnode
        // contains this particle 'nudge region', a box around the particle's pos
        // of the size of the nudge factor.
        T pNudge[Dim];
        for (d=0; d < Dim; ++d) {
          // initialize to the first rnode's width
          T minval = (*(RLayout.begin_iv())).second->getDomain()[d].length();

          // check the local rnodes
          for (localV = RLayout.begin_iv(); localV != localEnd; ++localV) {
        T checkval = (*localV).second->getDomain()[d].length();
        if (checkval < minval)
          minval = checkval;
          }

          // check the remote rnodes
          for (remoteV = RLayout.begin_rdv(); remoteV != remoteEnd; ++remoteV) {
        T checkval = (*remoteV).second->getDomain()[d].length();
        if (checkval < minval)
          minval = checkval;
          }

          // now rescale the minval, and save it
          pNudge[d] = 0.00001 * minval;
        }

        */

        // An NDRegion object used to store a particle position.
        NDRegion<T,Dim> pLoc;

        // get new message tag for particle exchange with empty domains
        int etag = Ippl::Comm->next_tag(P_SPATIAL_RETURN_TAG,P_LAYOUT_CYCLE);

        if (!getEmptyNode(myN))
        {

            // Particles are swapped in multipple passes, one for each dimension.
            // The tasks completed here for each dimension are the following:
            //   1. For each local Vnode, find the remote Vnodes which exist along
            //      same axis as the current axis (i.e. all Vnodes along the x-axis).
            //   2. From this list, determine which nodes we send messages to.
            //      Steps 1 & 2 have been done already in rebuild_neighbor_data.
            //   3. Go through all the particles, finding those which have moved to
            //      an off-processor vnode, and store index in an array for that node
            //   4. Send off the particles to the nodes (if no particles are
            //      going to a node, send them a message with 0 in it)
            //   5. Delete the send particles from our local list
            //   6. Receive particles sent to us by other nodes (some messages may
            //      say that we're receiving 0 particles from that node).

            // Initialize NDRegion with a position inside the first Vnode.
            // We can skip dim 0, since it will be filled below.
            for (d = 1; d < Dim; ++d)
            {
                T first = (*(RLayout.begin_iv())).second->getDomain()[d].first();
                T last  = (*(RLayout.begin_iv())).second->getDomain()[d].last();
                T mid   = first + 0.5 * (last - first);
                pLoc[d] = PRegion<T>(mid, mid);
            }

            for (d = 0; d < Dim; ++d)
            {

                // get new message tag for particle exchange along this dimension
                int tag = Ippl::Comm->next_tag(P_SPATIAL_TRANSFER_TAG,P_LAYOUT_CYCLE);

                // we only need to do the rest if there are other nodes in this dim
                if (NeighborNodes[d] > 0)
                {
                    // create new messages to send to our neighbors
                    for (i = 0; i < N; i++)
                        if (SwapNodeList[d][i])
                            SwapMsgList[i] = new Message;

                    // Go through the particles and find those moving in the current dir.
                    // When one is found, copy it into outgoing message and delete it.
                    for (ip=0; ip<LocalNum; ++ip)
                    {
                        if (!bool(canSwap[ip])) continue;  // skip if can't swap
                        // get the position of particle ip, and find the closest grid pnt
                        // for just the dimensions 0 ... d
                        for (j = 0; j <= d; j++)
                            pLoc[j] = PRegion<T>(PData.R[ip][j], PData.R[ip][j]);

                        // first check local domains (in this dimension)
                        bool foundit = false;
                        // JCC:	  int nudged = 0;
                        while (!foundit)
                        {
                            for (localV = RLayout.begin_iv();
                                    localV != localEnd && !foundit; ++localV)
                            {
                                foundit= (((*localV).second)->getDomain())[d].touches(pLoc[d]);
                            }

                            // if not found, it might be remote
                            if (!foundit)
                            {
                                // see which Vnode this postion is in
                                typename RegionLayout<T,Dim,Mesh>::touch_range_dv touchingVN =
                                    RLayout.touch_range_rdv(pLoc);

                                // make sure we have a vnode to send it to
                                if (touchingVN.first == touchingVN.second)
                                {
                                    // JCC:		if (nudged >= Dim) {
                                    ERRORMSG("Local particle " << ip << " with ID=");
                                    ERRORMSG(PData.ID[ip] << " at ");
                                    ERRORMSG(PData.R[ip] << " is outside of global domain ");
                                    ERRORMSG(RLayout.getDomain() << endl);
                                    ERRORMSG("This occurred when searching for point " << pLoc);
                                    ERRORMSG(" in RegionLayout = " << RLayout << endl);
                                    Ippl::abort();

                                    // JCC:
                                    /*
                                    }
                                            else {
                                      DEBUGMSG("Local particle " << ip << " with ID=");
                                      DEBUGMSG(PData.ID[ip] << " at ");
                                      DEBUGMSG(PData.R[ip] << " might be outside of global domain ");
                                      DEBUGMSG(RLayout.getDomain() << endl);
                                      DEBUGMSG("Attempting to nudge it to the right to see if it ");
                                      DEBUGMSG("is in a crack, along dim = " << nudged << endl);
                                      DEBUGMSG("Previously checked  pos = " << pLoc << endl);
                                      T oldval = PData.R[ip][nudged];
                                      pLoc[nudged] = PRegion<T>(oldval, oldval + pNudge[nudged]);
                                      nudged++;
                                      DEBUGMSG("Will check with new pos = " << pLoc << endl);
                                    }
                                    */

                                }
                                else
                                {
                                    // the node has been found - add index to put list
                                    unsigned node = (*(touchingVN.first)).second->getNode();
1004
                                    PAssert_EQ(SwapNodeList[d][node], true);
gsell's avatar
gsell committed
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
                                    PutList[node].push_back(ip);

                                    // .. and then add to DestroyList
                                    PData.destroy(1, ip);

                                    // indicate we found it to quit this check
                                    foundit = true;
                                }
                            }
                        }
                    }

                    // send the particles to their destination nodes
                    for (i = 0; i < N; i++)
                    {
                        if (SwapNodeList[d][i])
                        {
                            // put data for particles on this put list into message
                            PData.putMessage( *(SwapMsgList[i]), PutList[i] );

                            // add a final 'zero' number of particles to indicate the end
                            PData.putMessage(*(SwapMsgList[i]), (size_t) 0, (size_t) 0);

                            // send the message
                            //Inform dbgmsg("SpatialLayout", INFORM_ALL_NODES);
                            //dbgmsg << "Swapping "<<PutList[i].size() << " particles to node ";
                            //dbgmsg << i<<" with tag " << tag << " (" << 'x' + d << ")" << endl;
                            //dbgmsg << "  ... msg = " << *(SwapMsgList[i]) << endl;
                            int node = i;
                            Ippl::Comm->send(SwapMsgList[i], node, tag);

                            // clear the list
                            PutList[i].erase(PutList[i].begin(), PutList[i].end());
                        }
                    }

                    LocalNum -= PData.getDestroyNum();  // update local num
                    ADDIPPLSTAT(incParticlesSwapped, PData.getDestroyNum());
                    PData.performDestroy();

                    // receive particles from neighbor nodes, and add them to our list
                    unsigned sendnum = NeighborNodes[d];
                    while (sendnum-- > 0)
                    {
                        int node = Communicate::COMM_ANY_NODE;
                        Message *recmsg = Ippl::Comm->receive_block(node, tag);
                        size_t recvd;
                        while ((recvd = PData.getMessage(*recmsg)) > 0)
                            LocalNum += recvd;
                        delete recmsg;
                    }
                }  // end if (NeighborNodes[d] > 0)

                if (d == 0)
                {
                    // receive messages from any empty nodes
                    for (i = 0; i < N; ++i)
                    {
                        if (getEmptyNode(i))
                        {
                            int node = i;
                            Message *recmsg = Ippl::Comm->receive_block(node, etag);
                            size_t recvd;
                            while ((recvd = PData.getMessage(*recmsg)) > 0)
                                LocalNum += recvd;
                            delete recmsg;
                        }
                    }
                }

            }  // end for (d=0; d<Dim; ++d)

        }
        else   // empty node sends, but does not receive
        {
            // create new messages to send to our neighbors along dim 0
            for (i = 0; i < N; i++)
                if (SwapNodeList[0][i])
                    SwapMsgList[i] = new Message;

            // Go through the particles and find those moving to other nodes.
            // When one is found, copy it into outgoing message and delete it.
            for (ip=0; ip<LocalNum; ++ip)
            {
                if (!bool(canSwap[ip])) continue;  // skip if can't swap
                // get the position of particle ip, and find the closest grid pnt
                for (j = 0; j < Dim; j++)
                    pLoc[j] = PRegion<T>(PData.R[ip][j], PData.R[ip][j]);

                // see which remote Vnode this postion is in
                typename RegionLayout<T,Dim,Mesh>::touch_range_dv touchingVN =
                    RLayout.touch_range_rdv(pLoc);

                // make sure we have a vnode to send it to
                if (touchingVN.first == touchingVN.second)
                {
                    ERRORMSG("Local particle " << ip << " with ID=");
                    ERRORMSG(PData.ID[ip] << " at ");
                    ERRORMSG(PData.R[ip] << " is outside of global domain ");
                    ERRORMSG(RLayout.getDomain() << endl);
                    ERRORMSG("This occurred when searching for point " << pLoc);
                    ERRORMSG(" in RegionLayout = " << RLayout << endl);
                    Ippl::abort();
                }
                else
                {
                    // the node has been found - add index to put list
                    unsigned node = (*(touchingVN.first)).second->getNode();
1113
                    PAssert_EQ(SwapNodeList[0][node], true);
gsell's avatar
gsell committed
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
                    PutList[node].push_back(ip);

                    // .. and then add to DestroyList
                    PData.destroy(1, ip);
                }
            }

            // send the particles to their destination nodes
            for (i = 0; i < N; i++)
            {
                if (SwapNodeList[0][i])
                {
                    // put data for particles on this put list into message
                    PData.putMessage( *(SwapMsgList[i]), PutList[i] );

                    // add a final 'zero' number of particles to indicate the end
                    PData.putMessage(*(SwapMsgList[i]), (size_t) 0, (size_t) 0);

                    // send the message
                    int node = i;
                    Ippl::Comm->send(SwapMsgList[i], node, etag);

                    // clear the list
                    PutList[i].erase(PutList[i].begin(), PutList[i].end());
                }
            }

            LocalNum -= PData.getDestroyNum();  // update local num
            ADDIPPLSTAT(incParticlesSwapped, PData.getDestroyNum());
            PData.performDestroy();

        }

        // return how many particles we have now
        return LocalNum;
    }




/*
 * Newer (cleaner) version of swap particles that uses less bandwidth
 * and drastically lowers message counts for real cases.
kraus's avatar
kraus committed
1157
 */
gsell's avatar
gsell committed
1158 1159 1160 1161 1162
    template < class PB >
    size_t new_swap_particles(size_t LocalNum, PB& PData)
    {
        Ippl::Comm->barrier();
        static int sent = 0;
kraus's avatar
kraus committed
1163

gsell's avatar
gsell committed
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
        unsigned N = Ippl::getNodes();
        unsigned myN = Ippl::myNode();

        typename RegionLayout<T,Dim,Mesh>::iterator_iv localV, localEnd = RLayout.end_iv();
        typename RegionLayout<T,Dim,Mesh>::iterator_dv remoteV;

        int *msgsend = new int[N];
        std::fill(msgsend, msgsend+N, 0);
        int *msgrecv = new int[N];
        std::fill(msgrecv, msgrecv+N, 0);

        NDRegion<T,Dim> pLoc;

        std::multimap<unsigned, unsigned> p2n; //<node ID, particle ID>

kraus's avatar
kraus committed
1179
        int minParticlesPerNode = PData.getMinimumNumberOfParticlesPerCore();
adelmann's avatar
adelmann committed
1180
        int particlesLeft = LocalNum;
gsell's avatar
gsell committed
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
        for (unsigned int ip=0; ip<LocalNum; ++ip)
        {
            for (unsigned int j = 0; j < Dim; j++)
                pLoc[j] = PRegion<T>(PData.R[ip][j], PData.R[ip][j]);

            unsigned destination = myN;
            bool found = false;
            for (localV = RLayout.begin_iv(); localV != localEnd && !found; ++localV)
            {
                if ((((*localV).second)->getDomain()).touches(pLoc))
                    found = true; // particle is local and doesn't need to be sent anywhere
            }

            if (found)
                continue;

adelmann's avatar
adelmann committed
1197 1198
            if (particlesLeft <= minParticlesPerNode)
	        break; //leave atleast minimum number of particles per core
1199

gsell's avatar
gsell committed
1200 1201
            typename RegionLayout<T,Dim,Mesh>::touch_range_dv touchingVN = RLayout.touch_range_rdv(pLoc);

1202 1203
            //external location
            PInsist(touchingVN.first != touchingVN.second, "could not find node responsible for particle;\nmesh does not seem correctly adapted to particle distribution");
gsell's avatar
gsell committed
1204 1205 1206 1207 1208 1209
            destination = (*(touchingVN.first)).second->getNode();

            msgsend[destination] = 1;

            p2n.insert(std::pair<unsigned, unsigned>(destination, ip));
            sent++;
1210
	    particlesLeft--;
gsell's avatar
gsell committed
1211 1212 1213
        }

        //reduce message count so every node knows how many messages to receive
1214
        MPI_Allreduce(msgsend, msgrecv, N, MPI_INT, MPI_SUM, Ippl::getComm());
gsell's avatar
gsell committed
1215 1216 1217 1218 1219 1220

        int tag = Ippl::Comm->next_tag(P_SPATIAL_TRANSFER_TAG,P_LAYOUT_CYCLE);

        typename std::multimap<unsigned, unsigned>::iterator i = p2n.begin();

        Format *format = PData.getFormat();
kraus's avatar
kraus committed
1221 1222


gsell's avatar
gsell committed
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
        std::vector<MPI_Request> requests;
        std::vector<MsgBuffer*> buffers;

        while (i!=p2n.end())
        {
            unsigned cur_destination = i->first;

            MsgBuffer *msgbuf = new MsgBuffer(format, p2n.count(i->first));

            for (; i!=p2n.end() && i->first == cur_destination; ++i)
            {
                Message msg;
                PData.putMessage(msg, i->second);
                PData.destroy(1, i->second);
                msgbuf->add(&msg);
            }
kraus's avatar
kraus committed
1239

gsell's avatar
gsell committed
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278
            MPI_Request request = Ippl::Comm->raw_isend( msgbuf->getBuffer(), msgbuf->getSize(), cur_destination, tag);

			//remember request and buffer so we can delete them later
            requests.push_back(request);
            buffers.push_back(msgbuf);
        }

        LocalNum -= PData.getDestroyNum();  // update local num
        PData.performDestroy();

		//receive new particles
        for (int k = 0; k<msgrecv[myN]; ++k)
        {
            int node = Communicate::COMM_ANY_NODE;
            char *buffer = 0;
            int bufsize = Ippl::Comm->raw_probe_receive(buffer, node, tag);
            MsgBuffer recvbuf(format, buffer, bufsize);

            Message *msg = recvbuf.get();
            while (msg != 0)
            {
                LocalNum += PData.getSingleMessage(*msg);
                delete msg;
                msg = recvbuf.get();
            }


        }

		//wait for communication to finish and clean up buffers
        MPI_Waitall(requests.size(), &(requests[0]), MPI_STATUSES_IGNORE);
        for (unsigned int j = 0; j<buffers.size(); ++j)
        {
            delete buffers[j];
        }

        delete[] msgsend;
        delete[] msgrecv;
        delete format;
kraus's avatar
kraus committed
1279

gsell's avatar
gsell committed
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
        //std::cout << "node " << myN << " sent particles " << sent - old_sent << std::endl;

        return LocalNum;
    }

   template < class PB >
    size_t new_swap_particles(size_t LocalNum, PB& PData,
                      const ParticleAttrib<char>& canSwap)
    {
        Ippl::Comm->barrier();
        static int sent = 0;
kraus's avatar
kraus committed
1291

gsell's avatar
gsell committed
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306
        unsigned N = Ippl::getNodes();
        unsigned myN = Ippl::myNode();

        typename RegionLayout<T,Dim,Mesh>::iterator_iv localV, localEnd = RLayout.end_iv();
        typename RegionLayout<T,Dim,Mesh>::iterator_dv remoteV;

        int *msgsend = new int[N];
        std::fill(msgsend, msgsend+N, 0);
        int *msgrecv = new int[N];
        std::fill(msgrecv, msgrecv+N, 0);

        NDRegion<T,Dim> pLoc;

        std::multimap<unsigned, unsigned> p2n; //<node ID, particle ID>

kraus's avatar
kraus committed
1307
        int minParticlesPerNode = PData.getMinimumNumberOfParticlesPerCore();
1308
	int particlesLeft = LocalNum;
gsell's avatar
gsell committed
1309 1310 1311 1312
        for (unsigned int ip=0; ip<LocalNum; ++ip)
        {
            if (!bool(canSwap[ip]))//skip if it can't be swapped
                continue;
kraus's avatar
kraus committed
1313

gsell's avatar
gsell committed
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
            for (unsigned int j = 0; j < Dim; j++)
                pLoc[j] = PRegion<T>(PData.R[ip][j], PData.R[ip][j]);

            unsigned destination = myN;
            bool found = false;
            for (localV = RLayout.begin_iv(); localV != localEnd && !found; ++localV)
            {
                if ((((*localV).second)->getDomain()).touches(pLoc))
                    found = true; // particle is local and doesn't need to be sent anywhere
            }

            if (found)
                continue;

1328
	    if (particlesLeft <= minParticlesPerNode)
adelmann's avatar
adelmann committed
1329
	        continue; //leave atleast minimum number of particles per core
1330

gsell's avatar
gsell committed
1331 1332 1333
            typename RegionLayout<T,Dim,Mesh>::touch_range_dv touchingVN = RLayout.touch_range_rdv(pLoc);

			//external location
1334
            PInsist(touchingVN.first != touchingVN.second, "could not find node responsible for particle;\nmesh does not seem correctly adapted to particle distribution");
gsell's avatar
gsell committed
1335 1336 1337 1338 1339 1340
            destination = (*(touchingVN.first)).second->getNode();

            msgsend[destination] = 1;

            p2n.insert(std::pair<unsigned, unsigned>(destination, ip));
            sent++;
1341
	    particlesLeft--;
gsell's avatar
gsell committed
1342 1343 1344
        }

        //reduce message count so every node knows how many messages to receive
1345
        MPI_Allreduce(msgsend, msgrecv, N, MPI_INT, MPI_SUM, Ippl::getComm());
gsell's avatar
gsell committed
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402

        int tag = Ippl::Comm->next_tag(P_SPATIAL_TRANSFER_TAG,P_LAYOUT_CYCLE);

        typename std::multimap<unsigned, unsigned>::iterator i = p2n.begin();

        Format *format = PData.getFormat();

        std::vector<MPI_Request> requests;
        std::vector<MsgBuffer*> buffers;

        while (i!=p2n.end())
        {
            unsigned cur_destination = i->first;

            MsgBuffer *msgbuf = new MsgBuffer(format, p2n.count(i->first));

            for (; i!=p2n.end() && i->first == cur_destination; ++i)
            {
                Message msg;
                PData.putMessage(msg, i->second);
                PData.destroy(1, i->second);
                msgbuf->add(&msg);
            }

            MPI_Request request = Ippl::Comm->raw_isend( msgbuf->getBuffer(), msgbuf->getSize(), cur_destination, tag);

			//remember request and buffer so we can delete them later
            requests.push_back(request);
            buffers.push_back(msgbuf);
        }

        LocalNum -= PData.getDestroyNum();  // update local num
        PData.performDestroy();

		//receive new particles
        for (int k = 0; k<msgrecv[myN]; ++k)
        {
            int node = Communicate::COMM_ANY_NODE;
            char *buffer = 0;
            int bufsize = Ippl::Comm->raw_probe_receive(buffer, node, tag);
            MsgBuffer recvbuf(format, buffer, bufsize);

            Message *msg = recvbuf.get();
            while (msg != 0)
            {
                LocalNum += PData.getSingleMessage(*msg);
                delete msg;
                msg = recvbuf.get();
            }
        }

		//wait for communication to finish and clean up buffers
        MPI_Waitall(requests.size(), &(requests[0]), 0);
        for (unsigned int j = 0; j<buffers.size(); ++j)
        {
            delete buffers[j];
        }
kraus's avatar
kraus committed
1403

gsell's avatar
gsell committed
1404 1405 1406 1407
        delete[] msgsend;
        delete[] msgrecv;
        delete format;
        //std::cout << "node " << myN << " sent particles " << sent - old_sent << std::endl;
kraus's avatar
kraus committed
1408

gsell's avatar
gsell committed
1409 1410 1411 1412 1413
        return LocalNum;
    }

};

1414
#include "Particle/ParticleSpatialLayout.hpp"
gsell's avatar
gsell committed
1415 1416 1417 1418 1419 1420 1421

#endif // PARTICLE_SPATIAL_LAYOUT_H

/***************************************************************************
 * $RCSfile: ParticleSpatialLayout.h,v $   $Author: adelmann $
 * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:29 $
 * IPPL_VERSION_ID: $Id: ParticleSpatialLayout.h,v 1.1.1.1 2003/01/23 07:40:29 adelmann Exp $
1422
 ***************************************************************************/