PartBunchBase.hpp 67.5 KB
Newer Older
1 2 3 4 5
#ifndef PART_BUNCH_BASE_HPP
#define PART_BUNCH_BASE_HPP

#include "PartBunchBase.h"

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

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

using Physics::pi;

extern Inform *gmsg;
16

frey_m's avatar
frey_m committed
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
// template <class T, unsigned Dim>
// PartBunchBase<T, Dim>::PartBunchBase()
//     : pbase(nullptr),
//       myNode_m(Ippl::myNode()),
//       nodes_m(Ippl::getNodes()),
//       fixed_grid(false),
//       pbin_m(nullptr),
//       lossDs_m(nullptr),
//       pmsg_m(nullptr),
//       f_stream(nullptr),
//       unit_state_(units),
//       stateOfLastBoundP_(unitless),
//       moments_m(),
//       dt_m(0.0),
//       t_m(0.0),
//       eKin_m(0.0),
//       dE_m(0.0),
//       spos_m(0.0),
//       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),
//       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),
//       lPath_m(0.0),
//       stepsPerTurn_m(0),
//       localTrackStep_m(0),
//       globalTrackStep_m(0),
//       numBunch_m(1),
//       SteptoLastInj_m(0),
//       globalPartPerNode_m(nullptr),
//       dist_m(nullptr),
//       globalMeanR_m(Vector_t(0.0, 0.0, 0.0)),
//       globalToLocalQuaternion_m(Quaternion_t(1.0, 0.0, 0.0, 0.0)),
//       lowParticleCount_m(false),
frey_m's avatar
frey_m committed
70
//       dcBeam_m(false)
frey_m's avatar
frey_m committed
71 72 73 74 75
// {
//     R(*(pbase->R_p));   // undefined behaviour due to reference to null pointer
//     ID(*(pbase->ID_p));   // undefined behaviour due to reference to null pointer
// }

76 77
template <class T, unsigned Dim>
PartBunchBase<T, Dim>::PartBunchBase(AbstractParticle<T, Dim>* pb)
78
    : R(*(pb->R_p)),
79 80 81 82 83 84 85 86
      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),
87
      lowParticleCount_m(false),
88 89 90 91 92 93 94 95
//       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),
96
      spos_m(0.0),
97 98
      globalMeanR_m(Vector_t(0.0, 0.0, 0.0)),
      globalToLocalQuaternion_m(Quaternion_t(1.0, 0.0, 0.0, 0.0)),
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
      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),
      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),
      lPath_m(0.0),
      stepsPerTurn_m(0),
      localTrackStep_m(0),
      globalTrackStep_m(0),
      numBunch_m(1),
      SteptoLastInj_m(0),
      globalPartPerNode_m(nullptr),
      dist_m(nullptr),
      dcBeam_m(false),
132
      periodLength_m(Physics::c / 1e9),
133
      pbase(pb)
134
{
frey_m's avatar
frey_m committed
135
    setup(pb);
136

137
    boundpTimer_m = IpplTimings::getTimer("Boundingbox");
138 139
    boundpBoundsTimer_m = IpplTimings::getTimer("Boundingbox-bounds");
    boundpUpdateTimer_m = IpplTimings::getTimer("Boundingbox-update");
140

141 142 143 144 145 146 147
    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");
148

149 150 151 152 153 154 155 156 157 158 159 160 161
    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));
      }
    */
162 163 164
}

template <class T, unsigned Dim>
frey_m's avatar
frey_m committed
165
PartBunchBase<T, Dim>::PartBunchBase(AbstractParticle<T, Dim>* pb, const PartData *ref)
166
    : R(*(pb->R_p)),
frey_m's avatar
frey_m committed
167 168
      ID(*(pb->ID_p)),
      myNode_m(Ippl::myNode()),
169 170 171 172 173 174
      nodes_m(Ippl::getNodes()),
      fixed_grid(false),
      pbin_m(nullptr),
      lossDs_m(nullptr),
      pmsg_m(nullptr),
      f_stream(nullptr),
175
      lowParticleCount_m(false),
176 177 178 179 180 181 182 183 184
      reference(ref),
      unit_state_(units),
      stateOfLastBoundP_(unitless),
      moments_m(),
      dt_m(0.0),
      t_m(0.0),
      eKin_m(0.0),
      dE_m(0.0),
      spos_m(0.0),
185 186
      globalMeanR_m(Vector_t(0.0, 0.0, 0.0)),
      globalToLocalQuaternion_m(Quaternion_t(1.0, 0.0, 0.0, 0.0)),
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
      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),
      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),
      lPath_m(0.0),
      stepsPerTurn_m(0),
      localTrackStep_m(0),
      globalTrackStep_m(0),
      numBunch_m(1),
      SteptoLastInj_m(0),
      globalPartPerNode_m(nullptr),
      dist_m(nullptr),
      dcBeam_m(false),
220
      periodLength_m(Physics::c / 1e9),
221
      pbase(pb)
222
{
frey_m's avatar
frey_m committed
223
    setup(pb);
224

225
    boundpTimer_m = IpplTimings::getTimer("Boundingbox");
226 227
    boundpBoundsTimer_m = IpplTimings::getTimer("Boundingbox-bounds");
    boundpUpdateTimer_m = IpplTimings::getTimer("Boundingbox-update");
228 229 230 231 232 233 234
    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");
235

236 237 238 239 240 241 242 243 244 245 246 247 248
    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));
      }
    */
249 250
}

251
template <class T, unsigned Dim>
frey_m's avatar
frey_m committed
252 253
PartBunchBase<T, Dim>::PartBunchBase(AbstractParticle<T, Dim>* pb,
                                     const std::vector<OpalParticle>& rhs,
254
                                     const PartData *ref):
frey_m's avatar
frey_m committed
255 256
    R(*(pb->R_p)),
    ID(*(pb->ID_p)),
257 258 259 260 261 262 263
    myNode_m(Ippl::myNode()),
    nodes_m(Ippl::getNodes()),
    fixed_grid(false),
    pbin_m(nullptr),
    lossDs_m(nullptr),
    pmsg_m(nullptr),
    f_stream(nullptr),
264
    lowParticleCount_m(false),
265 266 267 268 269 270 271 272 273
    reference(ref),
    unit_state_(units),
    stateOfLastBoundP_(unitless),
    moments_m(),
    dt_m(0.0),
    t_m(0.0),
    eKin_m(0.0),
    dE_m(0.0),
    spos_m(0.0),
274 275
    globalMeanR_m(Vector_t(0.0, 0.0, 0.0)),
    globalToLocalQuaternion_m(Quaternion_t(1.0, 0.0, 0.0, 0.0)),
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
    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),
    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),
    lPath_m(0.0),
    stepsPerTurn_m(0),
    localTrackStep_m(0),
    globalTrackStep_m(0),
    numBunch_m(1),
    SteptoLastInj_m(0),
    globalPartPerNode_m(nullptr),
    dist_m(nullptr),
    dcBeam_m(false),
309
    periodLength_m(Physics::c / 1e9),
310
    pbase(pb)
311
{
312

313 314 315 316 317
}


template <class T, unsigned Dim>
PartBunchBase<T, Dim>::PartBunchBase(const PartBunchBase<T, Dim>& rhs):
frey_m's avatar
frey_m committed
318 319
    R(rhs.R),
    ID(rhs.ID),
320 321 322 323 324 325 326
    myNode_m(Ippl::myNode()),
    nodes_m(Ippl::getNodes()),
    fixed_grid(rhs.fixed_grid),
    pbin_m(nullptr),
    lossDs_m(nullptr),
    pmsg_m(nullptr),
    f_stream(nullptr),
327
    lowParticleCount_m(rhs.lowParticleCount_m),
328 329 330 331 332 333 334 335 336
    reference(rhs.reference),
    unit_state_(rhs.unit_state_),
    stateOfLastBoundP_(rhs.stateOfLastBoundP_),
    moments_m(rhs.moments_m),
    dt_m(rhs.dt_m),
    t_m(rhs.t_m),
    eKin_m(rhs.eKin_m),
    dE_m(rhs.dE_m),
    spos_m(0.0),
337 338
    globalMeanR_m(Vector_t(0.0, 0.0, 0.0)),
    globalToLocalQuaternion_m(Quaternion_t(1.0, 0.0, 0.0, 0.0)),
339 340 341 342 343 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
    rmax_m(rhs.rmax_m),
    rmin_m(rhs.rmin_m),
    rrms_m(rhs.rrms_m),
    prms_m(rhs.prms_m),
    rmean_m(rhs.rmean_m),
    pmean_m(rhs.pmean_m),
    eps_m(rhs.eps_m),
    eps_norm_m(rhs.eps_norm_m),
    rprms_m(rhs.rprms_m),
    Dx_m(rhs.Dx_m),
    Dy_m(rhs.Dy_m),
    DDx_m(rhs.DDx_m),
    DDy_m(rhs.DDy_m),
    hr_m(rhs.hr_m),
    nr_m(rhs.nr_m),
    fs_m(nullptr),
    couplingConstant_m(rhs.couplingConstant_m),
    qi_m(rhs.qi_m),
    distDump_m(rhs.distDump_m),
    fieldDBGStep_m(rhs.fieldDBGStep_m),
    dh_m(rhs.dh_m),
    tEmission_m(rhs.tEmission_m),
    bingamma_m(nullptr),
    binemitted_m(nullptr),
    lPath_m(rhs.lPath_m),
    stepsPerTurn_m(rhs.stepsPerTurn_m),
    localTrackStep_m(rhs.localTrackStep_m),
    globalTrackStep_m(rhs.globalTrackStep_m),
    numBunch_m(rhs.numBunch_m),
    SteptoLastInj_m(rhs.SteptoLastInj_m),
    globalPartPerNode_m(nullptr),
    dist_m(nullptr),
    dcBeam_m(rhs.dcBeam_m),
372
    periodLength_m(rhs.periodLength_m),
373
    pbase(rhs.pbase)
374 375
{
}
376

frey_m's avatar
frey_m committed
377 378 379 380 381

// template <class T, unsigned Dim>
// AbstractParticle<T, Dim>* PartBunchBase<T, Dim>::getParticleBase() {
//     return pbase;
// }
382 383
//
//
frey_m's avatar
frey_m committed
384 385 386 387 388 389
// template <class T, unsigned Dim>
// const AbstractParticle<T, Dim>* PartBunchBase<T, Dim>::getParticleBase() const {
//     return pbase;
// }


390 391 392 393 394 395
/*
 * Bunch common member functions
 */

template <class T, unsigned Dim>
bool PartBunchBase<T, Dim>::getIfBeamEmitting() {
396 397 398 399 400 401 402 403 404 405 406 407
    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;
}


408 409
template <class T, unsigned Dim>
int PartBunchBase<T, Dim>::getLastEmittedEnergyBin() {
410 411 412 413 414 415 416 417 418
    /*
     * Get maximum last emitted energy bin.
     */
    int lastEmittedBin = dist_m->getLastEmittedEnergyBin();
    reduce(lastEmittedBin, lastEmittedBin, OpMaxAssign());
    return lastEmittedBin;
}


419 420
template <class T, unsigned Dim>
size_t PartBunchBase<T, Dim>::getNumberOfEmissionSteps() {
421 422 423 424
    return dist_m->getNumberOfEmissionSteps();
}


425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
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>
493
void PartBunchBase<T, Dim>::switchOffUnitlessPositions(bool use_dt_per_particle) {
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517

    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
518
    // do nothing here
519 520 521 522 523 524
}


template <class T, unsigned Dim>
void PartBunchBase<T, Dim>::setDistribution(Distribution *d,
                                            std::vector<Distribution *> addedDistributions,
525
                                            size_t &np)
526 527 528 529
{
    Inform m("setDistribution " );
    dist_m = d;

530
    dist_m->createOpalT(this, addedDistributions, np);
531 532

//    if (Options::cZero)
533
//        dist_m->create(this, addedDistributions, np / 2);
534
//    else
535
//        dist_m->create(this, addedDistributions, np);
536 537 538 539 540 541 542 543 544
}


template <class T, unsigned Dim>
bool PartBunchBase<T, Dim>::isGridFixed() {
    return fixed_grid;
}


545 546 547 548 549 550
template <class T, unsigned Dim>
bool PartBunchBase<T, Dim>::hasBinning() {
    return (pbin_m != nullptr);
}


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
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
599
    return dist_m->emitParticles(this, eZ);
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 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
}


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;
}


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;
    for(unsigned int n = 0; n < getLocalNum(); n++)
        bingamma_m[this->Bin[n]] += sqrt(1.0 + dot(this->P[n], this->P[n]));
frey_m's avatar
frey_m committed
694 695 696

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

697 698 699 700 701
    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
702 703
        INFOMSG("Bin " << i << " : particle number = " << pbin_m->getTotalNumPerBin(i)
                       << " gamma = " << bingamma_m[i] << endl);
704 705 706 707 708 709 710 711 712 713 714 715 716
    }

}


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) {
717
  this->Q = where(eq(this->Bin, bin), q, 0.0);
718 719 720 721 722
}


template <class T, unsigned Dim>
void PartBunchBase<T, Dim>::setBinCharge(int bin) {
723
  this->Q = where(eq(this->Bin, bin), this->qi_m, 0.0);
724 725 726 727 728 729
}


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

frey_m's avatar
frey_m committed
730
    std::size_t localnum = 0;
731 732 733
    const Vector_t meanR = get_rmean();

    for(unsigned long k = 0; k < getLocalNum(); ++ k)
734 735 736
        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)) {
737

frey_m's avatar
frey_m committed
738
            ++localnum;
739
        }
740

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

frey_m's avatar
frey_m committed
743 744 745
    size_t npOutside = std::accumulate(globalPartPerNode_m.get(),
                                       globalPartPerNode_m.get() + Ippl::getNodes(), 0,
                                       std::plus<size_t>());
746

frey_m's avatar
frey_m committed
747
    return npOutside;
748 749 750
}


751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
/**
 * \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
769
        Vektor<int, 3>/*NDIndex<3>*/ grid;
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
        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;
787
        double tau = (z - zmin) / hz - idx;
788 789 790 791 792 793 794 795 796 797 798

        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
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813


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()) {
814
        const int dimIdx = (dcBeam_m? 2: 3);
frey_m's avatar
frey_m committed
815 816

        /**
817 818 819 820
            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
821

822
        this->updateDomainLength(nr_m);
823
        IpplTimings::startTimer(boundpBoundsTimer_m);
frey_m's avatar
frey_m committed
824
        get_bounds(rmin_m, rmax_m);
825
        IpplTimings::stopTimer(boundpBoundsTimer_m);
frey_m's avatar
frey_m committed
826
        Vector_t len = rmax_m - rmin_m;
827

828 829 830 831 832 833 834 835 836
        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
837
            }
838 839 840 841 842 843 844 845 846
            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
847

848 849 850 851 852 853 854
        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;
855

856
                length /= percent;
frey_m's avatar
frey_m committed
857

858 859
                rmax_m[2] += dh_m * length;
                rmin_m[2] -= dh_m * length;
860

861
                hr_m[2] = (rmax_m[2] - rmin_m[2]) / (nr_m[2] - 1);
frey_m's avatar
frey_m committed
862
            }
863
        }
frey_m's avatar
frey_m committed
864

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

870
        if(hr_m[0] * hr_m[1] * hr_m[2] <= 0) {
frey_m's avatar
frey_m committed
871 872
            throw GeneralClassicException("boundp() ", "h<0, can not build a mesh");
        }
873 874 875

        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
876
    }
877
    IpplTimings::startTimer(boundpUpdateTimer_m);
frey_m's avatar
frey_m committed
878
    update();
879
    IpplTimings::stopTimer(boundpUpdateTimer_m);
frey_m's avatar
frey_m committed
880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
    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;
    }
901

902
    this->updateDomainLength(nr_m);
frey_m's avatar
frey_m committed
903

904

905
    IpplTimings::startTimer(boundpBoundsTimer_m);
frey_m's avatar
frey_m committed
906
    get_bounds(rmin_m, rmax_m);
frey_m's avatar
frey_m committed
907
    IpplTimings::stopTimer(boundpBoundsTimer_m);
908

frey_m's avatar
frey_m committed
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
    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++) {
924
                    /* delete the particle if the distance to the beam center
frey_m's avatar
frey_m committed
925 926
                     * is larger than 8 times of beam's rms size
                     */
927 928 929
		    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
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
                    {
                        // 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++) {
948
                    /* delete the particle if the distance to the beam center
frey_m's avatar
frey_m committed
949 950
                     * is larger than 8 times of beam's rms size
                     */
951 952
		    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
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975
                    {
                        // 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
976
    this->updateFields(hr_m, rmin_m);
977

frey_m's avatar
frey_m committed
978 979 980
    if(weHaveBins()) {
        pbin_m->updatePartInBin_cyc(countLost.get());
    }
981

982
    IpplTimings::startTimer(boundpUpdateTimer_m);
frey_m's avatar
frey_m committed
983
    update();
984
    IpplTimings::stopTimer(boundpUpdateTimer_m);
985

frey_m's avatar
frey_m committed
986 987 988 989 990 991 992 993 994
    IpplTimings::stopTimer(boundpTimer_m);
}


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

    const unsigned int minNumParticlesPerCore = getMinimumNumberOfParticlesPerCore();

995
    this->updateDomainLength(nr_m);
frey_m's avatar
frey_m committed
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055

    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();
1056
    size_t ne = 0;
frey_m's avatar
frey_m committed
1057 1058 1059 1060 1061 1062 1063 1064 1065

    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);
1066
                ++ ne;
frey_m's avatar
frey_m committed
1067 1068 1069 1070 1071 1072
            } else
                tmpbinemitted[Bin[i]]++;
        }
    } else {
        Inform dmsg("destroy: ", INFORM_ALL_NODES);
        for(size_t i = 0; i < localNum; i++) {
1073 1074 1075 1076 1077
            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
1078 1079 1080 1081
            }
        }
        lowParticleCount_m = ((localNum - ne) <= minNumParticlesPerCore);
        reduce(lowParticleCount_m, lowParticleCount_m, OpOr());
1082 1083 1084 1085
    }

    if (ne > 0) {
        performDestroy(true);
frey_m's avatar
frey_m committed
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
    }

    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;
}

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


template <class T, unsigned Dim>
double PartBunchBase<T, Dim>::getPy(int i) {
    return 0.0;
}


template <class T, unsigned Dim>
double PartBunchBase<T, Dim>::getPz(int i) {
    return 0.0;
}


template <class T, unsigned Dim>
double PartBunchBase<T, Dim>::getPx0(int i) {
    return 0.0;
}


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


//ff
template <class T, unsigned Dim>
1165
double PartBunchBase<T, Dim>::getY0(int i) {
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
    return 0.0;
}


template <class T, unsigned Dim>
void PartBunchBase<T, Dim>::setZ(int i, double zcoo)
{
    // nothing done here
};


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

frey_m's avatar
frey_m committed
1180
    this->getLocalBounds(rmin, rmax);
1181

1182 1183
    double min[Dim];
    double max[Dim];
1184

1185 1186 1187 1188
    for (unsigned int i = 0; i < Dim; ++i) {
        min[i] = rmin[i];
        max[i] = rmax[i];
    }
1189

1190 1191 1192
    //FIXME use a min-max function
    allreduce(&min[0], Dim, std::less<double>());
    allreduce(&max[0], Dim, std::greater<double>());
1193

1194 1195 1196 1197
    for (unsigned int i = 0; i < Dim; ++i) {
        rmin[i] = min[i];
        rmax[i] = max[i];
    }
1198 1199 1200 1201 1202 1203
}


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
1204 1205 1206 1207 1208
    if (localNum == 0) {
	rmin = Vector_t(0.0, 0.0, 0.0);
	rmax = Vector_t(0.0, 0.0, 0.0);
	return;
    }
1209

1210 1211 1212 1213 1214
    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);
frey_m's avatar
frey_m committed
1215
	    else if (rmax(d) < R[i](d)) rmax(d) = R[i](d);
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
        }
    }
}


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>
1248
void PartBunchBase<T, Dim>::push_back(OpalParticle p) {
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
    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>
1279
void PartBunchBase<T, Dim>::set_part(OpalParticle p, int ii) {
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
    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>
1290 1291
OpalParticle PartBunchBase<T, Dim>::get_part(int ii) {
    OpalParticle part;
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
    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;
1306
    OpalParticle part;
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355

    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;
}