PartBunchBase.hpp 62.6 KB
Newer Older
1 2 3
#ifndef PART_BUNCH_BASE_HPP
#define PART_BUNCH_BASE_HPP

frey_m's avatar
frey_m committed
4 5
#include <numeric>

frey_m's avatar
frey_m committed
6 7
#include "Distribution/Distribution.h"

8
#include "AbstractObjects/OpalData.h"   // OPAL file
9
#include "Physics/Physics.h"
10
#include "Utilities/OpalException.h"
11
#include "Utilities/Options.h"
12
#include "Utilities/SwitcherError.h"
13 14 15
#include "Utilities/Util.h"

extern Inform *gmsg;
16 17 18

template <class T, unsigned Dim>
PartBunchBase<T, Dim>::PartBunchBase(AbstractParticle<T, Dim>* pb)
19
    : R(*(pb->R_p)),
20 21 22 23 24 25 26 27
      ID(*(pb->ID_p)),
      myNode_m(Ippl::myNode()),
      nodes_m(Ippl::getNodes()),
      fixed_grid(false),
      pbin_m(nullptr),
      lossDs_m(nullptr),
      pmsg_m(nullptr),
      f_stream(nullptr),
28
      lowParticleCount_m(false),
29 30 31 32 33 34 35 36
//       reference(ref), //FIXME
      unit_state_(units),
      stateOfLastBoundP_(unitless),
      moments_m(),
      dt_m(0.0),
      t_m(0.0),
      eKin_m(0.0),
      dE_m(0.0),
37
      spos_m(0.0),
38 39
      globalMeanR_m(Vector_t(0.0, 0.0, 0.0)),
      globalToLocalQuaternion_m(Quaternion_t(1.0, 0.0, 0.0, 0.0)),
40 41 42 43 44 45 46 47
      rmax_m(0.0),
      rmin_m(0.0),
      rrms_m(0.0),
      prms_m(0.0),
      rmean_m(0.0),
      pmean_m(0.0),
      eps_m(0.0),
      eps_norm_m(0.0),
48
      halo_m(Vector_t(0.0, 0.0, 0.0)),
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
      rprms_m(0.0),
      Dx_m(0.0),
      Dy_m(0.0),
      DDx_m(0.0),
      DDy_m(0.0),
      hr_m(-1.0),
      nr_m(0),
      fs_m(nullptr),
      couplingConstant_m(0.0),
      qi_m(0.0),
      distDump_m(0),
      fieldDBGStep_m(0),
      dh_m(1e-12),
      tEmission_m(0.0),
      bingamma_m(nullptr),
      binemitted_m(nullptr),
      stepsPerTurn_m(0),
      localTrackStep_m(0),
      globalTrackStep_m(0),
      numBunch_m(1),
frey_m's avatar
frey_m committed
69 70
      bunchTotalNum_m(1),
      bunchLocalNum_m(1),
71 72 73 74
      SteptoLastInj_m(0),
      globalPartPerNode_m(nullptr),
      dist_m(nullptr),
      dcBeam_m(false),
75
      periodLength_m(Physics::c / 1e9),
76
      pbase(pb)
77
{
frey_m's avatar
frey_m committed
78
    setup(pb);
79

80
    boundpTimer_m = IpplTimings::getTimer("Boundingbox");
81 82
    boundpBoundsTimer_m = IpplTimings::getTimer("Boundingbox-bounds");
    boundpUpdateTimer_m = IpplTimings::getTimer("Boundingbox-update");
83

84 85 86 87 88 89 90
    statParamTimer_m = IpplTimings::getTimer("Compute Statistics");
    selfFieldTimer_m = IpplTimings::getTimer("SelfField total");

    histoTimer_m = IpplTimings::getTimer("Histogram");

    distrCreate_m = IpplTimings::getTimer("Create Distr");
    distrReload_m = IpplTimings::getTimer("Load Distr");
91

92 93 94 95 96 97 98 99 100 101 102 103 104
    globalPartPerNode_m = std::unique_ptr<size_t[]>(new size_t[Ippl::getNodes()]);

    lossDs_m = std::unique_ptr<LossDataSink>(new LossDataSink(std::string("GlobalLosses"), !Options::asciidump));

    pmsg_m.release();
    //    f_stream.release();
    /*
      if(Ippl::getNodes() == 1) {
          f_stream = std::unique_ptr<ofstream>(new ofstream);
          f_stream->open("data/dist.dat", ios::out);
          pmsg_m = std::unique_ptr<Inform>(new Inform(0, *f_stream, 0));
      }
    */
105 106 107
}

template <class T, unsigned Dim>
frey_m's avatar
frey_m committed
108
PartBunchBase<T, Dim>::PartBunchBase(AbstractParticle<T, Dim>* pb, const PartData *ref)
109
    : PartBunchBase(pb)
110
{
111
    reference = ref;
112
}
113 114 115 116 117 118 119

/*
 * Bunch common member functions
 */

template <class T, unsigned Dim>
bool PartBunchBase<T, Dim>::getIfBeamEmitting() {
120 121 122 123 124 125 126 127 128 129 130 131
    if (dist_m != NULL) {
        size_t isBeamEmitted = dist_m->getIfDistEmitting();
        reduce(isBeamEmitted, isBeamEmitted, OpAddAssign());
        if (isBeamEmitted > 0)
            return true;
        else
            return false;
    } else
        return false;
}


132 133
template <class T, unsigned Dim>
int PartBunchBase<T, Dim>::getLastEmittedEnergyBin() {
134 135 136 137 138 139 140 141 142
    /*
     * Get maximum last emitted energy bin.
     */
    int lastEmittedBin = dist_m->getLastEmittedEnergyBin();
    reduce(lastEmittedBin, lastEmittedBin, OpMaxAssign());
    return lastEmittedBin;
}


143 144
template <class T, unsigned Dim>
size_t PartBunchBase<T, Dim>::getNumberOfEmissionSteps() {
145 146 147 148
    return dist_m->getNumberOfEmissionSteps();
}


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 214 215 216
template <class T, unsigned Dim>
int PartBunchBase<T, Dim>::getNumberOfEnergyBins() {
    return dist_m->getNumberOfEnergyBins();
}


template <class T, unsigned Dim>
void PartBunchBase<T, Dim>::Rebin() {

    size_t isBeamEmitting = dist_m->getIfDistEmitting();
    reduce(isBeamEmitting, isBeamEmitting, OpAddAssign());
    if (isBeamEmitting > 0) {
        *gmsg << "*****************************************************" << endl
              << "Warning: attempted to rebin, but not all distribution" << endl
              << "particles have been emitted. Rebin failed." << endl
              << "*****************************************************" << endl;
    } else {
        if (dist_m->Rebin())
            this->Bin = 0;
    }
}


template <class T, unsigned Dim>
void PartBunchBase<T, Dim>::setEnergyBins(int numberOfEnergyBins) {
    bingamma_m = std::unique_ptr<double[]>(new double[numberOfEnergyBins]);
    binemitted_m = std::unique_ptr<size_t[]>(new size_t[numberOfEnergyBins]);
    for(int i = 0; i < numberOfEnergyBins; i++)
        binemitted_m[i] = 0;
}


template <class T, unsigned Dim>
bool PartBunchBase<T, Dim>::weHaveEnergyBins() {

    if (dist_m != NULL)
        return dist_m->getNumberOfEnergyBins() > 0;
    else
        return false;
}


template <class T, unsigned Dim>
void PartBunchBase<T, Dim>::switchToUnitlessPositions(bool use_dt_per_particle) {

    if(unit_state_ == unitless)
        throw SwitcherError("PartBunch::switchToUnitlessPositions",
                            "Cannot make a unitless PartBunch unitless");

    bool hasToReset = false;
    if(!R.isDirty()) hasToReset = true;

    for(size_t i = 0; i < getLocalNum(); i++) {
        double dt = getdT();
        if(use_dt_per_particle)
            dt = this->dt[i];

        R[i] /= Vector_t(Physics::c * dt);
    }

    unit_state_ = unitless;

    if(hasToReset) R.resetDirtyFlag();
}


//FIXME: unify methods, use convention that all particles have own dt
template <class T, unsigned Dim>
217
void PartBunchBase<T, Dim>::switchOffUnitlessPositions(bool use_dt_per_particle) {
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241

    if(unit_state_ == units)
        throw SwitcherError("PartBunch::switchOffUnitlessPositions",
                            "Cannot apply units twice to PartBunch");

    bool hasToReset = false;
    if(!R.isDirty()) hasToReset = true;

    for(size_t i = 0; i < getLocalNum(); i++) {
        double dt = getdT();
        if(use_dt_per_particle)
            dt = this->dt[i];

        R[i] *= Vector_t(Physics::c * dt);
    }

    unit_state_ = units;

    if(hasToReset) R.resetDirtyFlag();
}


template <class T, unsigned Dim>
void PartBunchBase<T, Dim>::do_binaryRepart() {
frey_m's avatar
frey_m committed
242
    // do nothing here
243 244 245 246 247 248
}


template <class T, unsigned Dim>
void PartBunchBase<T, Dim>::setDistribution(Distribution *d,
                                            std::vector<Distribution *> addedDistributions,
249
                                            size_t &np)
250 251 252 253
{
    Inform m("setDistribution " );
    dist_m = d;

254
    dist_m->createOpalT(this, addedDistributions, np);
255 256

//    if (Options::cZero)
257
//        dist_m->create(this, addedDistributions, np / 2);
258
//    else
259
//        dist_m->create(this, addedDistributions, np);
260 261 262 263
}


template <class T, unsigned Dim>
264
bool PartBunchBase<T, Dim>::isGridFixed() const {
265 266 267 268
    return fixed_grid;
}


269
template <class T, unsigned Dim>
270
bool PartBunchBase<T, Dim>::hasBinning() const {
271 272 273 274
    return (pbin_m != nullptr);
}


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
template <class T, unsigned Dim>
void PartBunchBase<T, Dim>::setTEmission(double t) {
    tEmission_m = t;
}


template <class T, unsigned Dim>
double PartBunchBase<T, Dim>::getTEmission() {
    return tEmission_m;
}


template <class T, unsigned Dim>
bool PartBunchBase<T, Dim>::doEmission() {
    if (dist_m != NULL)
        return dist_m->getIfDistEmitting();
    else
        return false;
}


template <class T, unsigned Dim>
bool PartBunchBase<T, Dim>::weHaveBins() const {

    if(pbin_m != NULL)
        return pbin_m->weHaveBins();
    else
        return false;
}


template <class T, unsigned Dim>
void PartBunchBase<T, Dim>::setPBins(PartBins *pbin) {
    pbin_m = pbin;
    *gmsg << *pbin_m << endl;
    setEnergyBins(pbin_m->getNBins());
}


template <class T, unsigned Dim>
void PartBunchBase<T, Dim>::setPBins(PartBinsCyc *pbin) {
    pbin_m = pbin;
    setEnergyBins(pbin_m->getNBins());
}


template <class T, unsigned Dim>
size_t PartBunchBase<T, Dim>::emitParticles(double eZ) {
frey_m's avatar
frey_m committed
323
    return dist_m->emitParticles(this, eZ);
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
}


template <class T, unsigned Dim>
void PartBunchBase<T, Dim>::updateNumTotal() {
    size_t numParticles = getLocalNum();
    reduce(numParticles, numParticles, OpAddAssign());
    setTotalNum(numParticles);
}


template <class T, unsigned Dim>
void PartBunchBase<T, Dim>::rebin() {
    this->Bin = 0;
    pbin_m->resetBins();
    // delete pbin_m; we did not allocate it!
    pbin_m = NULL;
}


template <class T, unsigned Dim>
int PartBunchBase<T, Dim>::getNumBins() {
    if(pbin_m != NULL)
        return pbin_m->getNBins();
    else
        return 0;
}


template <class T, unsigned Dim>
int PartBunchBase<T, Dim>::getLastemittedBin() {
    if(pbin_m != NULL)
        return pbin_m->getLastemittedBin();
    else
        return 0;
}


362 363 364 365 366 367 368 369
template <class T, unsigned Dim>
void PartBunchBase<T, Dim>::setLocalBinCount(size_t num, int bin) {
    if(pbin_m != NULL) {
        pbin_m->setPartNum(bin, num);
    }
}


370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
template <class T, unsigned Dim>
void PartBunchBase<T, Dim>::calcGammas() {

    const int emittedBins = dist_m->getNumberOfEnergyBins();

    size_t s = 0;

    for(int i = 0; i < emittedBins; i++)
        bingamma_m[i] = 0.0;

    for(unsigned int n = 0; n < getLocalNum(); n++)
        bingamma_m[this->Bin[n]] += sqrt(1.0 + dot(this->P[n], this->P[n]));

    std::unique_ptr<size_t[]> particlesInBin(new size_t[emittedBins]);
    reduce(bingamma_m.get(), bingamma_m.get() + emittedBins, bingamma_m.get(), OpAddAssign());
    reduce(binemitted_m.get(), binemitted_m.get() + emittedBins, particlesInBin.get(), OpAddAssign());
    for(int i = 0; i < emittedBins; i++) {
        size_t &pInBin = particlesInBin[i];
        if(pInBin != 0) {
            bingamma_m[i] /= pInBin;
            INFOMSG(level2 << "Bin " << std::setw(3) << i
                           << " gamma = " << std::setw(8) << std::scientific
                           << std::setprecision(5) << bingamma_m[i]
                           << "; NpInBin= " << std::setw(8)
                           << std::setfill(' ') << pInBin << endl);
        } else {
            bingamma_m[i] = 1.0;
            INFOMSG(level2 << "Bin " << std::setw(3) << i << " has no particles " << endl);
        }
        s += pInBin;
    }
    particlesInBin.reset();


    if(s != getTotalNum() && !OpalData::getInstance()->hasGlobalGeometry())
        ERRORMSG("sum(Bins)= " << s << " != sum(R)= " << getTotalNum() << endl;);

    if(emittedBins >= 2) {
        for(int i = 1; i < emittedBins; i++) {
            if(binemitted_m[i - 1] != 0 && binemitted_m[i] != 0)
                INFOMSG(level2 << "d(gamma)= " << 100.0 * std::abs(bingamma_m[i - 1] - bingamma_m[i]) / bingamma_m[i] << " [%] "
                        << "between bin " << i - 1 << " and " << i << endl);
        }
    }
}


template <class T, unsigned Dim>
void PartBunchBase<T, Dim>::calcGammas_cycl() {

    const int emittedBins = pbin_m->getLastemittedBin();

    for(int i = 0; i < emittedBins; i++)
        bingamma_m[i] = 0.0;
424 425 426
    for(unsigned int n = 0; n < getLocalNum(); n++) {
        if ( this->Bin[n] > -1 ) {
            bingamma_m[this->Bin[n]] += sqrt(1.0 + dot(this->P[n], this->P[n]));
kraus's avatar
kraus committed
427
        }
428
    }
frey_m's avatar
frey_m committed
429 430 431

    allreduce(*bingamma_m.get(), emittedBins, std::plus<double>());

432 433 434 435 436
    for(int i = 0; i < emittedBins; i++) {
        if(pbin_m->getTotalNumPerBin(i) > 0)
            bingamma_m[i] /= pbin_m->getTotalNumPerBin(i);
        else
            bingamma_m[i] = 0.0;
frey_m's avatar
frey_m committed
437 438
        INFOMSG("Bin " << i << " : particle number = " << pbin_m->getTotalNumPerBin(i)
                       << " gamma = " << bingamma_m[i] << endl);
439 440 441 442 443 444 445 446 447 448 449 450 451
    }

}


template <class T, unsigned Dim>
double PartBunchBase<T, Dim>::getBinGamma(int bin) {
    return bingamma_m[bin];
}


template <class T, unsigned Dim>
void PartBunchBase<T, Dim>::setBinCharge(int bin, double q) {
452
  this->Q = where(eq(this->Bin, bin), q, 0.0);
453 454 455 456 457
}


template <class T, unsigned Dim>
void PartBunchBase<T, Dim>::setBinCharge(int bin) {
458
  this->Q = where(eq(this->Bin, bin), this->qi_m, 0.0);
459 460 461 462 463 464
}


template <class T, unsigned Dim>
size_t PartBunchBase<T, Dim>::calcNumPartsOutside(Vector_t x) {

frey_m's avatar
frey_m committed
465
    std::size_t localnum = 0;
466 467 468
    const Vector_t meanR = get_rmean();

    for(unsigned long k = 0; k < getLocalNum(); ++ k)
469 470 471
        if (std::abs(R[k](0) - meanR(0)) > x(0) ||
            std::abs(R[k](1) - meanR(1)) > x(1) ||
            std::abs(R[k](2) - meanR(2)) > x(2)) {
472

frey_m's avatar
frey_m committed
473
            ++localnum;
474
        }
475

frey_m's avatar
frey_m committed
476
    gather(&localnum, &globalPartPerNode_m[0], 1);
477

frey_m's avatar
frey_m committed
478 479 480
    size_t npOutside = std::accumulate(globalPartPerNode_m.get(),
                                       globalPartPerNode_m.get() + Ippl::getNodes(), 0,
                                       std::plus<size_t>());
481

frey_m's avatar
frey_m committed
482
    return npOutside;
483 484 485
}


486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
/**
 * \method calcLineDensity()
 * \brief calculates the 1d line density (not normalized) and append it to a file.
 * \see ParallelTTracker
 * \warning none yet
 *
 * DETAILED TODO
 *
 */
template <class T, unsigned Dim>
void PartBunchBase<T, Dim>::calcLineDensity(unsigned int nBins,
                                            std::vector<double> &lineDensity,
                                            std::pair<double, double> &meshInfo)
{
    Vector_t rmin, rmax;
    get_bounds(rmin, rmax);

    if (nBins < 2) {
frey_m's avatar
frey_m committed
504
        Vektor<int, 3>/*NDIndex<3>*/ grid;
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
        this->updateDomainLength(grid);
        nBins = grid[2];
    }

    double length = rmax(2) - rmin(2);
    double zmin = rmin(2) - dh_m * length, zmax = rmax(2) + dh_m * length;
    double hz = (zmax - zmin) / (nBins - 2);
    double perMeter = 1.0 / hz;//(zmax - zmin);
    zmin -= hz;

    lineDensity.resize(nBins, 0.0);
    std::fill(lineDensity.begin(), lineDensity.end(), 0.0);

    const unsigned int lN = getLocalNum();
    for (unsigned int i = 0; i < lN; ++ i) {
        const double z = R[i](2) - 0.5 * hz;
        unsigned int idx = (z - zmin) / hz;
522
        double tau = (z - zmin) / hz - idx;
523 524 525 526 527 528 529 530 531 532 533

        lineDensity[idx] += Q[i] * (1.0 - tau) * perMeter;
        lineDensity[idx + 1] += Q[i] * tau * perMeter;
    }

    reduce(&(lineDensity[0]), &(lineDensity[0]) + nBins, &(lineDensity[0]), OpAddAssign());

    meshInfo.first = zmin;
    meshInfo.second = hz;
}

frey_m's avatar
frey_m committed
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548


template <class T, unsigned Dim>
void PartBunchBase<T, Dim>::boundp() {
    /*
      Assume rmin_m < 0.0
     */

    IpplTimings::startTimer(boundpTimer_m);
    //if(!R.isDirty() && stateOfLastBoundP_ == unit_state_) return;
    if ( !(R.isDirty() || ID.isDirty() ) && stateOfLastBoundP_ == unit_state_) return; //-DW

    stateOfLastBoundP_ = unit_state_;

    if(!isGridFixed()) {
549
        const int dimIdx = (dcBeam_m? 2: 3);
frey_m's avatar
frey_m committed
550 551

        /**
552 553 554 555
            In case of dcBeam_m && hr_m < 0
            this is the first call to boundp and we
            have to set hr completely i.e. x,y and z.
         */
frey_m's avatar
frey_m committed
556

557
        this->updateDomainLength(nr_m);
558
        IpplTimings::startTimer(boundpBoundsTimer_m);
frey_m's avatar
frey_m committed
559
        get_bounds(rmin_m, rmax_m);
560
        IpplTimings::stopTimer(boundpBoundsTimer_m);
frey_m's avatar
frey_m committed
561
        Vector_t len = rmax_m - rmin_m;
562

563 564 565 566 567 568 569 570 571
        double volume = 1.0;
        for(int i = 0; i < dimIdx; i++) {
            double length = std::abs(rmax_m[i] - rmin_m[i]);
            if (length < 1e-10) {
                rmax_m[i] += 1e-10;
                rmin_m[i] -= 1e-10;
            } else {
                rmax_m[i] += dh_m * length;
                rmin_m[i] -= dh_m * length;
frey_m's avatar
frey_m committed
572
            }
573 574 575 576 577 578 579 580 581
            hr_m[i]    = (rmax_m[i] - rmin_m[i]) / (nr_m[i] - 1);
        }
        if (dcBeam_m) {
            rmax_m[2] = rmin_m[2] + periodLength_m;
            hr_m[2] = periodLength_m / (nr_m[2] - 1);
        }
        for (int i = 0; i < dimIdx; ++ i) {
            volume *= std::abs(rmax_m[i] - rmin_m[i]);
        }
frey_m's avatar
frey_m committed
582

583 584 585 586 587 588 589
        if (getIfBeamEmitting() && dist_m != NULL) {
            // keep particles per cell ratio high, don't spread a hand full particles across the whole grid
            double percent = std::max(1.0 / (nr_m[2] - 1), dist_m->getPercentageEmitted());
            double length  = std::abs(rmax_m[2] - rmin_m[2]) / (1.0 + 2 * dh_m);
            if (percent < 1.0 && percent > 0.0) {
                rmax_m[2] -= dh_m * length;
                rmin_m[2] = rmax_m[2] - length / percent;
590

591
                length /= percent;
frey_m's avatar
frey_m committed
592

593 594
                rmax_m[2] += dh_m * length;
                rmin_m[2] -= dh_m * length;
595

596
                hr_m[2] = (rmax_m[2] - rmin_m[2]) / (nr_m[2] - 1);
frey_m's avatar
frey_m committed
597
            }
598
        }
frey_m's avatar
frey_m committed
599

600
        if (volume < 1e-21 && getTotalNum() > 1 && std::abs(sum(Q)) > 0.0) {
601
            WARNMSG(level1 << "!!! Extremely high particle density detected !!!" << endl);
frey_m's avatar
frey_m committed
602
        }
603
        //INFOMSG("It is a full boundp hz= " << hr_m << " rmax= " << rmax_m << " rmin= " << rmin_m << endl);
604

605
        if(hr_m[0] * hr_m[1] * hr_m[2] <= 0) {
frey_m's avatar
frey_m committed
606 607
            throw GeneralClassicException("boundp() ", "h<0, can not build a mesh");
        }
608 609 610

        Vector_t origin = rmin_m - Vector_t(hr_m[0] / 2.0, hr_m[1] / 2.0, hr_m[2] / 2.0);
        this->updateFields(hr_m, origin);
frey_m's avatar
frey_m committed
611
    }
612
    IpplTimings::startTimer(boundpUpdateTimer_m);
frey_m's avatar
frey_m committed
613
    update();
614
    IpplTimings::stopTimer(boundpUpdateTimer_m);
frey_m's avatar
frey_m committed
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
    R.resetDirtyFlag();

    IpplTimings::stopTimer(boundpTimer_m);
}


template <class T, unsigned Dim>
void PartBunchBase<T, Dim>::boundp_destroy() {

    Inform gmsgAll("boundp_destroy ", INFORM_ALL_NODES);

    Vector_t len;
    const int dimIdx = 3;
    IpplTimings::startTimer(boundpTimer_m);

    std::unique_ptr<size_t[]> countLost;
    if(weHaveBins()) {
        const int tempN = pbin_m->getLastemittedBin();
        countLost = std::unique_ptr<size_t[]>(new size_t[tempN]);
        for(int ii = 0; ii < tempN; ii++) countLost[ii] = 0;
    }
636

637
    this->updateDomainLength(nr_m);
frey_m's avatar
frey_m committed
638

639

640
    IpplTimings::startTimer(boundpBoundsTimer_m);
frey_m's avatar
frey_m committed
641
    get_bounds(rmin_m, rmax_m);
frey_m's avatar
frey_m committed
642
    IpplTimings::stopTimer(boundpBoundsTimer_m);
643

frey_m's avatar
frey_m committed
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
    len = rmax_m - rmin_m;

    calcBeamParameters();

    int checkfactor = Options::remotePartDel;
    if (checkfactor != 0) {
        //INFOMSG("checkfactor= " << checkfactor << endl);
        // check the bunch if its full size is larger than checkfactor times of its rms size
        if(checkfactor < 0) {
            checkfactor *= -1;
            if (len[0] > checkfactor * rrms_m[0] ||
                len[1] > checkfactor * rrms_m[1] ||
                len[2] > checkfactor * rrms_m[2])
            {
                for(unsigned int ii = 0; ii < this->getLocalNum(); ii++) {
659
                    /* delete the particle if the distance to the beam center
frey_m's avatar
frey_m committed
660 661
                     * is larger than 8 times of beam's rms size
                     */
662 663 664
                    if (std::abs(R[ii](0) - rmean_m(0)) > checkfactor * rrms_m[0] ||
                        std::abs(R[ii](1) - rmean_m(1)) > checkfactor * rrms_m[1] ||
                        std::abs(R[ii](2) - rmean_m(2)) > checkfactor * rrms_m[2])
frey_m's avatar
frey_m committed
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
                    {
                        // put particle onto deletion list
                        destroy(1, ii);
                        //update bin parameter
                        if (weHaveBins())
                            countLost[Bin[ii]] += 1 ;
                        /* INFOMSG("REMOTE PARTICLE DELETION: ID = " << ID[ii] << ", R = " << R[ii]
                         * << ", beam rms = " << rrms_m << endl;);
                         */
                    }
                }
            }
        }
        else {
            if (len[0] > checkfactor * rrms_m[0] ||
                len[2] > checkfactor * rrms_m[2])
            {
                for(unsigned int ii = 0; ii < this->getLocalNum(); ii++) {
683
                    /* delete the particle if the distance to the beam center
frey_m's avatar
frey_m committed
684 685
                     * is larger than 8 times of beam's rms size
                     */
686 687
                    if (std::abs(R[ii](0) - rmean_m(0)) > checkfactor * rrms_m[0] ||
                        std::abs(R[ii](2) - rmean_m(2)) > checkfactor * rrms_m[2])
frey_m's avatar
frey_m committed
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
                    {
                        // put particle onto deletion list
                        destroy(1, ii);
                        //update bin parameter
                        if (weHaveBins())
                            countLost[Bin[ii]] += 1 ;
                        /* INFOMSG("REMOTE PARTICLE DELETION: ID = " << ID[ii] << ", R = " << R[ii]
                         * << ", beam rms = " << rrms_m << endl;);
                         */
                    }
                }
            }
        }
    }

    for(int i = 0; i < dimIdx; i++) {
        double length = std::abs(rmax_m[i] - rmin_m[i]);
        rmax_m[i] += dh_m * length;
        rmin_m[i] -= dh_m * length;
        hr_m[i]    = (rmax_m[i] - rmin_m[i]) / (nr_m[i] - 1);
    }

    // rescale mesh
711
    this->updateFields(hr_m, rmin_m);
712

frey_m's avatar
frey_m committed
713 714 715
    if(weHaveBins()) {
        pbin_m->updatePartInBin_cyc(countLost.get());
    }
716

frey_m's avatar
frey_m committed
717 718 719 720 721
    /* we also need to update the number of particles per bunch
     * expensive since does an allreduce!
     */
    countTotalNumPerBunch();

722
    IpplTimings::startTimer(boundpUpdateTimer_m);
frey_m's avatar
frey_m committed
723
    update();
724
    IpplTimings::stopTimer(boundpUpdateTimer_m);
725

frey_m's avatar
frey_m committed
726 727 728 729 730 731 732 733 734
    IpplTimings::stopTimer(boundpTimer_m);
}


template <class T, unsigned Dim>
size_t PartBunchBase<T, Dim>::boundp_destroyT() {

    const unsigned int minNumParticlesPerCore = getMinimumNumberOfParticlesPerCore();

735
    this->updateDomainLength(nr_m);
frey_m's avatar
frey_m committed
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

    std::unique_ptr<size_t[]> tmpbinemitted;

    boundp();

    size_t ne = 0;
    const size_t localNum = getLocalNum();

    if(weHaveEnergyBins()) {
        tmpbinemitted = std::unique_ptr<size_t[]>(new size_t[getNumberOfEnergyBins()]);
        for(int i = 0; i < getNumberOfEnergyBins(); i++) {
            tmpbinemitted[i] = 0;
        }
        for(unsigned int i = 0; i < localNum; i++) {
            if (Bin[i] < 0) {
                ne++;
                destroy(1, i);
            } else
                tmpbinemitted[Bin[i]]++;
        }
    } else {
        for(unsigned int i = 0; i < localNum; i++) {
            if((Bin[i] < 0) && ((localNum - ne) > minNumParticlesPerCore)) {   // need in minimum x particles per node
                ne++;
                destroy(1, i);
            }
        }
        lowParticleCount_m = ((localNum - ne) <= minNumParticlesPerCore);
        reduce(lowParticleCount_m, lowParticleCount_m, OpOr());
    }

    if (lowParticleCount_m) {
        Inform m ("boundp_destroyT a) ", INFORM_ALL_NODES);
        m << level3 << "Warning low number of particles on some cores localNum= "
          << localNum << " ne= " << ne << " NLocal= " << getLocalNum() << endl;
    } else {
        boundp();
    }
    calcBeamParameters();
    gatherLoadBalanceStatistics();

    if(weHaveEnergyBins()) {
        const int lastBin = dist_m->getLastEmittedEnergyBin();
        for(int i = 0; i < lastBin; i++) {
            binemitted_m[i] = tmpbinemitted[i];
        }
    }
    reduce(ne, ne, OpAddAssign());
    return ne;
}


template <class T, unsigned Dim>
size_t PartBunchBase<T, Dim>::destroyT() {

    const unsigned int minNumParticlesPerCore = getMinimumNumberOfParticlesPerCore();
    std::unique_ptr<size_t[]> tmpbinemitted;

    const size_t localNum = getLocalNum();
    const size_t totalNum = getTotalNum();
796
    size_t ne = 0;
frey_m's avatar
frey_m committed
797 798 799 800 801 802 803 804 805

    if(weHaveEnergyBins()) {
        tmpbinemitted = std::unique_ptr<size_t[]>(new size_t[getNumberOfEnergyBins()]);
        for(int i = 0; i < getNumberOfEnergyBins(); i++) {
            tmpbinemitted[i] = 0;
        }
        for(unsigned int i = 0; i < localNum; i++) {
            if (Bin[i] < 0) {
                destroy(1, i);
806
                ++ ne;
frey_m's avatar
frey_m committed
807 808 809 810 811 812
            } else
                tmpbinemitted[Bin[i]]++;
        }
    } else {
        Inform dmsg("destroy: ", INFORM_ALL_NODES);
        for(size_t i = 0; i < localNum; i++) {
813 814 815 816 817
            if((Bin[i] < 0)) {
                if ((localNum - ne) > minNumParticlesPerCore) {   // need in minimum x particles per node
                    ne++;
                    destroy(1, i);
                }
frey_m's avatar
frey_m committed
818 819 820 821
            }
        }
        lowParticleCount_m = ((localNum - ne) <= minNumParticlesPerCore);
        reduce(lowParticleCount_m, lowParticleCount_m, OpOr());
822 823 824 825
    }

    if (ne > 0) {
        performDestroy(true);
frey_m's avatar
frey_m committed
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
    }

    calcBeamParameters();
    gatherLoadBalanceStatistics();

    if (weHaveEnergyBins()) {
        const int lastBin = dist_m->getLastEmittedEnergyBin();
        for(int i = 0; i < lastBin; i++) {
            binemitted_m[i] = tmpbinemitted[i];
        }
    }
    size_t newTotalNum = getLocalNum();
    reduce(newTotalNum, newTotalNum, OpAddAssign());

    setTotalNum(newTotalNum);

    return totalNum - newTotalNum;
}

845
template <class T, unsigned Dim>
846
double PartBunchBase<T, Dim>::getPx(int /*i*/) {
847 848 849 850 851
    return 0.0;
}


template <class T, unsigned Dim>
852
double PartBunchBase<T, Dim>::getPy(int) {
853 854 855 856 857
    return 0.0;
}


template <class T, unsigned Dim>
858
double PartBunchBase<T, Dim>::getPz(int) {
859 860 861 862 863
    return 0.0;
}


template <class T, unsigned Dim>
864
double PartBunchBase<T, Dim>::getPx0(int) {
865 866 867 868 869
    return 0.0;
}


template <class T, unsigned Dim>
870
double PartBunchBase<T, Dim>::getPy0(int) {
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
    return 0;
}


//ff
template <class T, unsigned Dim>
double PartBunchBase<T, Dim>::getX(int i) {
    return this->R[i](0);
}


//ff
template <class T, unsigned Dim>
double PartBunchBase<T, Dim>::getY(int i) {
    return this->R[i](1);
}


//ff
template <class T, unsigned Dim>
double PartBunchBase<T, Dim>::getZ(int i) {
    return this->R[i](2);
}


//ff
template <class T, unsigned Dim>
898
double PartBunchBase<T, Dim>::getX0(int /*i*/) {
899 900 901 902 903 904
    return 0.0;
}


//ff
template <class T, unsigned Dim>
905
double PartBunchBase<T, Dim>::getY0(int /*i*/) {
906 907 908 909 910
    return 0.0;
}


template <class T, unsigned Dim>
911
void PartBunchBase<T, Dim>::setZ(int /*i*/, double /*zcoo*/) {
912 913 914 915 916
};


template <class T, unsigned Dim>
void PartBunchBase<T, Dim>::get_bounds(Vector_t &rmin, Vector_t &rmax) {
917

frey_m's avatar
frey_m committed
918
    this->getLocalBounds(rmin, rmax);
919

kraus's avatar
kraus committed
920
    double min[2*Dim];
921

922
    for (unsigned int i = 0; i < Dim; ++i) {
kraus's avatar
kraus committed
923 924
        min[2*i] = rmin[i];
        min[2*i + 1] = -rmax[i];
925
    }
926

kraus's avatar
kraus committed
927
    allreduce(min, 2*Dim, std::less<double>());
928

929
    for (unsigned int i = 0; i < Dim; ++i) {
kraus's avatar
kraus committed
930 931
        rmin[i] = min[2*i];
        rmax[i] = -min[2*i + 1];
932
    }
933 934 935 936 937 938
}


template <class T, unsigned Dim>
void PartBunchBase<T, Dim>::getLocalBounds(Vector_t &rmin, Vector_t &rmax) {
    const size_t localNum = getLocalNum();
frey_m's avatar
frey_m committed
939
    if (localNum == 0) {
940 941 942
        double maxValue = 1e8;
        rmin = Vector_t(maxValue, maxValue, maxValue);
        rmax = Vector_t(-maxValue, -maxValue, -maxValue);
kraus's avatar
kraus committed
943
        return;
frey_m's avatar
frey_m committed
944
    }
945

946 947 948 949 950
    rmin = R[0];
    rmax = R[0];
    for (size_t i = 1; i < localNum; ++ i) {
        for (unsigned short d = 0; d < 3u; ++ d) {
            if (rmin(d) > R[i](d)) rmin(d) = R[i](d);
kraus's avatar
kraus committed
951
            else if (rmax(d) < R[i](d)) rmax(d) = R[i](d);
952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
        }
    }
}


template <class T, unsigned Dim>
std::pair<Vector_t, double> PartBunchBase<T, Dim>::getBoundingSphere() {
    Vector_t rmin, rmax;
    get_bounds(rmin, rmax);

    std::pair<Vector_t, double> sphere;
    sphere.first = 0.5 * (rmin + rmax);
    sphere.second = sqrt(dot(rmax - sphere.first, rmax - sphere.first));

    return sphere;
}


template <class T, unsigned Dim>
std::pair<Vector_t, double> PartBunchBase<T, Dim>::getLocalBoundingSphere() {
    Vector_t rmin, rmax;
    getLocalBounds(rmin, rmax);

    std::pair<Vector_t, double> sphere;
    sphere.first = 0.5 * (rmin + rmax);
    sphere.second = sqrt(dot(rmax - sphere.first, rmax - sphere.first));

    return sphere;
}


template <class T, unsigned Dim>
984
void PartBunchBase<T, Dim>::push_back(OpalParticle p) {
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
    Inform msg("PartBunch ");

    create(1);
    size_t i = getTotalNum();

    R[i](0) = p[0];
    R[i](1) = p[1];
    R[i](2) = p[2];

    P[i](0) = p[3];
    P[i](1) = p[4];
    P[i](2) = p[5];

    update();
    msg << "Created one particle i= " << i << endl;
}


template <class T, unsigned Dim>
void PartBunchBase<T, Dim>::set_part(FVector<double, 6> z, int ii) {
    R[ii](0) = z[0];
    P[ii](0) = z[1];
    R[ii](1) = z[2];
    P[ii](1) = z[3];
    R[ii](2) = z[4];
    P[ii](2) = z[5];
}


template <class T, unsigned Dim>
1015
void PartBunchBase<T, Dim>::set_part(OpalParticle p, int ii) {
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
    R[ii](0) = p[0];
    P[ii](0) = p[1];
    R[ii](1) = p[2];
    P[ii](1) = p[3];
    R[ii](2) = p[4];
    P[ii](2) = p[5];
}


template <class T, unsigned Dim>
1026 1027
OpalParticle PartBunchBase<T, Dim>::get_part(int ii) {
    OpalParticle part;
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
    part[0] = R[ii](0);
    part[1] = P[ii](0);
    part[2] = R[ii](1);
    part[3] = P[ii](1);
    part[4] = R[ii](2);
    part[5] = P[ii](2);
    return part;
}


template <class T, unsigned Dim>
void PartBunchBase<T, Dim>::maximumAmplitudes(const FMatrix<double, 6, 6> &D,
                                              double &axmax, double &aymax) {
    axmax = aymax = 0.0;
1042
    OpalParticle part;
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084

    for(unsigned int ii = 0; ii < getLocalNum(); ii++) {

        part = get_part(ii);

        double xnor =
            D(0, 0) * part.x()  + D(0, 1) * part.px() + D(0, 2) * part.y() +
            D(0, 3) * part.py() + D(0, 4) * part.t()  + D(0, 5) * part.pt();
        double pxnor =
            D(1, 0) * part.x()  + D(1, 1) * part.px() + D(1, 2) * part.y() +
            D(1, 3) * part.py() + D(1, 4) * part.t()  + D(1, 5) * part.pt();
        double ynor =
            D(2, 0) * part.x()  + D(2, 1) * part.px() + D(2, 2) * part.y() +
            D(2, 3) * part.py() + D(2, 4) * part.t()  + D(2, 5) * part.pt();
        double pynor =
            D(3, 0) * part.x()  + D(3, 1) * part.px() + D(3, 2) * part.y() +
            D(3, 3) * part.py() + D(3, 4) * part.t()  + D(3, 5) * part.pt();

        axmax = std::max(axmax, (xnor * xnor + pxnor * pxnor));
        aymax = std::max(aymax, (ynor * ynor + pynor * pynor));
    }
}


template <class T, unsigned Dim>
void PartBunchBase<T, Dim>::setdT(double dt) {
    dt_m = dt;
}


template <class T, unsigned Dim>
double PartBunchBase<T, Dim>::getdT() const {
    return dt_m;
}


template <class T, unsigned Dim>
void PartBunchBase<T, Dim>::setT(double t) {
    t_m = t;
}


1085 1086 1087 1088 1089 1090
template <class T, unsigned Dim>
void PartBunchBase<T, Dim>::incrementT() {
    t_m += dt_m;
}


1091 1092 1093 1094 1095 1096 1097
template <class T, unsigned Dim>
double PartBunchBase<T, Dim>::getT() const {
    return t_m;
}


template <class T, unsigned Dim>
1098
double PartBunchBase<T, Dim>::get_sPos() const {
1099
    return spos_m;
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 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
}


template <class T, unsigned Dim>
void PartBunchBase<T, Dim>::set_sPos(double s) {
    spos_m = s;
}


template <class T, unsigned Dim>
double PartBunchBase<T, Dim>::get_gamma() const {
    return eKin_m / (getM()*1e-6) + 1.0;
}


template <class T, unsigned Dim>
double PartBunchBase<T, Dim>::get_meanKineticEnergy() const {
    return eKin_m;
}


template <class T, unsigned Dim>
Vector_t PartBunchBase<T, Dim>::get_origin() const {
    return rmin_m;
}


template <class T, unsigned Dim>
Vector_t PartBunchBase<T, Dim>::get_maxExtent() const {
    return rmax_m;
}


template <class T, unsigned Dim>
Vector_t PartBunchBase<T, Dim>::get_centroid() const {
    return rmean_m;
}


template <class T, unsigned Dim>
Vector_t PartBunchBase<T, Dim>::get_rrms() const {
    return rrms_m;
}


template <class T, unsigned Dim>
Vector_t PartBunchBase<T, Dim>::get_rprms() const {
    return rprms_m;
}


template <class T, unsigned Dim>
Vector_t PartBunchBase<T, Dim>::get_rmean() const {
    return rmean_m;
}


template <class T, unsigned Dim>
Vector_t PartBunchBase<T, Dim>::get_prms() const {
    return prms_m;
}


template <class T, unsigned Dim>
Vector_t PartBunchBase<T, Dim>::get_pmean() const {
    return pmean_m;
}


template <class T, unsigned Dim>
Vector_t PartBunchBase<T, Dim>::get_pmean_Distribution() const {
1171
    if (dist_m)// && dist_m->getType() != DistrTypeT::FROMFILE)
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
        return dist_m->get_pmean();

    double gamma = 0.1 / getM() + 1; // set default 0.1 eV
    return Vector_t(0, 0, sqrt(std::pow(gamma, 2) - 1));
}


template <class T, unsigned Dim>
Vector_t PartBunchBase<T, Dim>::get_emit() const {
    return eps_m;
}


template <class T, unsigned Dim>
Vector_t PartBunchBase<T, Dim>::get_norm_emit() const {
    return eps_norm_m;
}


frey_m's avatar
frey_m committed
1191
template <class T, unsigned Dim>
1192 1193
Vector_t PartBunchBase<T, Dim>::get_halo() const {
    return halo_m;
frey_m's avatar
frey_m committed
1194 1195 1196
}


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 1228 1229 1230 1231 1232 1233 1234 1235 1236
template <class T, unsigned Dim>
Vector_t PartBunchBase<T, Dim>::get_hr() const {
    return hr_m;
}


template <class T, unsigned Dim>
double PartBunchBase<T, Dim>::get_Dx() const {
    return Dx_m;
}


template <class T, unsigned Dim>
double PartBunchBase<T, Dim>::get_Dy() const {
    return Dy_m;
}


template <class T, unsigned Dim>
double PartBunchBase<T, Dim>::get_DDx() const {
    return DDx_m;
}


template <class T, unsigned Dim>
double PartBunchBase<T, Dim>::get_DDy() const {
    return DDy_m;
}


template <class T, unsigned Dim>
void PartBunchBase<T, Dim>::set_meshEnlargement(double dh) {
    dh_m = dh;
}


template <class T, unsigned Dim>
void PartBunchBase<T, Dim>::gatherLoadBalanceStatistics() {

    for(int i = 0; i < Ippl::getNodes(); i++)
frey_m's avatar
frey_m committed
1237
        globalPartPerNode_m[i] = 0;
1238

frey_m's avatar
frey_m committed
1239 1240
    std::size_t localnum = getLocalNum();
    gather(&localnum, &globalPartPerNode_m[0], 1);
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
}


template <class T, unsigned Dim>
size_t PartBunchBase<T, Dim>::getLoadBalance(int p) const {
    return globalPartPerNode_m[p];
}


template <class T, unsigned Dim>
void PartBunchBase<T, Dim>::get_PBounds(Vector_t &min, Vector_t &max) const {
    bounds(this->P, min, max);
}


template <class T, unsigned Dim>
void PartBunchBase<T, Dim>::calcBeamParameters() {

    Vector_t eps2, fac, rsqsum, psqsum, rpsum;

    IpplTimings::startTimer(statParamTimer_m);

    const size_t locNp = getLocalNum();
1264
    const size_t totalNum = getTotalNum();
1265 1266 1267 1268
    const double zero = 0.0;

    get_bounds(rmin_m, rmax_m);

1269
    if(totalNum == 0) {
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
        for(unsigned int i = 0 ; i < Dim; i++) {
            rmean_m(i) = 0.0;
            pmean_m(i) = 0.0;
            rrms_m(i) = 0.0;
            prms_m(i) = 0.0;
            eps_norm_m(i)  = 0.0;
        }
        rprms_m = 0.0;
        eKin_m = 0.0;
        eps_m = 0.0;
        IpplTimings::stopTimer(statParamTimer_m);
        return;
    }

1284 1285
    const size_t intN = calcMoments();
    const double N = static_cast<double>(intN);
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308

    for(unsigned int i = 0 ; <