BCond.hpp 189 KB
Newer Older
gsell's avatar
gsell committed
1 2 3 4
// -*- C++ -*-
/***************************************************************************
 *
 * The IPPL Framework
5 6
 *
 * This program was prepared by PSI.
gsell's avatar
gsell committed
7 8 9 10 11 12 13 14 15 16 17 18 19
 * 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
20
 *
gsell's avatar
gsell committed
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
 *
 * Visit http://people.web.psi.ch/adelmann/ for more details
 *
 ***************************************************************************/

// include files
#include "Field/BCond.h"
#include "Field/BareField.h"
#include "Index/NDIndex.h"
#include "Index/Index.h"
#include "Field/GuardCellSizes.h"
#include "Field/BrickIterator.h"
#include "Field/BrickExpression.h"
#include "Meshes/Centering.h"
#include "Meshes/CartesianCentering.h"
#include "Utility/IpplInfo.h"
#include "Utility/PAssert.h"
#include "AppTypes/AppTypeTraits.h"
uldis_l's avatar
uldis_l committed
39

gsell's avatar
gsell committed
40 41 42 43 44 45 46 47 48 49 50 51 52 53

#include <iostream>
#include <typeinfo>
#include <vector>

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

template<class T, unsigned D, class M, class C>
int BCondBase<T,D,M,C>::allComponents = -9999;

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

// Use this macro to specialize PETE_apply functions for component-wise
// operators and built-in types and print an error message.
54

gsell's avatar
gsell committed
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
#define COMPONENT_APPLY_BUILTIN(OP,T)                                       \
inline void PETE_apply(const OP<T>&, T&, const T&)                          \
{                                                                           \
  ERRORMSG("Component boundary condition on a scalar (T)." << endl);        \
  Ippl::abort();                                                           \
}


/*

  Constructor for BCondBase<T,D,M,C>
  Records the face, and figures out what component to remember.

 */

template<class T, unsigned int D, class M, class C>
BCondBase<T,D,M,C>::BCondBase(unsigned int face, int i, int j)
: m_face(face), m_changePhysical(false)
{
  // Must figure out if two, one, or no component indices are specified
  // for which this BC is to apply; of none are specified, it applies to
  // all components of the elements (of type T).
  if (j != BCondBase<T,D,M,C>::allComponents) {
78 79
    if (i == BCondBase<T,D,M,C>::allComponents)
      ERRORMSG("BCondBase(): component 2 specified, component 1 not."
gsell's avatar
gsell committed
80 81
	       << endl);
    // For two specified component indices, must turn the two integer component
82 83
    // index values into a single int value for Component, which is used in
    // pointer offsets in applicative templates elsewhere. How to do this
gsell's avatar
gsell committed
84 85 86 87 88 89 90 91 92
    // depends on what kind of two-index multicomponent object T is. Implement
    // only for Tenzor, AntiSymTenzor, and SymTenzor (for now, at least):
    if (getTensorOrder(get_tag(T())) == IPPL_TENSOR) {
      m_component = i + j*D;
    } else if (getTensorOrder(get_tag(T())) == IPPL_SYMTENSOR) {
      int lo = i < j ? i : j;
      int hi = i > j ? i : j;
      m_component = ((hi+1)*hi/2) + lo;
    } else if (getTensorOrder(get_tag(T())) == IPPL_ANTISYMTENSOR) {
93
      PAssert_GT(i, j);
gsell's avatar
gsell committed
94 95 96 97 98 99
      m_component = ((i-1)*i/2) + j;
    } else {
      ERRORMSG(
        "BCondBase(): something other than [Sym,AntiSym]Tenzor specified"
	<< " two component indices; not implemented." << endl);
    }
100

gsell's avatar
gsell committed
101 102 103
  } else {
    // For only one specified component index (including the default case of
    // BCondBase::allComponents meaning apply to all components of T, just
104
    // assign the Component value for use in pointer offsets into
gsell's avatar
gsell committed
105 106 107
    // single-component-index types in applicative templates elsewhere:
    m_component = i;
  }
108
}
gsell's avatar
gsell committed
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132

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

/*

  BCondBase::write(ostream&)
  Print out information about the BCondBase to an ostream.
  This is called by its subclasses, which is why
  it calls typeid(*this) to print out the class name.

 */

template<class T, unsigned int D, class M, class C>
void BCondBase<T,D,M,C>::write(std::ostream& out) const
{
  out << "BCondBase" << ", Face=" << m_face;
}

template<class T, unsigned int D, class M, class C>
void PeriodicFace<T,D,M,C>::write(std::ostream& out) const
{
  out << "PeriodicFace" << ", Face=" << BCondBase<T,D,M,C>::m_face;
}

Andreas Adelmann's avatar
for P3M  
Andreas Adelmann committed
133 134 135 136 137 138 139 140 141 142 143 144 145 146
//BENI adds Interpolation face BC
template<class T, unsigned int D, class M, class C>
void InterpolationFace<T,D,M,C>::write(std::ostream& out) const
{
  out << "InterpolationFace" << ", Face=" << BCondBase<T,D,M,C>::m_face;
}

//BENI adds ParallelInterpolation face BC
template<class T, unsigned int D, class M, class C>
void ParallelInterpolationFace<T,D,M,C>::write(std::ostream& out) const
{
  out << "ParallelInterpolationFace" << ", Face=" << BCondBase<T,D,M,C>::m_face;
}

gsell's avatar
gsell committed
147 148 149 150 151 152 153 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 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
template<class T, unsigned int D, class M, class C>
void ParallelPeriodicFace<T,D,M,C>::write(std::ostream& out) const
{
  out << "ParallelPeriodicFace" << ", Face=" << BCondBase<T,D,M,C>::m_face;
}

template<class T, unsigned int D, class M, class C>
void NegReflectFace<T,D,M,C>::write(std::ostream& out) const
{
  out << "NegReflectFace" << ", Face=" << BCondBase<T,D,M,C>::m_face;
}

template<class T, unsigned int D, class M, class C>
void NegReflectAndZeroFace<T,D,M,C>::write(std::ostream& out) const
{
  out << "NegReflectAndZeroFace" << ", Face=" << BCondBase<T,D,M,C>::m_face;
}

template<class T, unsigned int D, class M, class C>
void PosReflectFace<T,D,M,C>::write(std::ostream& out) const
{
  out << "PosReflectFace" << ", Face=" << BCondBase<T,D,M,C>::m_face;
}

template<class T, unsigned int D, class M, class C>
void ZeroFace<T,D,M,C>::write(std::ostream& out) const
{
  out << "ZeroFace" << ", Face=" << BCondBase<T,D,M,C>::m_face;
}

template<class T, unsigned int D, class M, class C>
void ZeroGuardsAndZeroFace<T,D,M,C>::write(std::ostream& out) const
{
  out << "ZeroGuardsAndZeroFace" << ", Face=" << BCondBase<T,D,M,C>::m_face;
}

template<class T, unsigned int D, class M, class C>
void ConstantFace<T,D,M,C>::write(std::ostream& out) const
{
  out << "ConstantFace"
      << ", Face=" << BCondBase<T,D,M,C>::m_face
      << ", Constant=" << this->Offset
      << endl;
}

template<class T, unsigned int D, class M, class C>
void EurekaFace<T,D,M,C>::write(std::ostream& out) const
{
  out << "EurekaFace" << ", Face=" << BCondBase<T,D,M,C>::m_face;
}

template<class T, unsigned int D, class M, class C>
void FunctionFace<T,D,M,C>::write(std::ostream& out) const
{
  out << "FunctionFace" << ", Face=" << BCondBase<T,D,M,C>::m_face;
}

template<class T, unsigned int D, class M, class C>
void ComponentFunctionFace<T,D,M,C>::write(std::ostream& out) const
{
  out << "ComponentFunctionFace" << ", Face=" << BCondBase<T,D,M,C>::m_face;
}

template<class T, unsigned D, class M, class C>
void
ExtrapolateFace<T,D,M,C>::write(std::ostream& o) const
{
214 215


gsell's avatar
gsell committed
216 217 218 219 220 221 222 223
  o << "ExtrapolateFace, Face=" << BCondBase<T,D,M,C>::m_face
    << ", Offset=" << Offset << ", Slope=" << Slope;
}

template<class T, unsigned D, class M, class C>
void
ExtrapolateAndZeroFace<T,D,M,C>::write(std::ostream& o) const
{
224 225


gsell's avatar
gsell committed
226 227 228 229 230 231 232 233
  o << "ExtrapolateAndZeroFace, Face=" << BCondBase<T,D,M,C>::m_face
    << ", Offset=" << Offset << ", Slope=" << Slope;
}

template<class T, unsigned D, class M, class C>
void
LinearExtrapolateFace<T,D,M,C>::write(std::ostream& o) const
{
234 235


gsell's avatar
gsell committed
236 237 238 239 240 241 242
  o << "LinearExtrapolateFace, Face=" << BCondBase<T,D,M,C>::m_face;
}

template<class T, unsigned D, class M, class C>
void
ComponentLinearExtrapolateFace<T,D,M,C>::write(std::ostream& o) const
{
uldis_l's avatar
uldis_l committed
243

gsell's avatar
gsell committed
244 245 246 247 248 249 250 251 252
  o << "ComponentLinearExtrapolateFace, Face=" << BCondBase<T,D,M,C>::m_face;
}

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

template<class T, unsigned D, class M, class C>
void
BConds<T,D,M,C>::write(std::ostream& o) const
{
253 254


gsell's avatar
gsell committed
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271

  o << "BConds:(" << std::endl;
  const_iterator p=this->begin();
  while (p!=this->end())
    {
      (*p).second->write(o);
      ++p;
      if (p!=this->end())
        o << " , " << std::endl;
      else
          o << std::endl << ")" << std::endl << std::endl;
    }
}

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

template<class T, unsigned D, class M, class C>
272
void
gsell's avatar
gsell committed
273 274
BConds<T,D,M,C>::apply( Field<T,D,M,C>& a )
{
275 276


gsell's avatar
gsell committed
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
  for (iterator p=this->begin(); p!=this->end(); ++p)
    (*p).second->apply(a);
}

template<class T, unsigned D, class M, class C>
bool
BConds<T,D,M,C>::changesPhysicalCells() const
{
  for (const_iterator p=this->begin(); p!=this->end(); ++p)
    if ((*p).second->changesPhysicalCells())
      return true;
  return false;
}

//=============================================================================
// Constructors for PeriodicFace, ExtrapolateFace, FunctionFace classes
// and, now, ComponentFunctionFace
//=============================================================================

template<class T, unsigned D, class M, class C>
PeriodicFace<T,D,M,C>::PeriodicFace(unsigned f, int i, int j)
  : BCondBase<T,D,M,C>(f,i,j)
{
Andreas Adelmann's avatar
for P3M  
Andreas Adelmann committed
300 301 302 303 304 305 306 307 308 309
	//std::cout << "(1) Constructor periodic face called" << std::endl;


}

//BENI adds Interpolation face BC
template<class T, unsigned D, class M, class C>
InterpolationFace<T,D,M,C>::InterpolationFace(unsigned f, int i, int j)
  : BCondBase<T,D,M,C>(f,i,j)
{
310 311


gsell's avatar
gsell committed
312 313 314 315 316 317
}

template<class T, unsigned D, class M, class C>
ExtrapolateFace<T,D,M,C>::ExtrapolateFace(unsigned f, T o, T s, int i, int j)
  : BCondBase<T,D,M,C>(f,i,j), Offset(o), Slope(s)
{
318 319


gsell's avatar
gsell committed
320 321 322 323 324 325 326
}

template<class T, unsigned D, class M, class C>
ExtrapolateAndZeroFace<T,D,M,C>::
ExtrapolateAndZeroFace(unsigned f, T o, T s, int i, int j)
  : BCondBase<T,D,M,C>(f,i,j), Offset(o), Slope(s)
{
uldis_l's avatar
uldis_l committed
327

gsell's avatar
gsell committed
328 329 330 331 332 333 334 335
  BCondBase<T,D,M,C>::m_changePhysical = true;
}

template<class T, unsigned D, class M, class C>
FunctionFace<T,D,M,C>::
FunctionFace(T (*func)(const T&), unsigned face)
  : BCondBase<T,D,M,C>(face), Func(func)
{
336 337


gsell's avatar
gsell committed
338 339 340 341
}

template<class T, unsigned D, class M, class C>
ComponentFunctionFace<T,D,M,C>::
342 343
ComponentFunctionFace(typename ApplyToComponentType<T>::type
		      (*func)( typename ApplyToComponentType<T>::type),
gsell's avatar
gsell committed
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
		      unsigned face, int i, int j)
  : BCondBase<T,D,M,C>(face,i,j), Func(func)
{

  // Disallow specification of all components (default, unfortunately):
  if ( (j == BCondBase<T,D,M,C>::allComponents) &&
       (i == BCondBase<T,D,M,C>::allComponents) )
    ERRORMSG("ComponentFunctionFace(): allComponents specified; not allowed; "
	     << "use FunctionFace class instead." << endl);
}


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

// Applicative templates for PeriodicFace:

// Standard, for applying to all components of elemental type:
// (N.B.: could just use OpAssign, but put this in for clarity and consistency
// with other appliciative templates in this module.)
template<class T>
struct OpPeriodic
{
#ifdef IPPL_PURIFY
  OpPeriodic() {}
  OpPeriodic(const OpPeriodic<T> &) {}
  OpPeriodic<T>& operator=(const OpPeriodic<T> &) { return *this; }
#endif
};
template<class T>
Andreas Adelmann's avatar
for P3M  
Andreas Adelmann committed
373
inline void PETE_apply(const OpPeriodic<T>& e, T& a, const T& b) {a = b; }
gsell's avatar
gsell committed
374 375 376 377 378 379 380 381 382 383 384 385 386

// Special, for applying to single component of multicomponent elemental type:
template<class T>
struct OpPeriodicComponent
{
  OpPeriodicComponent(int c) : Component(c) {}
  int Component;
};

template<class T>
inline void PETE_apply(const OpPeriodicComponent<T>& e, T& a, const T& b)
{ a[e.Component] = b[e.Component]; }

387 388 389 390
// Following specializations are necessary because of the runtime branches in
// code which unfortunately force instantiation of OpPeriodicComponent
// instances for non-multicomponent types like {char,double,...}.
// Note: if user uses non-multicomponent (no operator[]) types of his own,
gsell's avatar
gsell committed
391 392 393 394 395 396 397 398 399 400 401 402
// he'll get a compile error. See comments regarding similar specializations
// for OpExtrapolateComponent for a more details.
COMPONENT_APPLY_BUILTIN(OpPeriodicComponent,char)
COMPONENT_APPLY_BUILTIN(OpPeriodicComponent,bool)
COMPONENT_APPLY_BUILTIN(OpPeriodicComponent,int)
COMPONENT_APPLY_BUILTIN(OpPeriodicComponent,unsigned)
COMPONENT_APPLY_BUILTIN(OpPeriodicComponent,short)
COMPONENT_APPLY_BUILTIN(OpPeriodicComponent,long)
COMPONENT_APPLY_BUILTIN(OpPeriodicComponent,float)
COMPONENT_APPLY_BUILTIN(OpPeriodicComponent,double)
COMPONENT_APPLY_BUILTIN(OpPeriodicComponent,dcomplex)

Andreas Adelmann's avatar
for P3M  
Andreas Adelmann committed
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

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

//----------------------------------------------------------------------------
// For unspecified centering, can't implement PeriodicFace::apply()
// correctly, and can't partial-specialize yet, so... don't have a prototype
// for unspecified centering, so user gets a compile error if he tries to
// invoke it for a centering not yet implemented. Implement external functions
// which are specializations for the various centerings
// {Cell,Vert,CartesianCentering}; these are called from the general
// PeriodicFace::apply() function body.
//----------------------------------------------------------------------------


//BENI: Do the whole operation part with += for Interpolation Boundary Conditions
//////////////////////////////////////////////////////////////////////

// Applicative templates for PeriodicFace:

// Standard, for applying to all components of elemental type:
// (N.B.: could just use OpAssign, but put this in for clarity and consistency
// with other appliciative templates in this module.)
template<class T>
struct OpInterpolation
{
#ifdef IPPL_PURIFY
  OpInterpolation() {}
  OpInterpolation(const OpInterpolation<T> &) {}
  OpInterpolation<T>& operator=(const OpInterpolation<T> &) { return *this; }
#endif
};
template<class T>
inline void PETE_apply(const OpInterpolation<T>& e, T& a, const T& b) {a = a + b; }

// Special, for applying to single component of multicomponent elemental type:
template<class T>
struct OpInterpolationComponent
{
  OpInterpolationComponent(int c) : Component(c) {}
  int Component;
};

template<class T>
inline void PETE_apply(const OpInterpolationComponent<T>& e, T& a, const T& b)
{ a[e.Component] = a[e.Component]+b[e.Component]; }

// Following specializations are necessary because of the runtime branches in
// code which unfortunately force instantiation of OpPeriodicComponent
// instances for non-multicomponent types like {char,double,...}.
// Note: if user uses non-multicomponent (no operator[]) types of his own,
// he'll get a compile error. See comments regarding similar specializations
// for OpExtrapolateComponent for a more details.


COMPONENT_APPLY_BUILTIN(OpInterpolationComponent,char)
COMPONENT_APPLY_BUILTIN(OpInterpolationComponent,bool)
COMPONENT_APPLY_BUILTIN(OpInterpolationComponent,int)
COMPONENT_APPLY_BUILTIN(OpInterpolationComponent,unsigned)
COMPONENT_APPLY_BUILTIN(OpInterpolationComponent,short)
COMPONENT_APPLY_BUILTIN(OpInterpolationComponent,long)
COMPONENT_APPLY_BUILTIN(OpInterpolationComponent,float)
COMPONENT_APPLY_BUILTIN(OpInterpolationComponent,double)
COMPONENT_APPLY_BUILTIN(OpInterpolationComponent,dcomplex)
gsell's avatar
gsell committed
466 467 468
//////////////////////////////////////////////////////////////////////

//----------------------------------------------------------------------------
469
// For unspecified centering, can't implement PeriodicFace::apply()
gsell's avatar
gsell committed
470 471 472
// correctly, and can't partial-specialize yet, so... don't have a prototype
// for unspecified centering, so user gets a compile error if he tries to
// invoke it for a centering not yet implemented. Implement external functions
473 474
// which are specializations for the various centerings
// {Cell,Vert,CartesianCentering}; these are called from the general
gsell's avatar
gsell committed
475 476 477
// PeriodicFace::apply() function body.
//----------------------------------------------------------------------------

Andreas Adelmann's avatar
for P3M  
Andreas Adelmann committed
478

gsell's avatar
gsell committed
479 480 481
template<class T, unsigned D, class M>
void PeriodicFaceBCApply(PeriodicFace<T,D,M,Cell>& pf,
			 Field<T,D,M,Cell>& A );
Andreas Adelmann's avatar
for P3M  
Andreas Adelmann committed
482 483 484 485 486
//BENI adds InterpolationFace ONLY Cell centered implementation!!!
template<class T, unsigned D, class M>
void InterpolationFaceBCApply(InterpolationFace<T,D,M,Cell>& pf,
			 Field<T,D,M,Cell>& A );

gsell's avatar
gsell committed
487 488 489 490 491 492 493 494 495 496 497
template<class T, unsigned D, class M>
void PeriodicFaceBCApply(PeriodicFace<T,D,M,Vert>& pf,
			 Field<T,D,M,Vert>& A );
template<class T, unsigned D, class M, const CenteringEnum* CE, unsigned NC>
void PeriodicFaceBCApply(PeriodicFace<T,D,M,
			 CartesianCentering<CE,D,NC> >& pf,
			 Field<T,D,M,CartesianCentering<CE,D,NC> >& A );

template<class T, unsigned D, class M, class C>
void PeriodicFace<T,D,M,C>::apply( Field<T,D,M,C>& A )
{
498

Andreas Adelmann's avatar
for P3M  
Andreas Adelmann committed
499
	//std::cout << "(2) PeriodicFace::apply" << std::endl;
500

gsell's avatar
gsell committed
501 502
  PeriodicFaceBCApply(*this, A);
}
Andreas Adelmann's avatar
for P3M  
Andreas Adelmann committed
503 504 505 506 507
//BENI adds InterpolationFace
template<class T, unsigned D, class M, class C>
void InterpolationFace<T,D,M,C>::apply( Field<T,D,M,C>& A )
{

gsell's avatar
gsell committed
508

Andreas Adelmann's avatar
for P3M  
Andreas Adelmann committed
509 510
  InterpolationFaceBCApply(*this, A);
}
gsell's avatar
gsell committed
511 512 513 514 515 516 517 518 519

//-----------------------------------------------------------------------------
// Specialization of PeriodicFace::apply() for Cell centering.
// Rather, indirectly-called specialized global function PeriodicFaceBCApply
//-----------------------------------------------------------------------------
template<class T, unsigned D, class M>
void PeriodicFaceBCApply(PeriodicFace<T,D,M,Cell>& pf,
			 Field<T,D,M,Cell>& A )
{
520 521


Andreas Adelmann's avatar
for P3M  
Andreas Adelmann committed
522
	//std::cout << "(3) PeriodicFaceBCApply called" << std::endl;
523
  // NOTE: See the PeriodicFaceBCApply functions below for more
gsell's avatar
gsell committed
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
  // comprehensible comments --TJW

  // Find the slab that is the destination.
  const NDIndex<D>& domain( A.getDomain() );




  NDIndex<D> slab = AddGuardCells(domain,A.getGuardCellSizes());
  unsigned d = pf.getFace()/2;
  int offset;
  if ( pf.getFace() & 1 )
    {
      slab[d] = Index( domain[d].max() + 1, domain[d].max() + A.leftGuard(d) );
      offset = -domain[d].length();
    }
  else
    {
      slab[d] = Index( domain[d].min() - A.leftGuard(d), domain[d].min()-1 );
      offset = domain[d].length();
    }

546
  DEBUGMSG("PeriodicFaceBCApply domain" << domain << " d= " << d << " slab= " << slab[d] << endl);
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

  // Loop over the ones the slab touches.
  typename Field<T,D,M,Cell>::iterator_if fill_i;
  for (fill_i=A.begin_if(); fill_i!=A.end_if(); ++fill_i)
    {
      // Cache some things we will use often below.
      LField<T,D> &fill = *(*fill_i).second;
      const NDIndex<D> &fill_alloc = fill.getAllocated();
      if ( slab.touches( fill_alloc ) )
        {
          // Find what it touches in this LField.
          NDIndex<D> dest = slab.intersect( fill_alloc );

          // Find where that comes from.
          NDIndex<D> src = dest;
          src[d] = src[d] + offset;

          // Loop over the ones that src touches.
          typename Field<T,D,M,Cell>::iterator_if from_i;
          for (from_i=A.begin_if(); from_i!=A.end_if(); ++from_i)
            {
              // Cache a few things.
              LField<T,D> &from = *(*from_i).second;
              const NDIndex<D> &from_owned = from.getOwned();
              const NDIndex<D> &from_alloc = from.getAllocated();
              // If src touches this LField...
              if ( src.touches( from_owned ) )
                {
		  // bfh: Worry about compression ...
		  // If 'fill' is a compressed LField, then writing data into
		  // it via the expression will actually write the value for
		  // all elements of the LField.  We can do the following:
		  //   a) figure out if the 'fill' elements are all the same
		  //      value, if 'from' elements are the same value, if
		  //      the 'fill' elements are the same as the elements
		  //      throughout that LField, and then just do an
		  //      assigment for a single element
		  //   b) just uncompress the 'fill' LField, to make sure we
		  //      do the right thing.
		  // I vote for b).
		  fill.Uncompress();

                  NDIndex<D> from_it = src.intersect( from_alloc );
                  NDIndex<D> fill_it = dest.plugBase( from_it );
                  // Build iterators for the copy...
                  typedef typename LField<T,D>::iterator LFI;
                  LFI lhs = fill.begin(fill_it);
                  LFI rhs = from.begin(from_it);
                  // And do the assignment.
		  // BrickExpression<D,LFI,LFI,OpAssign >(lhs,rhs).apply();
		  if (pf.getComponent() == BCondBase<T,D,M,Cell>::allComponents) {
		    BrickExpression<D,LFI,LFI,OpPeriodic<T> >
		      (lhs,rhs,OpPeriodic<T>()).apply();
		  } else {
		    BrickExpression<D,LFI,LFI,OpPeriodicComponent<T> >
		      (lhs,rhs,OpPeriodicComponent<T>(pf.getComponent())).apply();
		  }
                }
            }
        }
    }
}

Andreas Adelmann's avatar
for P3M  
Andreas Adelmann committed
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
//BENI adds for InterpolationFace
//-----------------------------------------------------------------------------
// Specialization of InterpolationFace::apply() for Cell centering.
// Rather, indirectly-called specialized global function InerpolationFaceBCApply
//-----------------------------------------------------------------------------
template<class T, unsigned D, class M>
void InterpolationFaceBCApply(InterpolationFace<T,D,M,Cell>& pf,
			 Field<T,D,M,Cell>& A )
{

  // NOTE: See the PeriodicFaceBCApply functions below for more
  // comprehensible comments --TJW

  // Find the slab that is the source (BENI: opposite to periodic BC).
  const NDIndex<D>& domain( A.getDomain() );

  NDIndex<D> slab = AddGuardCells(domain,A.getGuardCellSizes());
  unsigned d = pf.getFace()/2;
  int offset;
  if ( pf.getFace() & 1 )
    {
      slab[d] = Index( domain[d].max() + 1, domain[d].max() + A.leftGuard(d) );
      offset = -domain[d].length();
    }
  else
    {
      slab[d] = Index( domain[d].min() - A.leftGuard(d), domain[d].min()-1 );
      offset = domain[d].length();
    }

640
  DEBUGMSG("InterpolationFaceBCApply domain" << domain << " d= " << d << " slab= " << slab[d] << endl);
Andreas Adelmann's avatar
for P3M  
Andreas Adelmann committed
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

  // Loop over the ones the slab touches.
  typename Field<T,D,M,Cell>::iterator_if fill_i;
  for (fill_i=A.begin_if(); fill_i!=A.end_if(); ++fill_i)
    {
      // Cache some things we will use often below.
      LField<T,D> &fill = *(*fill_i).second;
      const NDIndex<D> &fill_alloc = fill.getAllocated();
      if ( slab.touches( fill_alloc ) )
        {
          // Find what it touches in this LField.
          //BENI: The ghost values are the source to be accumulated to the boundaries
		  NDIndex<D> src = slab.intersect( fill_alloc );

          // BENI: destination is the boundary on the other side
          NDIndex<D> dest = src;
          dest[d] = dest[d] + offset;
		 // std::cout << "src = " << src << std::endl;
		 // std::cout << "dest = " << dest << std::endl;


          // Loop over the ones that src touches.
          typename Field<T,D,M,Cell>::iterator_if from_i;
          for (from_i=A.begin_if(); from_i!=A.end_if(); ++from_i)
            {
              // Cache a few things.
              LField<T,D> &from = *(*from_i).second;
              const NDIndex<D> &from_owned = from.getOwned();
              const NDIndex<D> &from_alloc = from.getAllocated();
              // BENI: If destination touches this LField...
              if ( dest.touches( from_owned ) )
                {
		  // bfh: Worry about compression ...
		  // If 'fill' is a compressed LField, then writing data into
		  // it via the expression will actually write the value for
		  // all elements of the LField.  We can do the following:
		  //   a) figure out if the 'fill' elements are all the same
		  //      value, if 'from' elements are the same value, if
		  //      the 'fill' elements are the same as the elements
		  //      throughout that LField, and then just do an
		  //      assigment for a single element
		  //   b) just uncompress the 'fill' LField, to make sure we
		  //      do the right thing.
		  // I vote for b).
		  fill.Uncompress();

                  NDIndex<D> from_it = src.intersect( from_alloc );
                  NDIndex<D> fill_it = dest.plugBase( from_it );
                  // Build iterators for the copy...
                  typedef typename LField<T,D>::iterator LFI;
                  LFI lhs = fill.begin(fill_it);
                  LFI rhs = from.begin(from_it);
                  // And do the assignment.
		  // BrickExpression<D,LFI,LFI,OpAssign >(lhs,rhs).apply();
		  if (pf.getComponent() == BCondBase<T,D,M,Cell>::allComponents) {
			  //std::cout << "TRY to apply OPInterpol" << std::endl;
		    BrickExpression<D,LFI,LFI,OpInterpolation<T> >
		      (lhs,rhs,OpInterpolation<T>()).apply();
		  } else {
		    BrickExpression<D,LFI,LFI,OpInterpolationComponent<T> >
		      (lhs,rhs,OpInterpolationComponent<T>(pf.getComponent())).apply();
		  }
                }
            }
        }
    }
}

gsell's avatar
gsell committed
709 710 711 712 713 714 715 716 717
//-----------------------------------------------------------------------------
// Specialization of PeriodicFace::apply() for Vert centering.
// Rather, indirectly-called specialized global function PeriodicFaceBCApply
//-----------------------------------------------------------------------------
template<class T, unsigned D, class M>
void PeriodicFaceBCApply(PeriodicFace<T,D,M,Vert>& pf,
			 Field<T,D,M,Vert>& A )
{

718 719 720


  // NOTE: See the ExtrapolateFaceBCApply functions below for more
gsell's avatar
gsell committed
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 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
  // comprehensible comments --TJW

  // Find the slab that is the destination.
  const NDIndex<D>& domain( A.getDomain() );
  NDIndex<D> slab = AddGuardCells(domain,A.getGuardCellSizes());
  unsigned d = pf.getFace()/2;
  int offset;
  if ( pf.getFace() & 1 )
    {
      // TJW: this used to say "leftGuard(d)", which I think was wrong:
      slab[d] = Index(domain[d].max(), domain[d].max() + A.rightGuard(d));
      // N.B.: the extra +1 here is what distinguishes this Vert-centered
      // implementation from the Cell-centered one:
      offset = -domain[d].length() + 1;
    }
  else
    {
      slab[d] = Index( domain[d].min() - A.leftGuard(d), domain[d].min()-1 );
      // N.B.: the extra -1 here is what distinguishes this Vert-centered
      // implementation from the Cell-centered one:
      offset = domain[d].length() - 1;
    }

  // Loop over the ones the slab touches.
  typename Field<T,D,M,Vert>::iterator_if fill_i;
  for (fill_i=A.begin_if(); fill_i!=A.end_if(); ++fill_i)
    {
      // Cache some things we will use often below.
      LField<T,D> &fill = *(*fill_i).second;
      const NDIndex<D> &fill_alloc = fill.getAllocated();
      if ( slab.touches( fill_alloc ) )
        {
          // Find what it touches in this LField.
          NDIndex<D> dest = slab.intersect( fill_alloc );

          // Find where that comes from.
          NDIndex<D> src = dest;
          src[d] = src[d] + offset;

          // Loop over the ones that src touches.
          typename Field<T,D,M,Vert>::iterator_if from_i;
          for (from_i=A.begin_if(); from_i!=A.end_if(); ++from_i)
            {
              // Cache a few things.
              LField<T,D> &from = *(*from_i).second;
              const NDIndex<D> &from_owned = from.getOwned();
              const NDIndex<D> &from_alloc = from.getAllocated();
              // If src touches this LField...
              if ( src.touches( from_owned ) )
                {
		  // bfh: Worry about compression ...
		  // If 'fill' is a compressed LField, then writing data into
		  // it via the expression will actually write the value for
		  // all elements of the LField.  We can do the following:
		  //   a) figure out if the 'fill' elements are all the same
		  //      value, if 'from' elements are the same value, if
		  //      the 'fill' elements are the same as the elements
		  //      throughout that LField, and then just do an
		  //      assigment for a single element
		  //   b) just uncompress the 'fill' LField, to make sure we
		  //      do the right thing.
		  // I vote for b).
		  fill.Uncompress();

                  NDIndex<D> from_it = src.intersect( from_alloc );
                  NDIndex<D> fill_it = dest.plugBase( from_it );
                  // Build iterators for the copy...
                  typedef typename LField<T,D>::iterator LFI;
                  LFI lhs = fill.begin(fill_it);
                  LFI rhs = from.begin(from_it);
                  // And do the assignment.
		  // BrickExpression<D,LFI,LFI,OpAssign >(lhs,rhs).apply();
		  if (pf.getComponent() == BCondBase<T,D,M,Vert>::allComponents) {
		    BrickExpression<D,LFI,LFI,OpPeriodic<T> >
		      (lhs,rhs,OpPeriodic<T>()).apply();
		  } else {
		    BrickExpression<D,LFI,LFI,OpPeriodicComponent<T> >
		      (lhs,rhs,OpPeriodicComponent<T>(pf.getComponent())).apply();
		  }
                }
            }
        }
    }
}


//-----------------------------------------------------------------------------
// Specialization of PeriodicFace::apply() for CartesianCentering centering.
// Rather, indirectly-called specialized global function PeriodicFaceBCApply
//-----------------------------------------------------------------------------
template<class T, unsigned D, class M, const CenteringEnum* CE, unsigned NC>
void PeriodicFaceBCApply(PeriodicFace<T,D,M,
			 CartesianCentering<CE,D,NC> >& pf,
			 Field<T,D,M,CartesianCentering<CE,D,NC> >& A )
{

817 818 819


  // NOTE: See the ExtrapolateFaceBCApply functions below for more
gsell's avatar
gsell committed
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
  // comprehensible comments --TJW

  // Find the slab that is the destination.
  const NDIndex<D>& domain( A.getDomain() );
  NDIndex<D> slab = AddGuardCells(domain,A.getGuardCellSizes());
  unsigned d = pf.getFace()/2;
  int offset;
  if ( pf.getFace() & 1 )
    {
      // Do the right thing for CELL or VERT centering for this component (or
      // all components, if the PeriodicFace object so specifies):
      if (pf.getComponent() == BCondBase<T,D,M,CartesianCentering<CE,D,NC> >::
	  allComponents) {
	// Make sure all components are really centered the same, as assumed:
	CenteringEnum centering0 = CE[0 + d*NC]; // 1st component along dir d
	for (int c=1; c<NC; c++) { // Compare other components with 1st
	  if (CE[c + d*NC] != centering0)
	    ERRORMSG("PeriodicFaceBCApply: BCond thinks all components have"
		     << " same centering along direction " << d
		     << ", but it isn't so." << endl);
	}
	// Now do the right thing for CELL or VERT centering of all components:
	if (centering0 == CELL) {
	  offset = -domain[d].length();     // CELL case
	} else {
	  // TJW: this used to say "leftGuard(d)", which I think was wrong:
846
	  slab[d] =
gsell's avatar
gsell committed
847 848 849 850 851 852 853 854
	    Index( domain[d].max(), domain[d].max() + A.rightGuard(d));
	  offset = -domain[d].length()+1; // VERT case
	}
      } else { // The BC applies only to one component, not all:
	// Do the right thing for CELL or VERT centering of the component:
	if (CE[pf.getComponent() + d*NC] == CELL) {
	  offset = -domain[d].length();     // CELL case
	} else {
855
	  slab[d] =
gsell's avatar
gsell committed
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
	    Index( domain[d].max(), domain[d].max() + A.rightGuard(d));
	  offset = -domain[d].length()+1; // VERT case
	}
      }
    }
  else
    {
      slab[d] = Index( domain[d].min() - A.leftGuard(d), domain[d].min()-1 );
      // Do the right thing for CELL or VERT centering for this component (or
      // all components, if the PeriodicFace object so specifies):
      if (pf.getComponent() == BCondBase<T,D,M,CartesianCentering<CE,D,NC> >::
	  allComponents) {
	// Make sure all components are really centered the same, as assumed:
	CenteringEnum centering0 = CE[0 + d*NC]; // 1st component along dir d
	for (int c=1; c<NC; c++) { // Compare other components with 1st
	  if (CE[c + d*NC] != centering0)
	    ERRORMSG("PeriodicFaceBCApply: BCond thinks all components have"
		     << " same centering along direction " << d
		     << ", but it isn't so." << endl);
	}
	// Now do the right thing for CELL or VERT centering of all components:
	if (centering0 == CELL) {
	  offset = -domain[d].length();     // CELL case
	} else {
	  offset = -domain[d].length() + 1; // VERT case
	}
      } else { // The BC applies only to one component, not all:
	// Do the right thing for CELL or VERT centering of the component:
	if (CE[pf.getComponent() + d*NC] == CELL) {
	  offset = domain[d].length();     // CELL case
	} else {
	  offset = domain[d].length() - 1; // VERT case
	}
      }
    }

  // Loop over the ones the slab touches.
  typename Field<T,D,M,CartesianCentering<CE,D,NC> >::iterator_if fill_i;
  for (fill_i=A.begin_if(); fill_i!=A.end_if(); ++fill_i)
    {
      // Cache some things we will use often below.
      LField<T,D> &fill = *(*fill_i).second;
      const NDIndex<D> &fill_alloc = fill.getAllocated();
      if ( slab.touches( fill_alloc ) )
        {
          // Find what it touches in this LField.
          NDIndex<D> dest = slab.intersect( fill_alloc );

          // Find where that comes from.
          NDIndex<D> src = dest;
          src[d] = src[d] + offset;

          // Loop over the ones that src touches.
          typename Field<T,D,M,CartesianCentering<CE,D,NC> >::iterator_if from_i;
          for (from_i=A.begin_if(); from_i!=A.end_if(); ++from_i)
            {
              // Cache a few things.
              LField<T,D> &from = *(*from_i).second;
              const NDIndex<D> &from_owned = from.getOwned();
              const NDIndex<D> &from_alloc = from.getAllocated();
              // If src touches this LField...
              if ( src.touches( from_owned ) )
                {
		  // bfh: Worry about compression ...
		  // If 'fill' is a compressed LField, then writing data into
		  // it via the expression will actually write the value for
		  // all elements of the LField.  We can do the following:
		  //   a) figure out if the 'fill' elements are all the same
		  //      value, if 'from' elements are the same value, if
		  //      the 'fill' elements are the same as the elements
		  //      throughout that LField, and then just do an
		  //      assigment for a single element
		  //   b) just uncompress the 'fill' LField, to make sure we
		  //      do the right thing.
		  // I vote for b).
		  fill.Uncompress();

                  NDIndex<D> from_it = src.intersect( from_alloc );
                  NDIndex<D> fill_it = dest.plugBase( from_it );
                  // Build iterators for the copy...
                  typedef typename LField<T,D>::iterator LFI;
                  LFI lhs = fill.begin(fill_it);
                  LFI rhs = from.begin(from_it);
                  // And do the assignment.
		  // BrickExpression<D,LFI,LFI,OpAssign >(lhs,rhs).apply();
		  if (pf.getComponent() == BCondBase<T,D,M,
		      CartesianCentering<CE,D,NC> >::allComponents) {
		    BrickExpression<D,LFI,LFI,OpPeriodic<T> >
		      (lhs,rhs,OpPeriodic<T>()).apply();
		  } else {
		    BrickExpression<D,LFI,LFI,OpPeriodicComponent<T> >
		      (lhs,rhs,OpPeriodicComponent<T>(pf.getComponent())).apply();
		  }
                }
            }
        }
    }
}


//-----------------------------------------------------------------------------
957
// Specialization of CalcParallelPeriodicDomain for various centerings.
gsell's avatar
gsell committed
958 959 960 961 962 963 964 965 966
// This is the centering-specific code for ParallelPeriodicFace::apply().
//-----------------------------------------------------------------------------

#ifdef PRINT_DEBUG
// For distance.
#  include <iterator.h>
#endif

template <class T, unsigned D, class M>
967
inline void
gsell's avatar
gsell committed
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986
CalcParallelPeriodicDomain(const Field<T,D,M,Cell> &A,
			   const ParallelPeriodicFace<T,D,M,Cell>& pf,
			   NDIndex<D> &dest_slab,
			   int &offset)
{
  // Direction Dim has faces 2*Dim and 2*Dim + 1, so the following
  // expression converts the face index to the direction index.

  unsigned d = pf.getFace()/2;

  const NDIndex<D>& domain(A.getDomain());

  if (pf.getFace() & 1) // Odd ("top" or "right") face
    {
      // The cells that we need to fill start one beyond the last
      // physical cell at the "top" and continue to the last guard
      // cell. Change "dest_slab" to restrict direction "d" to this
      // subdomain.

987
      dest_slab[d] =
gsell's avatar
gsell committed
988 989 990 991 992 993 994 995 996 997 998 999
	Index(domain[d].max() + 1, domain[d].max() + A.leftGuard(d));

      // The offset to the cells that we are going to read; i.e. the
      // read domain will be "dest_slab + offset". This is the number of
      // physical cells in that direction.

      offset = -domain[d].length();
    }
  else // Even ("bottom" or "left") face
    {
      // The cells that we need to fill start with the first guard
      // cell on the bottom and continue up through the cell before
1000
      // the first physical cell.
gsell's avatar
gsell committed
1001

1002
      dest_slab[d] =
gsell's avatar
gsell committed
1003 1004 1005 1006 1007 1008 1009 1010
	Index(domain[d].min() - A.leftGuard(d), domain[d].min()-1);

      // See above.

      offset = domain[d].length();
    }
}

1011
// Note: this does the same thing that PeriodicFace::apply() does, but
gsell's avatar
gsell committed
1012 1013 1014
// I don't think that this is correct.

template <class T, unsigned D, class M>
1015
inline void
gsell's avatar
gsell committed
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
CalcParallelPeriodicDomain(const Field<T,D,M,Vert> &A,
			   const ParallelPeriodicFace<T,D,M,Vert>& pf,
			   NDIndex<D> &dest_slab,
			   int &offset)
{
  // Direction Dim has faces 2*Dim and 2*Dim + 1, so the following
  // expression converts the face index to the direction index.

  const NDIndex<D>& domain(A.getDomain());

  unsigned d = pf.getFace()/2;

  if (pf.getFace() & 1) // Odd ("top" or "right") face
    {
      // A vert-centered periodic field duplicates the boundary
      // point. As a result, the right boundary point is filled from
      // the left boundary point. Thus, the points that we need to fill
      // include the last physical point (domain[d].max()) and the
      // guard points.

1036
      dest_slab[d] =
gsell's avatar
gsell committed
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
	Index(domain[d].max(), domain[d].max() + A.rightGuard(d));

      // The offset to the points that we are going to read; i.e. the
      // read domain will be "dest_slab + offset". This is the number of
      // physical points in that direction.

      offset = -domain[d].length() + 1;
    }
  else // Even ("bottom" or "left") face
    {
      // The points that we need to fill start with the first guard
      // cell on the bottom and continue up through the cell before
1049
      // the first physical cell.
gsell's avatar
gsell committed
1050

1051
      dest_slab[d] =
gsell's avatar
gsell committed
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
	Index(domain[d].min() - A.leftGuard(d), domain[d].min()-1);

      // See above.

      offset = domain[d].length() - 1;
    }
}

// See comments above - vert centering wrong, I think.

template<class T, unsigned D, class M, const CenteringEnum* CE, unsigned NC>
1063
inline void
gsell's avatar
gsell committed
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
CalcParallelPeriodicDomain(const Field<T,D,M,CartesianCentering<CE,D,NC> >& A,
			   const ParallelPeriodicFace<T,D,M,
			           CartesianCentering<CE,D,NC> >& pf,
			   NDIndex<D> &dest_slab,
			   int &offset)
{
  typedef BCondBase<T,D,M,CartesianCentering<CE,D,NC> > BCBase_t;

  // Direction Dim has faces 2*Dim and 2*Dim + 1, so the following
  // expression converts the face index to the direction index.

  const NDIndex<D>& domain(A.getDomain());

  unsigned d = pf.getFace()/2;

  if (pf.getFace() & 1) // Odd ("top" or "right") face
    {
      // For this specialization we need to do the right thing for
      // CELL or VERT centering for the appropriate components of the
      // field. The cells that we need to fill, and the offset to the
      // source cells, depend on the centering.  See below and the
      // comments in the vert and cell versions above.

1087
      if (pf.getComponent() == BCBase_t::allComponents)
gsell's avatar
gsell committed
1088 1089 1090 1091 1092 1093
	{
	  // Make sure all components are really centered the same, as
	  // assumed:

	  CenteringEnum centering0 = CE[0 + d*NC]; // 1st component
	                                           // along dir d
1094 1095
	  for (int c = 1; c < NC; c++)
	    {
gsell's avatar
gsell committed
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
	      // Compare other components with 1st
	      if (CE[c + d*NC] != centering0)
		ERRORMSG("ParallelPeriodicFaceBCApply:"
			 << "BCond thinks all components have"
			 << " same centering along direction " << d
			 << ", but it isn't so." << endl);
	    }

	  // Now do the right thing for CELL or VERT centering of all
	  // components:

	  if (centering0 == CELL) {
	    offset = -domain[d].length();     // CELL case
	  } else {
1110
	    dest_slab[d] =
gsell's avatar
gsell committed
1111 1112 1113 1114
	      Index(domain[d].max(), domain[d].max() + A.leftGuard(d));
	    offset = -domain[d].length() + 1; // VERT case
	  }

1115 1116 1117
	}
      else
	{
gsell's avatar
gsell committed
1118 1119 1120
	  // The BC applies only to one component, not all: Do the
	  // right thing for CELL or VERT centering of the component:

1121
	  if (CE[pf.getComponent() + d*NC] == CELL)
gsell's avatar
gsell committed
1122 1123 1124
	    {
	      offset = -domain[d].length();     // CELL case
	    }
1125
	  else
gsell's avatar
gsell committed
1126
	    {
1127
	      dest_slab[d] =
gsell's avatar
gsell committed
1128 1129 1130 1131 1132 1133 1134 1135 1136
		Index(domain[d].max(), domain[d].max() + A.leftGuard(d));
	      offset = -domain[d].length() + 1; // VERT case
	    }
	}
    }
  else // Even ("bottom" or "left") face
    {
      // The cells that we need to fill start with the first guard
      // cell on the bottom and continue up through the cell before
1137
      // the first physical cell.
gsell's avatar
gsell committed
1138

1139
      dest_slab[d] =
gsell's avatar
gsell committed
1140 1141 1142 1143
	Index(domain[d].min() - A.leftGuard(d), domain[d].min()-1);

      // See above.

1144
      if (pf.getComponent() == BCBase_t::allComponents)
gsell's avatar
gsell committed
1145 1146 1147
	{
	  // Make sure all components are really centered the same, as
	  // assumed:
1148

gsell's avatar
gsell committed
1149 1150
	  CenteringEnum centering0 = CE[0 + d*NC]; // 1st component
	                                           // along dir d
1151
	  for (int c = 1; c < NC; c++)
gsell's avatar
gsell committed
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
	    { // Compare other components with 1st
	      if (CE[c + d*NC] != centering0)
		ERRORMSG("ParallelPeriodicFaceBCApply:"
			 << "BCond thinks all components have"
			 << " same centering along direction " << d
			 << ", but it isn't so." << endl);
	    }

	  // Now do the right thing for CELL or VERT centering of all
	  // components:

	  if (centering0 == CELL) {
	    offset = -domain[d].length();     // CELL case
	  } else {
	    offset = -domain[d].length() + 1; // VERT case
	  }

	}
1170 1171
      else
	{
gsell's avatar
gsell committed
1172 1173 1174
	  // The BC applies only to one component, not all: Do the
	  // right thing for CELL or VERT centering of the component:

1175
	  if (CE[pf.getComponent() + d*NC] == CELL)
gsell's avatar
gsell committed
1176 1177
	    {
	      offset = domain[d].length();     // CELL case
1178 1179
	    }
	  else
gsell's avatar
gsell committed
1180 1181 1182 1183 1184 1185 1186 1187
	    {
	      offset = domain[d].length() - 1; // VERT case
	    }
	}
    }
}

//-----------------------------------------------------------------------------
1188
// ParallelPeriodicFace::apply()
gsell's avatar
gsell committed
1189 1190 1191 1192 1193 1194 1195
// Apply the periodic boundary condition. This version can handle
// fields that are parallel in the periodic direction. Unlike the
// other BCond types, the Lion's share of the code is in this single
// apply() method. The only centering-specific calculation is that of
// the destination domain and the offset, and that is separated out
// into the CalcParallelPeriodicDomain functions defined above.
//-----------------------------------------------------------------------------
Andreas Adelmann's avatar
for P3M  
Andreas Adelmann committed
1196
//#define PRINT_DEBUG
gsell's avatar
gsell committed
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
template<class T, unsigned D, class M, class C>
void ParallelPeriodicFace<T,D,M,C>::apply( Field<T,D,M,C>& A )
{

#ifdef PRINT_DEBUG
  Inform msg("PPeriodicBC", INFORM_ALL_NODES);
#endif


  // Useful typedefs:

  typedef T                   Element_t;
  typedef NDIndex<D>          Domain_t;
  typedef LField<T,D>         LField_t;
  typedef typename LField_t::iterator  LFI_t;
  typedef Field<T,D,M,C>      Field_t;
  typedef FieldLayout<D>      Layout_t;

  //===========================================================================
  //
  // Unlike most boundary conditions, periodic BCs are (in general)
  // non-local. Indeed, they really are identical to the guard-cell
  // seams between LFields internal to the Field. In this case the
  // LFields just have a periodic geometry, but the FieldLayout
  // doesn't express this, so we duplicate the code, which is quite
  // similar to fillGuardCellsr, but somewhat more complicated, here.
  // The complications arise from three sources:
  //
  //  - The source and destination domains are offset, not overlapping.
  //  - Only a subset of all LFields are, in general, involved.
  //  - The corners must be handled correctly.
1228
  //
gsell's avatar
gsell committed
1229
  // Here's the plan:
1230
  //
gsell's avatar
gsell committed
1231 1232 1233 1234 1235 1236
  //  0. Calculate source and destination domains.
  //  1. Build send and receive lists, and send messages.
  //  2. Evaluate local pieces directly.
  //  3. Receive messages and evaluate remaining pieces.
  //
  //===========================================================================
Andreas Adelmann's avatar
for P3M  
Andreas Adelmann committed
1237
/*
gsell's avatar
gsell committed
1238
#ifdef PRINT_DEBUG
1239
  msg << "Starting BC Calculation for face "
gsell's avatar
gsell committed
1240 1241
      << getFace() << "." << endl;
#endif
Andreas Adelmann's avatar
for P3M  
Andreas Adelmann committed
1242
*/
gsell's avatar
gsell committed
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
  //===========================================================================
  //  0. Calculate destination domain and the offset.
  //===========================================================================

  // Find the slab that is the destination. First get the whole
  // domain, including guard cells, and then restrict it to the area
  // that this BC will fill.

  const NDIndex<D>& domain(A.getDomain());

  NDIndex<D> dest_slab = AddGuardCells(domain,A.getGuardCellSizes());

  // Direction Dim has faces 2*Dim and 2*Dim + 1, so the following
  // expression converts the face index to the direction index.

  unsigned d = this->getFace()/2;

  int offset;

  CalcParallelPeriodicDomain(A,*this,dest_slab,offset);

  Domain_t src_slab = dest_slab;
  src_slab[d] = src_slab[d] + offset;

#ifdef PRINT_DEBUG
  msg << "dest_slab = " << dest_slab << endl;
  msg << "src_slab  = " << src_slab  << endl;
  //  stop_here();
#endif


  //===========================================================================
  //  1. Build send and receive lists and send messages
  //===========================================================================

  // Declare these at this scope so that we don't have to duplicate
  // the local code. (fillguardcells puts these in the scope of the
1280
  // "if (nprocs > 1) { ... }" section, but has to duplicate the
gsell's avatar
gsell committed
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
  // code for the local fills as a result. The cost of this is a bit
  // of stackspace, and the cost of allocating an empty map.)

  // Container for holding Domain -> LField mapping
  // so that we can sort out which messages go where.

  typedef std::multimap<Domain_t,LField_t*, std::less<Domain_t> > ReceiveMap_t;

  // (Time this since it allocates an empty map.)

1291

gsell's avatar
gsell committed
1292 1293 1294

  ReceiveMap_t receive_map;

1295

gsell's avatar
gsell committed
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312

  // Number of nodes that will send us messages.

  int receive_count = 0;
  int send_count = 0;

  // Communications tag

  int bc_comm_tag;


  // Next fill the dest_list and src_list, lists of the LFields that
  // touch the destination and source domains, respectively.

  // (Do we need this for local-only code???)

  // (Also, if a domain ends up in both lists, it will only be
1313
  // involved in local communication. We should structure this code to
gsell's avatar
gsell committed
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
  // take advantage of this, otherwise all existing parallel code is
  // going to incur additional overhead that really is unnecessary.)
  // (In other words, we should be able to do the general case, but
  // this capability shouldn't slow down the typical cases too much.)

  typedef std::vector<LField_t*> DestList_t;
  typedef std::vector<LField_t*> SrcList_t;
  typedef typename DestList_t::iterator DestListIterator_t;
  typedef typename SrcList_t::iterator SrcListIterator_t;

  DestList_t dest_list;
  SrcList_t src_list;

  dest_list.reserve(1);
  src_list.reserve(1);

  typename Field_t::iterator_if lf_i;

#ifdef PRINT_DEBUG
  msg << "Starting dest & src domain calculation." << endl;
#endif

  for (lf_i = A.begin_if(); lf_i != A.end_if(); ++lf_i)
    {
      LField_t &lf = *lf_i->second;

1340
      // We fill if our allocated domain touches the
gsell's avatar
gsell committed
1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
      // destination slab.

      const Domain_t &lf_allocated = lf.getAllocated();

#ifdef PRINT_DEBUG
      msg << "  Processing subdomain : " << lf_allocated << endl;
      //      stop_here();
#endif

      if (lf_allocated.touches(dest_slab))
	dest_list.push_back(&lf);

      // We only provide data if our owned cells touch
      // the source slab (although we actually send the
1355
      // allocated data).
gsell's avatar
gsell committed
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

      const Domain_t &lf_owned = lf.getOwned();

      if (lf_owned.touches(src_slab))
	src_list.push_back(&lf);
    }

#ifdef PRINT_DEBUG
  msg << "  dest_list has " << dest_list.size() << " elements." << endl;
  msg << "  src_list has " << src_list.size() << " elements." << endl;
#endif

  DestListIterator_t dest_begin = dest_list.begin();
  DestListIterator_t dest_end   = dest_list.end();
  SrcListIterator_t src_begin  = src_list.begin();
  SrcListIterator_t src_end    = src_list.end();

  // Aliases to some of Field A's properties...

  const Layout_t &layout      = A.getLayout();
  const GuardCellSizes<D> &gc = A.getGuardCellSizes();

  int nprocs = Ippl::getNodes();

  if (nprocs > 1) // Skip send/receive code if we're single-processor.
    {
1382

gsell's avatar
gsell committed
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398

#ifdef PRINT_DEBUG
      msg << "Starting receive calculation." << endl;
      //      stop_here();
#endif

      //---------------------------------------------------
      // Receive calculation
      //---------------------------------------------------

      // Mask indicating the nodes will send us messages.

      std::vector<bool> receive_mask(nprocs,false);

      DestListIterator_t dest_i;

1399
      for (dest_i = dest_begin; dest_i != dest_end; ++dest_i)
gsell's avatar
gsell committed
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
        {
          // Cache some information about this local array.

          LField_t &dest_lf = **dest_i;

          const Domain_t &dest_lf_alloc = dest_lf.getAllocated();

	  // Calculate the destination domain in this LField, and the
	  // source domain (which may be spread across multipple
	  // processors) from whence that domain will be filled:

	  const Domain_t dest_domain = dest_lf_alloc.intersect(dest_slab);

	  Domain_t src_domain = dest_domain;
	  src_domain[d] = src_domain[d] + offset;

          // Find the remote LFields that contain src_domain. Note
          // that we have to fill from the full allocated domains in
          // order to properly fill the corners of the boundary cells,
          // BUT we only need to intersect with the physical domain.
          // Intersecting the allocated domain would result in
          // unnecessary messages. (In fact, only the corners *need* to
          // send the allocated domains, but for regular decompositions,
          // sending the allocated domains will result in fewer
          // messages [albeit larger ones] than sending only from
          // physical cells.)

          typename Layout_t::touch_range_dv
            src_range(layout.touch_range_rdv(src_domain));

	  // src_range is a begin/end pair into a list of remote
	  // domain/vnode pairs whose physical domains touch
	  // src_domain. Iterate through this list and set up the
	  // receive map and the receive mask.

          typename Layout_t::touch_iterator_dv rv_i;

1437
          for (rv_i = src_range.first; rv_i != src_range.second; ++rv_i)
gsell's avatar
gsell committed
1438
            {
1439 1440
              // Intersect src_domain with the allocated cells for the
	      // remote LField (rv_alloc). This will give us the strip
gsell's avatar
gsell committed
1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481
	      // that will be sent. Translate this domain back to the
	      // domain of the receiving LField.

	      const Domain_t rv_alloc = AddGuardCells(rv_i->first,gc);

              Domain_t hit = src_domain.intersect(rv_alloc);
	      hit[d] = hit[d] - offset;

	      // Save this domain and the LField pointer

              typedef typename ReceiveMap_t::value_type value_type;

              receive_map.insert(value_type(hit,&dest_lf));

#ifdef PRINT_DEBUG
	      msg << "  Need remote data for domain: " << hit << endl;
#endif

              // Note who will be sending this data

              int rnode = rv_i->second->getNode();

              receive_mask[rnode] = true;

            } // rv_i
	} // dest_i

      receive_count = 0;

      for (int iproc = 0; iproc < nprocs; ++iproc)
	if (receive_mask[iproc]) ++receive_count;


#ifdef PRINT_DEBUG
      msg << "  Expecting to see " << receive_count << " messages." << endl;
      msg << "Done with receive calculation." << endl;
      //      stop_here();
#endif



1482 1483


gsell's avatar
gsell committed
1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501

#ifdef PRINT_DEBUG
      msg << "Starting send calculation" << endl;
#endif

      //---------------------------------------------------
      // Send calculation
      //---------------------------------------------------

      // Array of messages to be sent.

      std::vector<Message *> messages(nprocs);
      for (int miter=0; miter < nprocs; messages[miter++] = 0);

      // Debugging info.

#ifdef PRINT_DEBUG
      // KCC 3.2d has trouble with this. 3.3 doesn't, but
1502
      // some are still using 3.2.
gsell's avatar
gsell committed
1503 1504 1505 1506 1507 1508 1509
      //      vector<int> ndomains(nprocs,0);
      std::vector<int> ndomains(nprocs);
      for(int i = 0; i < nprocs; ++i) ndomains[i] = 0;
#endif

      SrcListIterator_t src_i;

1510
      for (src_i = src_begin; src_i != src_end; ++src_i)
gsell's avatar
gsell committed
1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553
        {
          // Cache some information about this local array.

          LField_t &src_lf = **src_i;

	  // We need to send the allocated data to properly fill the
	  // corners when using periodic BCs in multipple dimensions.
	  // However, we don't want to send to nodes that only would
	  // receive data from our guard cells. Thus we do the
	  // intersection test with our owned data.

          const Domain_t &src_lf_owned = src_lf.getOwned();
	  const Domain_t &src_lf_alloc = src_lf.getAllocated();

	  // Calculate the owned and allocated parts of the source
	  // domain in this LField, and corresponding destination
	  // domains.

	  const Domain_t src_owned = src_lf_owned.intersect(src_slab);
	  const Domain_t src_alloc = src_lf_alloc.intersect(src_slab);

	  Domain_t dest_owned = src_owned;
	  dest_owned[d] = dest_owned[d] - offset;

	  Domain_t dest_alloc = src_alloc;
	  dest_alloc[d] = dest_alloc[d] - offset;

#ifdef PRINT_DEBUG
	  msg << "  Considering LField with the domains:" << endl;
	  msg << "     owned = " << src_lf_owned << endl;
	  msg << "     alloc = " << src_lf_alloc << endl;
	  msg << "  The intersections with src_slab are:" << endl;
	  msg << "     owned = " << src_owned << endl;
	  msg << "     alloc = " << src_alloc << endl;
#endif

          // Find the remote LFields whose allocated cells (note the
	  // additional "gc" arg) are touched by dest_owned.

          typename Layout_t::touch_range_dv
            dest_range(layout.touch_range_rdv(dest_owned,gc));

          typename Layout_t::touch_iterator_dv rv_i;
Andreas Adelmann's avatar
for P3M  
Andreas Adelmann committed
1554
/*
gsell's avatar
gsell committed
1555 1556 1557 1558 1559
#ifdef PRINT_DEBUG
	  msg << "  Touch calculation found "
	      << distance(dest_range.first, dest_range.second)
	      << " elements." << endl;
#endif
Andreas Adelmann's avatar
for P3M  
Andreas Adelmann committed
1560
*/
1561 1562

          for (rv_i = dest_range.first; rv_i != dest_range.second; ++rv_i)
gsell's avatar
gsell committed
1563
            {
1564
              // Find the intersection of the returned domain with the
gsell's avatar
gsell committed
1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592
	      // allocated version of the translated source domain.