BareField.hpp 40.1 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 29 30 31 32 33 34 35
// -*- C++ -*-
/***************************************************************************
 *
 * The IPPL Framework
 * 
 * This program was prepared by PSI. 
 * All rights in the program are reserved by PSI.
 * Neither PSI nor the author(s)
 * makes any warranty, express or implied, or assumes any liability or
 * responsibility for the use of this software
 *
 * Visit www.amas.web.psi for more details
 *
 ***************************************************************************/

// -*- C++ -*-
/***************************************************************************
 *
 * The IPPL Framework
 * 
 *
 * Visit http://people.web.psi.ch/adelmann/ for more details
 *
 ***************************************************************************/

// include files
#include "Field/BareField.h"
#include "Field/BrickExpression.h"
#include "FieldLayout/FieldLayout.h"
#include "Message/Communicate.h"
#include "Message/GlobalComm.h"
#include "Message/Tags.h"
#include "Utility/Inform.h"
#include "Utility/Unique.h"
#include "Utility/IpplInfo.h"
36
//#include "Utility/IpplStats.h"
uldis_l's avatar
uldis_l committed
37

gsell's avatar
gsell committed
38 39 40 41 42 43 44 45 46 47 48 49 50
#include <map>
#include <cstdlib>


//////////////////////////////////////////////////////////////////////
//
// Copy ctor.
//

template< class T, unsigned Dim >
BareField<T,Dim>::BareField(const BareField<T,Dim>& a)
: Layout( a.Layout ),		// Copy the layout.
  Gc( a.Gc ),			// Copy the number of guard cells.
uldis_l's avatar
uldis_l committed
51 52
  compressible_m( a.compressible_m ),
  pinned(false) //UL: for pinned memory allocation
gsell's avatar
gsell committed
53
{
uldis_l's avatar
uldis_l committed
54 55
  
  
gsell's avatar
gsell committed
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

  // We assume the guard cells are peachy so clear the dirty flag.
  clearDirtyFlag();

  // Reserve space for the pointers to the LFields.
  Locals_ac.reserve( a.size_if() );
  // Loop over the LFields of the other array, creating LFields as we go.
  for ( const_iterator_if a_i = a.begin_if(); a_i != a.end_if(); ++a_i )
    {
      // Create an LField with copy ctor.
      LField<T,Dim> *lf = new LField<T,Dim>( *((*a_i).second) );
      // Insert in the local list, hinting that it should go at the end.
      Locals_ac.insert( Locals_ac.end(),
			typename ac_id_larray::value_type((*a_i).first,lf) );
    }
  // Tell the layout we are here.
  getLayout().checkin( *this , Gc );
  //INCIPPLSTAT(incBareFields);
}


//////////////////////////////////////////////////////////////////////
//
// Destructor
//

template< class T, unsigned Dim >
BareField<T,Dim>::~BareField() {
uldis_l's avatar
uldis_l committed
84 85
  
  
gsell's avatar
gsell committed
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
  // must check out from our layout
  if (Layout != 0) {
    Layout->checkout(*this);
  }
}


//////////////////////////////////////////////////////////////////////
// Initialize the field, if it was constructed from the default constructor.
// This should NOT be called if the field was constructed by providing
// a FieldLayout.

template< class T, unsigned Dim >
void
BareField<T,Dim>::initialize(Layout_t & l) {
uldis_l's avatar
uldis_l committed
101 102
  
  
gsell's avatar
gsell committed
103 104 105 106 107 108 109 110

  // if our Layout has been previously set, we just ignore this request
  if (Layout == 0) {
    Layout = &l;
    setup();
  }
}

uldis_l's avatar
uldis_l committed
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
//UL: for pinned memory allocation
template< class T, unsigned Dim >
void
BareField<T,Dim>::initialize(Layout_t & l, const bool p) {
  
  

  // if our Layout has been previously set, we just ignore this request
  if (Layout == 0) {
    Layout = &l;
    pinned = p;
    setup();
  }
}

gsell's avatar
gsell committed
126 127 128 129
template< class T, unsigned Dim >
void
BareField<T,Dim>::initialize(Layout_t & l,
			     const GuardCellSizes<Dim>& gc) {
uldis_l's avatar
uldis_l committed
130 131
  
  
gsell's avatar
gsell committed
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151

  // if our Layout has been previously set, we just ignore this request
  if (Layout == 0) {
    Layout = &l;
    Gc = gc;
    setup();
  }
}


//////////////////////////////////////////////////////////////////////
//
// Using the data that has been initialized by the ctors,
// complete the construction by allocating the LFields.
//

template< class T, unsigned Dim >
void
BareField<T,Dim>::setup()
{
uldis_l's avatar
uldis_l committed
152 153
  
  
gsell's avatar
gsell committed
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183

  // Make sure this FieldLayout can handle the number of GuardCells
  // which we have here
  if ( ! getLayout().fitsGuardCells(Gc)) {
    ERRORMSG("Cannot construct IPPL BareField:" << endl);
    ERRORMSG("  One or more vnodes is too small for the guard cells." << endl);
    ERRORMSG("  Guard cell sizes = " << Gc << endl);
    ERRORMSG("  FieldLayout = " << getLayout() << endl);
    Ippl::abort();
  }

  // We assume the guard cells are peachy so clear the dirty flag.
  clearDirtyFlag();

  // Reserve space for the pointers to the LFields.
  Locals_ac.reserve( getLayout().size_iv() );

  // Loop over all the Vnodes, creating an LField in each.
  for (typename Layout_t::iterator_iv v_i=getLayout().begin_iv();
       v_i != getLayout().end_iv();
       ++v_i)
    {
      // Get the owned and guarded sizes.
      const NDIndex<Dim> &owned = (*v_i).second->getDomain();
      NDIndex<Dim> guarded = AddGuardCells( owned , Gc );

      // Get the global vnode number (ID number, value from 0 to nvnodes-1):
      int vnode = (*v_i).second->getVnode();

      // Construct the LField for this Vnode.
uldis_l's avatar
uldis_l committed
184 185 186 187 188 189
      //UL: for pinned memory allocation
      LField<T, Dim> *lf;
      if (pinned)
	lf = new LField<T,Dim>( owned, guarded, vnode, pinned );
      else
	lf = new LField<T,Dim>( owned, guarded, vnode );
gsell's avatar
gsell committed
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209

      // Put it in the list.
      Locals_ac.insert( end_if(), 
                        typename ac_id_larray::value_type((*v_i).first,lf));
    }
  // Tell the layout we are here.
  getLayout().checkin( *this , Gc );
  //INCIPPLSTAT(incBareFields);
}

//////////////////////////////////////////////////////////////////////

//
// Print a BareField out.
//

template< class T, unsigned Dim>
void 
BareField<T,Dim>::write(std::ostream& out)
{
uldis_l's avatar
uldis_l committed
210 211
  
  
gsell's avatar
gsell committed
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 272 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

  // Inform dbgmsg(">>>>>>>> BareField::write", INFORM_ALL_NODES);
  // dbgmsg << "Printing values for field at address = " << &(*this) << endl;

  // on remote nodes, we must send the subnodes LField's to node 0
  int tag = Ippl::Comm->next_tag(F_WRITE_TAG, F_TAG_CYCLE);
  if (Ippl::myNode() != 0) {
    for ( iterator_if local = begin_if(); local != end_if() ; ++local) {
      // Cache some information about this local field.
      LField<T,Dim>&  l = *((*local).second);
      NDIndex<Dim>&  lo = (NDIndex<Dim>&) l.getOwned();
      typename LField<T,Dim>::iterator rhs(l.begin());

      // Build and send a message containing the owned LocalField data
      if (Ippl::myNode() != 0) {
	Message *mess = new Message();
	lo.putMessage(*mess);	      // send the local domain of the LField
	rhs.putMessage(*mess);          // send the data itself
	// dbgmsg << "Sending domain " << lo << " to node 0" << endl;
	Ippl::Comm->send(mess, 0, tag);
      }
    }
  } else {    // now, on node 0, receive the remaining LField's ...
    // put all the LField's in a big, uncompressed LField
    LField<T,Dim> data(getDomain(), getDomain());
    data.Uncompress();

    // first put in our local ones
    for ( iterator_if local = begin_if(); local != end_if() ; ++local) {
      // Cache some information about this local field.
      LField<T,Dim>&  l = *((*local).second);
      NDIndex<Dim>&  lo = (NDIndex<Dim>&) l.getOwned();
      typename LField<T,Dim>::iterator rhs(l.begin());
      
      // put the local LField in our big LField
      // dbgmsg << "  Copying local domain " << lo << " from Lfield at ";
      // dbgmsg << &l << ":" << endl;
      typename LField<T,Dim>::iterator putloc = data.begin(lo);
      typename LField<T,Dim>::iterator getloc = l.begin(lo);
      for ( ; getloc != l.end() ; ++putloc, ++getloc ) {
	// dbgmsg << "    from " << &(*getloc) << " to " << &(*putloc);
	// dbgmsg << ": " << *putloc << " = " << *getloc << endl;
	*putloc = *getloc;
      }
    }

    // we expect to receive one message from each remote vnode
    int remaining = getLayout().size_rdv();

    // keep receiving messages until they're all here
    for ( ; remaining > 0; --remaining) {
      // Receive the generic message.
      int any_node = COMM_ANY_NODE;
      Message *mess = Ippl::Comm->receive_block(any_node, tag);

      // Extract the domain size and LField iterator from the message
      NDIndex<Dim> lo;
      T compressed_data;
      typename LField<T,Dim>::iterator rhs(compressed_data);
      lo.getMessage(*mess);
      rhs.getMessage(*mess);
      // dbgmsg << "Received domain " << lo << " from " << any_node << endl;

      // put the received LField in our big LField
      typename LField<T,Dim>::iterator putloc = data.begin(lo);
      for (unsigned elems=lo.size(); elems > 0; ++putloc, ++rhs, --elems)
	*putloc = *rhs;

      // Free the memory in the message.
      delete mess;
    }

    // finally, we can print the big LField out
    out << data;
  }
}


//////////////////////////////////////////////////////////////////////

//
// Fill all the guard cells, including all the necessary communication.
//

template< class T, unsigned Dim >
void BareField<T,Dim>::fillGuardCells(bool reallyFill) const
{

  // This operation is logically const because the physical cells
  // of the BareField are unaffected, so cast away const here.
  BareField<T,Dim>& ncf = const_cast<BareField<T,Dim>&>(*this);

  // Only fill if we are supposed to.
  if (!reallyFill)
    return;

  // Make ourselves clean.
  ncf.clearDirtyFlag();

  // Only need to do work if we have non-zero GuardCellSizes
  if (Gc == GuardCellSizes<Dim>())
    return;

  // indicate we're doing another gc fill
  //INCIPPLSTAT(incGuardCellFills);

  // iterators for looping through LField's of this BareField
  iterator_if lf_i, lf_e = ncf.end_if();

  // ----------------------------------------
  // First the send loop.
  // Loop over all the local nodes and
  // send data to the remote ones they overlap.
  int nprocs = Ippl::getNodes();
  if (nprocs > 1) {
uldis_l's avatar
uldis_l committed
327
    
gsell's avatar
gsell committed
328 329 330 331
    // Build a map of the messages we expect to receive.
    typedef std::multimap< NDIndex<Dim> , LField<T,Dim>* , std::less<NDIndex<Dim> > > ac_recv_type;
    ac_recv_type recv_ac;
    bool* recvmsg = new bool[nprocs];
uldis_l's avatar
uldis_l committed
332
    
gsell's avatar
gsell committed
333

uldis_l's avatar
uldis_l committed
334
    
gsell's avatar
gsell committed
335 336 337 338 339 340 341
    // set up messages to be sent
    Message** mess = new Message*[nprocs];
    int iproc;
    for (iproc=0; iproc<nprocs; ++iproc) {
      mess[iproc] = NULL;
      recvmsg[iproc] = false;
    }
uldis_l's avatar
uldis_l committed
342
    
gsell's avatar
gsell committed
343 344
    // now do main loop over LFields, packing overlaps into proper messages
    for (lf_i = ncf.begin_if(); lf_i != lf_e; ++lf_i) {
uldis_l's avatar
uldis_l committed
345
      
gsell's avatar
gsell committed
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
      // Cache some information about this local array.
      LField<T,Dim> &lf = *((*lf_i).second);
      const NDIndex<Dim> &lf_domain = lf.getAllocated();
      // Find the remote ones that touch this LField's guard cells
      typename Layout_t::touch_range_dv
	rrange(ncf.getLayout().touch_range_rdv(lf_domain));
      typename Layout_t::touch_iterator_dv rv_i;
      for (rv_i = rrange.first; rv_i != rrange.second; ++rv_i) {
	// Save the intersection and the LField it is for.
	NDIndex<Dim> sub = lf_domain.intersect( (*rv_i).first );
	typedef typename ac_recv_type::value_type value_type;
	recv_ac.insert(value_type(sub,&lf));
        // note who will be sending this data
        int rnode = (*rv_i).second->getNode();
        recvmsg[rnode] = true;
      }
uldis_l's avatar
uldis_l committed
362
      
gsell's avatar
gsell committed
363

uldis_l's avatar
uldis_l committed
364
      
gsell's avatar
gsell committed
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
      const NDIndex<Dim>& lo = lf.getOwned();
      // Loop over the remote domains which have guard cells
      // that this local domain touches.
      typename Layout_t::touch_range_dv
	range( ncf.getLayout().touch_range_rdv(lo,ncf.getGC()) );
      typename Layout_t::touch_iterator_dv remote_i;
      for (remote_i = range.first; remote_i != range.second; ++remote_i) {
	// Find the intersection.
	NDIndex<Dim> intersection = lo.intersect( (*remote_i).first );
        // Find out who owns this remote domain.
        int rnode = (*remote_i).second->getNode();
	// Create an LField iterator for this intersection region,
	// and try to compress it.
        // storage for LField compression
        T compressed_value;
	LFI msgval = lf.begin(intersection, compressed_value);
	msgval.TryCompress();

	// Put intersection domain and field data into message
        if (!mess[rnode]) mess[rnode] = new Message;
        PAssert(mess[rnode]);
	mess[rnode]->put(intersection); // puts Dim items in Message
	mess[rnode]->put(msgval);       // puts 3 items in Message
      }
uldis_l's avatar
uldis_l committed
389
    
gsell's avatar
gsell committed
390
    }
uldis_l's avatar
uldis_l committed
391
    
gsell's avatar
gsell committed
392 393 394 395
    int remaining = 0;
    for (iproc=0; iproc<nprocs; ++iproc)
      if (recvmsg[iproc]) ++remaining;
    delete [] recvmsg;
uldis_l's avatar
uldis_l committed
396
    
gsell's avatar
gsell committed
397

uldis_l's avatar
uldis_l committed
398
    
gsell's avatar
gsell committed
399 400
    // Get message tag.
    int tag = Ippl::Comm->next_tag( F_GUARD_CELLS_TAG , F_TAG_CYCLE );
uldis_l's avatar
uldis_l committed
401
    
gsell's avatar
gsell committed
402 403 404 405 406 407
    // Send all the messages.
    for (iproc=0; iproc<nprocs; ++iproc) {
      if (mess[iproc]) {
        Ippl::Comm->send(mess[iproc], iproc, tag);
      }
    }
uldis_l's avatar
uldis_l committed
408
    
gsell's avatar
gsell committed
409 410 411 412 413
    delete [] mess;

    // ----------------------------------------
    // Handle the local fills.
    // Loop over all the local arrays.
uldis_l's avatar
uldis_l committed
414
    
gsell's avatar
gsell committed
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
    for (lf_i = ncf.begin_if(); lf_i != lf_e; ++lf_i)
    {
      // Cache some information about this LField.
      LField<T,Dim> &lf = *(*lf_i).second;
      const NDIndex<Dim>& la = lf.getAllocated();

      // Loop over all the other LFields to establish each LField's
      // cache of overlaps.
	
      // This is an N*N operation, but the expectation is that this will
      // pay off since we will reuse this cache quite often.

      if (!lf.OverlapCacheInitialized())
      {
        for (iterator_if rf_i = ncf.begin_if(); rf_i != ncf.end_if(); ++rf_i)
	  if ( rf_i != lf_i )
	  {
	    // Cache some info about this LField.
	    LField<T,Dim> &rf = *(*rf_i).second;
	    const NDIndex<Dim>& ro = rf.getOwned();

	    // If the remote has info we want, then add it to our cache.
	    if ( la.touches(ro) )
	      lf.AddToOverlapCache(&rf);
	  }
      }

      // We know at this point that the overlap cache is established.
      // Use it.

      for (typename LField<T,Dim>::OverlapIterator rf_i = lf.BeginOverlap();
	   rf_i != lf.EndOverlap(); ++rf_i)
      {
        LField<T, Dim> &rf = *(*rf_i);
        const NDIndex<Dim>& ro = rf.getOwned();

        bool c1 = lf.IsCompressed();
        bool c2 = rf.IsCompressed();
        bool c3 = *rf.begin() == *lf.begin();

        // If these are compressed we might not have to do any work.
        if ( !( c1 && c2 && c3 ) )
        {
uldis_l's avatar
uldis_l committed
458
	  
gsell's avatar
gsell committed
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477

	  // Find the intersection.
	  NDIndex<Dim> intersection = la.intersect(ro);
		
	  // Build an iterator for the rhs.
	  LFI rhs = rf.begin(intersection);
		
	  // Could we compress that?
	  if ( !(c1 && rhs.CanCompress(*lf.begin())) )
	  {
	    // Make sure the left is not compressed.
	    lf.Uncompress();
		  
	    // Nope, we really have to copy.
	    LFI lhs = lf.begin(intersection);
	    // And do the assignment.
	    BrickExpression<Dim,LFI,LFI,OpAssign>(lhs,rhs).apply();
	  }
	      
uldis_l's avatar
uldis_l committed
478
	  
gsell's avatar
gsell committed
479 480 481
        }
      }
    }
uldis_l's avatar
uldis_l committed
482
    
gsell's avatar
gsell committed
483 484 485

    // ----------------------------------------
    // Receive all the messages.
uldis_l's avatar
uldis_l committed
486
    
gsell's avatar
gsell committed
487 488 489
    while (remaining>0) {
      // Receive the next message.
      int any_node = COMM_ANY_NODE;
uldis_l's avatar
uldis_l committed
490
      
gsell's avatar
gsell committed
491 492 493
      Message* rmess = Ippl::Comm->receive_block(any_node,tag);
      PAssert(rmess);
      --remaining;
uldis_l's avatar
uldis_l committed
494
      
gsell's avatar
gsell committed
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

      // Determine the number of domains being sent
      int ndoms = rmess->size() / (Dim + 3);
      for (int idom=0; idom<ndoms; ++idom) {
        // Extract the intersection domain from the message.
        NDIndex<Dim> intersection;
        intersection.getMessage(*rmess);

        // Extract the rhs iterator from it.
        T compressed_value;
        LFI rhs(compressed_value);
        rhs.getMessage(*rmess);

        // Find the LField it is destined for.
        typename ac_recv_type::iterator hit = recv_ac.find( intersection );
        PAssert( hit != recv_ac.end() );
        // Build the lhs brick iterator.
        LField<T,Dim> &lf = *(*hit).second;
        // Check and see if we really have to do this.
        if ( !(rhs.IsCompressed() && lf.IsCompressed() &&
             (*rhs == *lf.begin())) )
	{
	  // Yep. gotta do it.
	  lf.Uncompress();
	  LFI lhs = lf.begin(intersection);
	  // Do the assignment.
	  BrickExpression<Dim,LFI,LFI,OpAssign>(lhs,rhs).apply();
	}

        // Take that entry out of the receive list.
        recv_ac.erase( hit );
      }
      delete rmess;
    }
uldis_l's avatar
uldis_l committed
529
    
gsell's avatar
gsell committed
530 531 532 533 534
  }
  else { // single-node case
    // ----------------------------------------
    // Handle the local fills.
    // Loop over all the local arrays.
uldis_l's avatar
uldis_l committed
535
    
gsell's avatar
gsell committed
536 537 538 539 540 541 542 543 544 545 546 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
    for (lf_i = ncf.begin_if(); lf_i != lf_e; ++lf_i)
    {
      // Cache some information about this LField.
      LField<T,Dim> &lf = *(*lf_i).second;
      const NDIndex<Dim>& la = lf.getAllocated();

      // Loop over all the other LFields to establish each LField's
      // cache of overlaps.
	
      // This is an N*N operation, but the expectation is that this will
      // pay off since we will reuse this cache quite often.

      if (!lf.OverlapCacheInitialized())
      {
        for (iterator_if rf_i = ncf.begin_if(); rf_i != ncf.end_if(); ++rf_i)
	  if ( rf_i != lf_i )
	  {
	    // Cache some info about this LField.
	    LField<T,Dim> &rf = *(*rf_i).second;
	    const NDIndex<Dim>& ro = rf.getOwned();

	    // If the remote has info we want, then add it to our cache.
	    if ( la.touches(ro) )
	      lf.AddToOverlapCache(&rf);
	  }
      }

      // We know at this point that the overlap cache is established.
      // Use it.

      for (typename LField<T,Dim>::OverlapIterator rf_i = lf.BeginOverlap();
	   rf_i != lf.EndOverlap(); ++rf_i)
      {
        LField<T, Dim> &rf = *(*rf_i);
        const NDIndex<Dim>& ro = rf.getOwned();

        bool c1 = lf.IsCompressed();
        bool c2 = rf.IsCompressed();
        bool c3 = *rf.begin() == *lf.begin();

        // If these are compressed we might not have to do any work.
        if ( !( c1 && c2 && c3 ) )
        {
uldis_l's avatar
uldis_l committed
579
	  
gsell's avatar
gsell committed
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598

	  // Find the intersection.
	  NDIndex<Dim> intersection = la.intersect(ro);
		
	  // Build an iterator for the rhs.
	  LFI rhs = rf.begin(intersection);
		
	  // Could we compress that?
	  if ( !(c1 && rhs.CanCompress(*lf.begin())) )
	  {
	    // Make sure the left is not compressed.
	    lf.Uncompress();
		  
	    // Nope, we really have to copy.
	    LFI lhs = lf.begin(intersection);
	    // And do the assignment.
	    BrickExpression<Dim,LFI,LFI,OpAssign>(lhs,rhs).apply();
	  }
	      
uldis_l's avatar
uldis_l committed
599
	  
gsell's avatar
gsell committed
600 601 602
        }
      }
    }
uldis_l's avatar
uldis_l committed
603
    
gsell's avatar
gsell committed
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
  }
  return;
}

//////////////////////////////////////////////////////////////////////

//
// Fill guard cells with a constant value.
// This is typically used to zero out the guard cells before a scatter.
//

template <class T, unsigned Dim>
void BareField<T,Dim>::setGuardCells(const T& val) const
{
  // profiling macros
uldis_l's avatar
uldis_l committed
619 620
  
  
gsell's avatar
gsell committed
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 646 647 648 649 650 651 652 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 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713

  // if there are no guard cells, we can just return
  if (Gc == GuardCellSizes<Dim>())
    return;

  // this member function is logically const, so cast away const-ness
  BareField<T,Dim>& ncf = const_cast<BareField<T,Dim>&>(*this);

  // loop over our LFields and set guard cell values
  iterator_if lf_i, lf_e = ncf.end_if();
  for (lf_i = ncf.begin_if(); lf_i != lf_e; ++lf_i) {
    // Get this LField
    LField<T,Dim>& lf = *((*lf_i).second);

    // Quick test to see if we can avoid doing any work.
    // If this LField is compressed and already contains
    // the value that is being assigned to the guard cells,
    // then we can just move on to the next LField.
    if (lf.IsCompressed() && lf.getCompressedData() == val)
      continue;

    // OK, we really have to fill the guard cells, so get 
    // the domains we will be working with.
    const NDIndex<Dim>& adom = lf.getAllocated();
    const NDIndex<Dim>& odom = lf.getOwned();
    NDIndex<Dim> dom = odom;  // initialize working domain to Owned

    // create a compressed LField with the same allocated domain
    // containing the value to be assigned to the guard cells
    LField<T,Dim> rf(odom,adom);
    rf.Compress(val);

    // Uncompress LField to be filled and get some iterators
    lf.Uncompress();
    LFI lhs, rhs;

    // now loop over dimensions and fill guard cells along each
    for (unsigned int idim = 0; idim < Dim; ++idim) {
      // set working domain to left guards in this dimension
      dom[idim] = Index(adom[idim].first(),
                        adom[idim].first() + Gc.left(idim) - 1);
      if (!dom[idim].empty()) {
	// Set iterators over working domain and do assignment
	lhs = lf.begin(dom);
	rhs = rf.begin(dom);
	BrickExpression<Dim,LFI,LFI,OpAssign>(lhs,rhs).apply();
      }

      // Set working domain to right guards in this dimension
      dom[idim] = Index(adom[idim].last() - Gc.right(idim) + 1,
                        adom[idim].last());
      if (!dom[idim].empty()) {
	// Set iterators over working domain and do assignment
	lhs = lf.begin(dom);
	rhs = rf.begin(dom);
	BrickExpression<Dim,LFI,LFI,OpAssign>(lhs,rhs).apply();
      }

      // Adjust working domain along this direction 
      // in preparation for working on next dimension.
      dom[idim] = adom[idim];
    }
  }

  // let's set the dirty flag, since we have modified guard cells.
  ncf.setDirtyFlag();

  return;
}

//////////////////////////////////////////////////////////////////////

//
// Accumulate guard cells into real cells, including necessary communication.
//

template <class T, unsigned Dim>
void BareField<T,Dim>::accumGuardCells()
{

  // Only need to do work if we have non-zero GuardCellSizes
  if (Gc == GuardCellSizes<Dim>())
    return;

  // iterators for looping through LField's of this BareField
  iterator_if lf_i, lf_e = end_if();

  // ----------------------------------------
  // First the send loop.
  // Loop over all the local nodes and
  // send data to the remote ones they overlap.
  int nprocs = Ippl::getNodes();
  if (nprocs > 1) {
uldis_l's avatar
uldis_l committed
714
    
gsell's avatar
gsell committed
715 716 717 718
    // Build a map of the messages we expect to receive.
    typedef std::multimap< NDIndex<Dim> , LField<T,Dim>* , std::less<NDIndex<Dim> > > ac_recv_type;
    ac_recv_type recv_ac;
    bool* recvmsg = new bool[nprocs];
uldis_l's avatar
uldis_l committed
719
    
gsell's avatar
gsell committed
720

uldis_l's avatar
uldis_l committed
721
    
gsell's avatar
gsell committed
722 723 724 725 726 727 728
    // set up messages to be sent
    Message** mess = new Message*[nprocs];
    int iproc;
    for (iproc=0; iproc<nprocs; ++iproc) {
      mess[iproc] = NULL;
      recvmsg[iproc] = false;
    }
uldis_l's avatar
uldis_l committed
729
    
gsell's avatar
gsell committed
730 731
    // now do main loop over LFields, packing overlaps into proper messages
    for (lf_i = begin_if(); lf_i != lf_e; ++lf_i) {
uldis_l's avatar
uldis_l committed
732
      
gsell's avatar
gsell committed
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
      // Cache some information about this local array.
      LField<T,Dim> &lf = *((*lf_i).second);
      const NDIndex<Dim>& lo = lf.getOwned();
      // Find the remote ones with guard cells touching this LField
      typename Layout_t::touch_range_dv
	rrange( getLayout().touch_range_rdv(lo,Gc) );
      typename Layout_t::touch_iterator_dv rv_i;
      for (rv_i = rrange.first; rv_i != rrange.second; ++rv_i) {
	// Save the intersection and the LField it is for.
	NDIndex<Dim> sub = lo.intersect( (*rv_i).first );
	recv_ac.insert(typename ac_recv_type::value_type(sub,&lf));
        // note who will be sending this data
        int rnode = (*rv_i).second->getNode();
        recvmsg[rnode] = true;
      } 
uldis_l's avatar
uldis_l committed
748
      
gsell's avatar
gsell committed
749

uldis_l's avatar
uldis_l committed
750
      
gsell's avatar
gsell committed
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
      const NDIndex<Dim> &lf_domain = lf.getAllocated();
      // Loop over the remote domains that touch this local
      // domain's guard cells
      typename Layout_t::touch_range_dv
	range(getLayout().touch_range_rdv(lf_domain));
      typename Layout_t::touch_iterator_dv remote_i;
      for (remote_i = range.first; remote_i != range.second; ++remote_i) {
	// Find the intersection.
	NDIndex<Dim> intersection = lf_domain.intersect( (*remote_i).first );
        // Find out who owns this remote domain.
        int rnode = (*remote_i).second->getNode();
	// Create an LField iterator for this intersection region,
	// and try to compress it.
        // storage for LField compression
        T compressed_value;
	LFI msgval = lf.begin(intersection, compressed_value);
	msgval.TryCompress();

	// Put intersection domain and field data into message
        if (!mess[rnode]) mess[rnode] = new Message;
        PAssert(mess[rnode]);
	mess[rnode]->put(intersection); // puts Dim items in Message
	mess[rnode]->put(msgval);       // puts 3 items in Message
      }
uldis_l's avatar
uldis_l committed
775
    
gsell's avatar
gsell committed
776
    }
uldis_l's avatar
uldis_l committed
777
    
gsell's avatar
gsell committed
778 779 780 781
    int remaining = 0;
    for (iproc=0; iproc<nprocs; ++iproc)
      if (recvmsg[iproc]) ++remaining;
    delete [] recvmsg;
uldis_l's avatar
uldis_l committed
782
    
gsell's avatar
gsell committed
783

uldis_l's avatar
uldis_l committed
784
    
gsell's avatar
gsell committed
785 786
    // Get message tag.
    int tag = Ippl::Comm->next_tag( F_GUARD_CELLS_TAG , F_TAG_CYCLE );
uldis_l's avatar
uldis_l committed
787
    
gsell's avatar
gsell committed
788 789 790 791 792 793
    // Send all the messages.
    for (iproc=0; iproc<nprocs; ++iproc) {
      if (mess[iproc]) {
        Ippl::Comm->send(mess[iproc], iproc, tag);
      }
    }
uldis_l's avatar
uldis_l committed
794
    
gsell's avatar
gsell committed
795 796 797 798 799
    delete [] mess;

    // ----------------------------------------
    // Handle the local fills.
    // Loop over all the local arrays.
uldis_l's avatar
uldis_l committed
800
    
gsell's avatar
gsell committed
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
    for (lf_i=begin_if(); lf_i != lf_e; ++lf_i)
    {
      // Cache some information about this LField.
      LField<T,Dim> &lf = *(*lf_i).second;
      const NDIndex<Dim>& la = lf.getAllocated();

      // Loop over all the other LFields to establish each LField's
      // cache of overlaps.
	
      // This is an N*N operation, but the expectation is that this will
      // pay off since we will reuse this cache quite often.

      if (!lf.OverlapCacheInitialized())
      {
        for (iterator_if rf_i = begin_if(); rf_i != end_if(); ++rf_i)
	  if ( rf_i != lf_i )
	  {
	    // Cache some info about this LField.
	    LField<T,Dim> &rf = *(*rf_i).second;
	    const NDIndex<Dim>& ro = rf.getOwned();

	    // If the remote has info we want, then add it to our cache.
	    if ( la.touches(ro) )
	      lf.AddToOverlapCache(&rf);
	  }
      }

      // We know at this point that the overlap cache is established.
      // Use it.

      for (typename LField<T,Dim>::OverlapIterator rf_i = lf.BeginOverlap();
	   rf_i != lf.EndOverlap(); ++rf_i)
      {
        LField<T, Dim> &rf = *(*rf_i);
        const NDIndex<Dim>& ro = rf.getOwned();

uldis_l's avatar
uldis_l committed
837
        
gsell's avatar
gsell committed
838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856

        // Find the intersection.
        NDIndex<Dim> intersection = la.intersect(ro);
		
        // Build iterator for lf guard cells
        LFI lhs = lf.begin(intersection);

        // check if we can skip accumulation
        if ( !lhs.CanCompress(T()) ) {

          // Make sure the right side is not compressed.
          rf.Uncompress();
		  
          // Build iterator for rf real cells
          LFI rhs = rf.begin(intersection);

          // And do the accumulation
          BrickExpression<Dim,LFI,LFI,OpAddAssign>(rhs,lhs).apply();
	}    
uldis_l's avatar
uldis_l committed
857
        
gsell's avatar
gsell committed
858 859
      }
    }
uldis_l's avatar
uldis_l committed
860
    
gsell's avatar
gsell committed
861 862 863

    // ----------------------------------------
    // Receive all the messages.
uldis_l's avatar
uldis_l committed
864
    
gsell's avatar
gsell committed
865 866 867
    while (remaining>0) {
      // Receive the next message.
      int any_node = COMM_ANY_NODE;
uldis_l's avatar
uldis_l committed
868
      
gsell's avatar
gsell committed
869 870 871
      Message* rmess = Ippl::Comm->receive_block(any_node,tag);
      PAssert(rmess);
      --remaining;
uldis_l's avatar
uldis_l committed
872
      
gsell's avatar
gsell committed
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

      // Determine the number of domains being sent
      int ndoms = rmess->size() / (Dim + 3);
      for (int idom=0; idom<ndoms; ++idom) {
        // Extract the intersection domain from the message.
        NDIndex<Dim> intersection;
        intersection.getMessage(*rmess);

        // Extract the rhs iterator from it.
        T compressed_value;
        LFI rhs(compressed_value);
        rhs.getMessage(*rmess);

        // Find the LField it is destined for.
        typename ac_recv_type::iterator hit = recv_ac.find( intersection );
        PAssert( hit != recv_ac.end() );

        // Build the lhs brick iterator.
        LField<T,Dim> &lf = *(*hit).second;

	// Make sure LField is uncompressed
	lf.Uncompress();
	LFI lhs = lf.begin(intersection);

	// Do the accumulation
	BrickExpression<Dim,LFI,LFI,OpAddAssign>(lhs,rhs).apply();

        // Take that entry out of the receive list.
        recv_ac.erase( hit );
      }
      delete rmess;
    }
uldis_l's avatar
uldis_l committed
905
    
gsell's avatar
gsell committed
906 907 908 909 910
  }
  else { // single-node case
    // ----------------------------------------
    // Handle the local fills.
    // Loop over all the local arrays.
uldis_l's avatar
uldis_l committed
911
    
gsell's avatar
gsell committed
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
    for (lf_i=begin_if(); lf_i != lf_e; ++lf_i)
    {
      // Cache some information about this LField.
      LField<T,Dim> &lf = *(*lf_i).second;
      const NDIndex<Dim>& la = lf.getAllocated();

      // Loop over all the other LFields to establish each LField's
      // cache of overlaps.
	
      // This is an N*N operation, but the expectation is that this will
      // pay off since we will reuse this cache quite often.

      if (!lf.OverlapCacheInitialized())
      {
        for (iterator_if rf_i = begin_if(); rf_i != end_if(); ++rf_i)
	  if ( rf_i != lf_i )
	  {
	    // Cache some info about this LField.
	    LField<T,Dim> &rf = *(*rf_i).second;
	    const NDIndex<Dim>& ro = rf.getOwned();

	    // If the remote has info we want, then add it to our cache.
	    if ( la.touches(ro) )
	      lf.AddToOverlapCache(&rf);
	  }
      }

      // We know at this point that the overlap cache is established.
      // Use it.

      for (typename LField<T,Dim>::OverlapIterator rf_i = lf.BeginOverlap();
	   rf_i != lf.EndOverlap(); ++rf_i)
      {
        LField<T, Dim> &rf = *(*rf_i);
        const NDIndex<Dim>& ro = rf.getOwned();

uldis_l's avatar
uldis_l committed
948
        
gsell's avatar
gsell committed
949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966

        // Find the intersection.
        NDIndex<Dim> intersection = la.intersect(ro);
		
        // Build iterator for lf guard cells
        LFI lhs = lf.begin(intersection);

        // Check if we can skip accumulation
        if ( !lhs.CanCompress(T()) ) {
          // Make sure rf is not compressed.
          rf.Uncompress();
		  
          // Build iterator for rf real cells
          LFI rhs = rf.begin(intersection);

          // And do the accumulation
          BrickExpression<Dim,LFI,LFI,OpAddAssign>(rhs,lhs).apply();
	}    
uldis_l's avatar
uldis_l committed
967
        
gsell's avatar
gsell committed
968 969
      }
    }
uldis_l's avatar
uldis_l committed
970
    
gsell's avatar
gsell committed
971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
  }

  // since we just modified real cell values, set dirty flag if using
  // deferred guard cell fills
  setDirtyFlag();
  // fill guard cells now, unless we are deferring
  fillGuardCellsIfNotDirty();
  // try to compress the final result
  Compress();

  return;
}

//////////////////////////////////////////////////////////////////////

//
// Tell a BareField to compress itself.
// Just loop over all of the local fields and tell them to compress.
//
template<class T, unsigned Dim>
void BareField<T,Dim>::Compress() const
{
uldis_l's avatar
uldis_l committed
993 994
  
  
gsell's avatar
gsell committed
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006

  if (!compressible_m) return;

  // This operation is logically const, so cast away const here
  BareField<T,Dim>& ncf = const_cast<BareField<T,Dim>&>(*this);
  for (iterator_if lf_i = ncf.begin_if(); lf_i != ncf.end_if(); ++lf_i)
    (*lf_i).second->TryCompress(isDirty());
}

template<class T, unsigned Dim>
void BareField<T,Dim>::Uncompress() const
{
uldis_l's avatar
uldis_l committed
1007 1008
  
  
gsell's avatar
gsell committed
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022

  // This operation is logically const, so cast away const here
  BareField<T,Dim>& ncf = const_cast<BareField<T,Dim>&>(*this);
  for (iterator_if lf_i = ncf.begin_if(); lf_i != ncf.end_if(); ++lf_i)
    (*lf_i).second->Uncompress();
}

//
// Look at all the local fields and calculate the 
// fraction of all the elements that are compressed.
//
template<class T, unsigned Dim>
double BareField<T,Dim>::CompressedFraction() const
{
uldis_l's avatar
uldis_l committed
1023 1024
  
  
gsell's avatar
gsell committed
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

  // elements[0] = total elements
  // elements[1] = compressed elements
  double elements[2] = { 0.0, 0.0};
  // Loop over all of the local fields.
  for (const_iterator_if lf_i=begin_if(); lf_i != end_if(); ++lf_i)
    {
      // Get a reference to the current local field.
      LField<T,Dim> &lf = *(*lf_i).second;
      // Get the size of this one.
      double s = lf.getOwned().size();
      // Add that up.
      elements[0] += s;
      // If it is compressed...
      if ( lf.IsCompressed() )
	// Add that amount to the compressed total.
	elements[1] += s;
    }
  // Make some space to put the global sum of each of the above.
  double reduced_elements[2] = { 0.0, 0.0};
  // Do the global reduction.
  reduce(elements,elements+2,reduced_elements,OpAddAssign());
  // Return the fraction.
  return reduced_elements[1]/reduced_elements[0];
}


//////////////////////////////////////////////////////////////////////
template<class T, unsigned Dim>
void BareField<T,Dim>::Repartition(UserList* userlist)
{
uldis_l's avatar
uldis_l committed
1056 1057
  
  
gsell's avatar
gsell committed
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080

  // Cast to the proper type of FieldLayout.
  Layout_t *newLayout = (Layout_t *)( userlist );

  // Build a new temporary field on the new layout.
  BareField<T,Dim> tempField( *newLayout, Gc );

  // Copy our data over to the new layout.
  tempField = *this;

  // Copy back the pointers to the new local fields.
  Locals_ac = tempField.Locals_ac;

  //INCIPPLSTAT(incRepartitions);
}


//////////////////////////////////////////////////////////////////////
// Tell the subclass that the FieldLayout is being deleted, so
// don't use it anymore
template<class T, unsigned Dim>
void BareField<T,Dim>::notifyUserOfDelete(UserList* userlist)
{
uldis_l's avatar
uldis_l committed
1081 1082
  
  
gsell's avatar
gsell committed
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 1113 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

  // just set our layout pointer to NULL; if we try to do anything more
  // with this object, other than delete it, a core dump is likely
  if (Layout != 0 && Layout->get_Id() == userlist->getUserListID()) {
    // the ID refers to this layout, so get rid of it.  It is possible
    // the ID refers to some other object, in which case we do not want
    // to cast away our Layout object.
    Layout = 0;
  } else {
    // for now, print a warning, until other types of FieldLayoutUser's
    // are set up to register with a FieldLayout ... but in general,
    // this is OK and this warning should be removed
    WARNMSG("BareField: notified of unknown UserList being deleted.");
    WARNMSG(endl);
  }
}

// a simple true-false template used to select which loop to implement
// in the BareField::localElement body
template<unsigned Dim, bool exists>
class LFieldDimTag {
};

// 1, 2, 3, and N Dimensional functions
template <class T>
inline
T* PtrOffset(T* ptr, const NDIndex<1U>& pos, const NDIndex<1U>& alloc,
             LFieldDimTag<1U,true>) {
  T* newptr = ptr + pos[0].first() - alloc[0].first();
  return newptr;
}

template <class T>
inline
T* PtrOffset(T* ptr, const NDIndex<2U>& pos, const NDIndex<2U>& alloc,
               LFieldDimTag<2U,true>) {
  T* newptr = ptr + pos[0].first() - alloc[0].first() +
         alloc[0].length() * ( pos[1].first() - alloc[1].first() );
  return newptr;
}

template <class T>
inline
T* PtrOffset(T* ptr, const NDIndex<3U>& pos, const NDIndex<3U>& alloc,
               LFieldDimTag<3U,true>) {
  T* newptr = ptr + pos[0].first() - alloc[0].first() +
         alloc[0].length() * ( pos[1].first() - alloc[1].first() +
         alloc[1].length() * ( pos[2].first() - alloc[2].first() ) );
  return newptr;
}

template <class T, unsigned Dim>
inline
T* PtrOffset(T* ptr, const NDIndex<Dim>& pos, const NDIndex<Dim>& alloc,
             LFieldDimTag<Dim,false>) {
  T* newptr = ptr;
  int n=1;
  for (unsigned int d=0; d<Dim; ++d) {
    newptr += n * (pos[d].first() - alloc[d].first());
    n *= alloc[d].length();
  }
  return newptr;
}


//////////////////////////////////////////////////////////////////////
// Get a ref to a single element of the Field; if it is not local to our
// processor, print an error and exit.  This allows the user to provide
// different index values on each node, instead of using the same element
// and broadcasting to all nodes.
template<class T, unsigned Dim> 
T& BareField<T,Dim>::localElement(const NDIndex<Dim>& Indexes) const
{
uldis_l's avatar
uldis_l committed
1156 1157 1158
  
  
  
gsell's avatar
gsell committed
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202

  // Instead of checking to see if the user has asked for one element,
  // we will just use the first element specified for each dimension.

  // Is this element here? 
  // Try and find it in the local BareFields.
  const_iterator_if lf_i   = begin_if();
  const_iterator_if lf_end = end_if();
  for ( ; lf_i != lf_end ; ++lf_i ) {
    LField<T,Dim>& lf(*(*lf_i).second);
    // End-point "contains" OK since "owned" is unit stride.
    // was before CK fix: if ( lf.getOwned().contains( Indexes ) ) {
    if ( lf.getAllocated().contains( Indexes ) ) {	
      // Found it ... first uncompress, then get a pointer to the
      // requested element.
      lf.Uncompress();
      //      return *(lf.begin(Indexes));
      // instead of building an iterator, just find the value
      NDIndex<Dim> alloc = lf.getAllocated();
      T* pdata = PtrOffset(lf.getP(), Indexes, alloc,
                           LFieldDimTag<Dim,(Dim<=3)>());
      return *pdata;
    }
  }

  // if we're here, we did not find it ... it must not be local
  ERRORMSG("BareField::localElement: attempt to access non-local index ");
  ERRORMSG(Indexes << " on node " << Ippl::myNode() << endl);
  ERRORMSG("Occurred in a BareField with layout = " << getLayout() << endl);
  ERRORMSG("Calling abort ..." << endl);
  Ippl::abort();
  return *((*((*(begin_if())).second)).begin());
}


//////////////////////////////////////////////////////////////////////
//
// Get a single value and return it in the given storage.  Whichever
// node owns the value must broadcast it to the other nodes.
//
//////////////////////////////////////////////////////////////////////
template <class T, unsigned int Dim>
void BareField<T,Dim>::getsingle(const NDIndex<Dim>& Indexes, T& r) const
{
uldis_l's avatar
uldis_l committed
1203 1204
  
  
gsell's avatar
gsell committed
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 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 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335

  // Instead of checking to see if the user has asked for one element,
  // we will just use the first element specified for each dimension.

  // Check to see if the point is in the boundary conditions.
  // Check for: The point is not in the owned domain, but it is in that
  //            domain augmented with the boundary condition size.
  // If so, use a different algorithm.
  if ( (!Indexes.touches(Layout->getDomain())) &&
       Indexes.touches(AddGuardCells(Layout->getDomain(),Gc)) ) {
    getsingle_bc(Indexes,r);
    return;
  }

  // create a tag for send/receives if necessary
  int tag = Ippl::Comm->next_tag(F_GETSINGLE_TAG, F_TAG_CYCLE);

  // Is it here? Try and find it in the LFields
  const_iterator_if lf_end = end_if();
  for (const_iterator_if lf_i = begin_if(); lf_i != lf_end ; ++lf_i) {
    if ( (*lf_i).second->getOwned().contains( Indexes ) ) {
      // Found it.
      // Get a pointer to the requested element.
      LField<T,Dim>& lf( *(*lf_i).second );
      typename LField<T,Dim>::iterator lp = lf.begin(Indexes);

      // Get the requested data.
      r = *lp;

      // Broadcast it if we're running in parallel
      if (Ippl::getNodes() > 1) {
	Message *mess = new Message;
	::putMessage(*mess, r);
	Ippl::Comm->broadcast_others(mess, tag);
      }

      return;
    }
  }

  // If we're here, we didn't find it: It is remote.  Wait for a message.
  if (Ippl::getNodes() > 1) {
    int any_node = COMM_ANY_NODE;
    Message *mess = Ippl::Comm->receive_block(any_node,tag);
    ::getMessage(*mess, r);
    delete mess;
  }
  else {
    // we did not find it, and we only have one node, so this must be
    // an error.
    ERRORMSG("Illegal single-value index " << Indexes);
    ERRORMSG(" in BareField::getsingle()" << endl);
  }
}

//////////////////////////////////////////////////////////////////////

//
// Get a single value from the BareField when we know that the 
// value is in the boundary condition area.
// We use a more robust but slower algorithm here because there could 
// be redundancy.
//

template<class T, unsigned D>
void
BareField<T,D>::getsingle_bc(const NDIndex<D>& Indexes, T& r) const
{
  // We will look through everything to find who is the authority
  // for the data.  We look through the locals to see if we have it,
  // and we look through the remotes to see if someone else has it.
  // The lowest numbered processor is the authority.
  int authority_proc = -1;

  // Look through all the locals to try and find it.
  // Loop over all the LFields.
  const_iterator_if lf_end = end_if();
  for (const_iterator_if lf_i = begin_if(); lf_i != lf_end ; ++lf_i) {
    // Is it in this LField?
    if ( (*lf_i).second->getAllocated().contains( Indexes ) ) {
      // Found it.  As far as we know now, this is the authority proc.
      authority_proc = Ippl::myNode();

      // Get the requested data.
      LField<T,D>& lf( *(*lf_i).second );
      typename LField<T,D>::iterator lp = lf.begin(Indexes);
      r = *lp;

      // If we're not the only guy on the block, go on to find the remotes.
      if (Ippl::getNodes() > 1) 
	break;

      // Otherwise, we're done.
      return;
    }
  }

  // Look through all the remotes to see who else has it.
  // Loop over all the remote LFields that touch Indexes.
  typename FieldLayout<D>::touch_range_dv range = 
    Layout->touch_range_rdv(Indexes,Gc);
  for (typename FieldLayout<D>::touch_iterator_dv p=range.first; 
       p!=range.second;++p) 
    // See if anybody has a lower processor number.
    if ( authority_proc > (*p).second->getNode() )
      // Someone else is the authority.
      authority_proc = (*p).second->getNode();

  // create a tag for the broadcast.
  int tag = Ippl::Comm->next_tag(F_GETSINGLE_TAG, F_TAG_CYCLE);

  if ( authority_proc == Ippl::myNode() ) {
    // If we're the authority, broadcast.
    Message *mess = new Message;
    ::putMessage(*mess, r);
    Ippl::Comm->broadcast_others(mess, tag);
  }
  else {
    // If someone else is the authority, receive the message.
    Message *mess = Ippl::Comm->receive_block(authority_proc,tag);
    ::getMessage(*mess, r);
    delete mess;
  }
  
}

/***************************************************************************
 * $RCSfile: BareField.cpp,v $   $Author: adelmann $
 * $Revision: 1.1.1.1 $   $Date: 2003/01/23 07:40:26 $
 * IPPL_VERSION_ID: $Id: BareField.cpp,v 1.1.1.1 2003/01/23 07:40:26 adelmann Exp $ 
 ***************************************************************************/