ParallelTTracker.cpp 99.8 KB
Newer Older
gsell's avatar
gsell committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
// ------------------------------------------------------------------------
// $RCSfile: ParallelTTracker.cpp,v $
// ------------------------------------------------------------------------
// $Revision: 1.1.2.1 $
// ------------------------------------------------------------------------
// Copyright: see Copyright.readme
// ------------------------------------------------------------------------
//
// Class: ParallelTTracker
//   The visitor class for tracking particles with time as independent
//   variable.
//
// ------------------------------------------------------------------------
//
// $Date: 2004/11/12 20:10:11 $
// $Author: adelmann $
//
// ------------------------------------------------------------------------

#include <cfloat>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <string>
26
#include <limits>
gsell's avatar
gsell committed
27 28

#include "Algorithms/ParallelTTracker.h"
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
#include "Algorithms/PartPusher.h"
#include "AbsBeamline/AlignWrapper.h"
#include "AbsBeamline/BeamBeam.h"
#include "AbsBeamline/Collimator.h"
#include "AbsBeamline/Corrector.h"
#include "AbsBeamline/Diagnostic.h"
#include "AbsBeamline/Drift.h"
#include "AbsBeamline/ElementBase.h"
#include "AbsBeamline/Lambertson.h"
#include "AbsBeamline/Marker.h"
#include "AbsBeamline/Monitor.h"
#include "AbsBeamline/Multipole.h"
#include "AbsBeamline/Probe.h"
#include "AbsBeamline/RBend.h"
#include "AbsBeamline/RFCavity.h"
#include "AbsBeamline/TravelingWave.h"
#include "AbsBeamline/RFQuadrupole.h"
#include "AbsBeamline/SBend.h"
#include "AbsBeamline/Separator.h"
#include "AbsBeamline/Septum.h"
#include "AbsBeamline/Solenoid.h"
#include "AbsBeamline/ParallelPlate.h"
#include "AbsBeamline/CyclotronValley.h"
#include "Beamlines/Beamline.h"
#include "Lines/Sequence.h"
gsell's avatar
gsell committed
54 55 56 57 58 59

#include "AbstractObjects/OpalData.h"

#include "BasicActions/Option.h"

#include "Distribution/Distribution.h"
60
#include "ValueDefinitions/RealVariable.h"
gsell's avatar
gsell committed
61 62
#include "Utilities/Timer.h"
#include "Utilities/OpalException.h"
63
#include "Solvers/SurfacePhysicsHandler.hh"
gsell's avatar
gsell committed
64 65 66 67 68 69 70 71 72 73 74 75
#include "Structure/BoundaryGeometry.h"

class PartData;

using namespace std;
using namespace OPALTimer;

ParallelTTracker::ParallelTTracker(const Beamline &beamline,
                                   const PartData &reference,
                                   bool revBeam,
                                   bool revTrack):
    Tracker(beamline, reference, revBeam, revTrack),
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
    itsBunch(NULL),
    itsDataSink_m(NULL),
    bgf_m(NULL),
    itsOpalBeamline_m(),
    lineDensity_m(),
    RefPartR_zxy_m(0.0),
    RefPartP_zxy_m(0.0),
    RefPartR_suv_m(0.0),
    RefPartP_suv_m(0.0),
    globalEOL_m(false),
    wakeStatus_m(false),
    surfaceStatus_m(false),
    secondaryFlg_m(false),
    mpacflg_m(true),
    nEmissionMode_m(false),
    zStop_m(0.0),
    scaleFactor_m(1.0),
    vscaleFactor_m(scaleFactor_m),
    recpGamma_m(1.0),
    rescale_coeff_m(1.0),
    dtTrack_m(0.0),
    surfaceEmissionStop_m(-1),
    minStepforReBin_m(-1),
99
    minBinEmitted_m(std::numeric_limits<size_t>::max()),
100 101 102 103
    repartFreq_m(-1),
    lastVisited_m(-1),
    numRefs_m(-1),
    gunSubTimeSteps_m(-1),
104
    emissionSteps_m(std::numeric_limits<unsigned int>::max()),
105
    localTrackSteps_m(0),
106
    maxNparts_m(0),
107
    numberOfFieldEmittedParticles_m(std::numeric_limits<size_t>::max()),
108 109 110 111 112 113 114 115
    bends_m(0),
    numParticlesInSimulation_m(0),
    space_orientation_m(0.0),
    timeIntegrationTimer1_m(IpplTimings::getTimer("TIntegration1")),
    timeIntegrationTimer2_m(IpplTimings::getTimer("TIntegration2")),
    timeFieldEvaluation_m(IpplTimings::getTimer("Fieldeval")),
    BinRepartTimer_m(IpplTimings::getTimer("Binaryrepart")),
    WakeFieldTimer_m(IpplTimings::getTimer("WakeField")) {
gsell's avatar
gsell committed
116 117 118 119 120 121 122 123 124 125 126 127 128

}


ParallelTTracker::ParallelTTracker(const Beamline &beamline,
                                   PartBunch &bunch,
                                   DataSink &ds,
                                   const PartData &reference,
                                   bool revBeam,
                                   bool revTrack,
                                   int maxSTEPS,
                                   double zstop):
    Tracker(beamline, reference, revBeam, revTrack),
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
    itsBunch(&bunch),
    itsDataSink_m(&ds),
    bgf_m(NULL),
    itsOpalBeamline_m(),
    lineDensity_m(),
    RefPartR_zxy_m(0.0),
    RefPartP_zxy_m(0.0),
    RefPartR_suv_m(0.0),
    RefPartP_suv_m(0.0),
    globalEOL_m(false),
    wakeStatus_m(false),
    surfaceStatus_m(false),
    secondaryFlg_m(false),
    mpacflg_m(true),
    nEmissionMode_m(false),
    zStop_m(zstop),
    scaleFactor_m(itsBunch->getdT() * Physics::c),
    vscaleFactor_m(scaleFactor_m),
    recpGamma_m(1.0),
    rescale_coeff_m(1.0),
    dtTrack_m(0.0),
    surfaceEmissionStop_m(-1),
    minStepforReBin_m(-1),
152
    minBinEmitted_m(std::numeric_limits<size_t>::max()),
153 154 155 156 157
    repartFreq_m(-1),
    lastVisited_m(-1),
    numRefs_m(-1),
    gunSubTimeSteps_m(-1),
    emissionSteps_m(numeric_limits<unsigned int>::max()),
158
    localTrackSteps_m(maxSTEPS),
159 160 161 162 163 164 165 166 167 168
    maxNparts_m(0),
    numberOfFieldEmittedParticles_m(numeric_limits<size_t>::max()),
    bends_m(0),
    numParticlesInSimulation_m(0),
    space_orientation_m(0.0),
    timeIntegrationTimer1_m(IpplTimings::getTimer("TIntegration1")),
    timeIntegrationTimer2_m(IpplTimings::getTimer("TIntegration2")),
    timeFieldEvaluation_m(IpplTimings::getTimer("Fieldeval")),
    BinRepartTimer_m(IpplTimings::getTimer("Binaryrepart")),
    WakeFieldTimer_m(IpplTimings::getTimer("WakeField")) {
gsell's avatar
gsell committed
169
    //    itsBeamline = dynamic_cast<Beamline*>(beamline.clone());
170

gsell's avatar
gsell committed
171
#ifdef DBG_SYM
172
    string fn = OpalData::getInstance()->getInputBasename() + string(".fields");
gsell's avatar
gsell committed
173 174 175 176
    of_m.open(fn.c_str(), ios::out);
    of_m.precision(9);
    of_m << "# spos Ex Ey Ez Bz By Bz at: (h,h),(h,-h),(-h,h)(-h,-h) h=0.001" << endl;
#endif
177

gsell's avatar
gsell committed
178 179 180 181 182 183 184 185 186 187 188
}


ParallelTTracker::~ParallelTTracker() {
#ifdef DBG_SYM
    of_m.close();
#endif
}

void ParallelTTracker::applySchottkyCorrection(PartBunch &itsBunch, int ne, double t, double rescale_coeff) {

189
    Inform msg("ParallelTTracker ");
gsell's avatar
gsell committed
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
    const long ls = 0;
    /*
      Now I can calculate E_{rf} at each position
      of the newely generated particles and rescale Q

      Note:
      For now I only sample the field of the last emitted particles.
      Space charge is not yet included
    */


    double laser_erg = itsBunch.getLaserEnergy(); // 4.7322; energy of single photon of 262nm laser  [eV]
    double workFunction = itsBunch.getWorkFunctionRf(); // espace energy for copper (4.31)  [eV]

    const double schottky_coeff = 0.037947; // coeffecient for calculate schottky potenial from E field [eV/(MV^0.5)]

    if(ne == 0)
        return ;

    double Ez = 0;
    double obtain_erg = 0;
    double par_t = 0;
    for(int k = 0; k < ne; k++) {
        size_t n = itsBunch.getLocalNum() - k - 1;
        Vector_t externalE(0.0);
        Vector_t externalB(0.0);

        itsBunch.R[n] *= Vector_t(Physics::c * itsBunch.dt[n]);
        par_t = t + itsBunch.dt[n] / 2;
        itsOpalBeamline_m.getFieldAt(n, itsBunch.R[n], ls, par_t, externalE, externalB);
        Ez = externalE(2);

        // fabs(Ez): if the field of cathode surface is in the right direction, it will increase the
        // energy which electron obtain. If the field is in the wrong direction, this particle will
        // be back to the cathode surface and then be deleted automaticly by OPAL,  we don't add
        // another logical branch to handle this. So fabs is the simplest way to handle this
        obtain_erg = laser_erg - workFunction + schottky_coeff * sqrt(fabs(Ez) / 1E6);
        double schottkyScale = obtain_erg * obtain_erg * rescale_coeff;

        itsBunch.Q[n] *= schottkyScale;
        itsBunch.R[n] /= Vector_t(Physics::c * itsBunch.dt[n]);
    }
}

double ParallelTTracker::schottkyLoop(double rescale_coeff) {

236 237
    Inform msg("ParallelTTracker ");

gsell's avatar
gsell committed
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
    double recpgamma;
    double t = 0.0;
    double dt = itsBunch->getdT();
    Vector_t vscaleFactor = Vector_t(scaleFactor_m);

    unsigned long long step = 0;
    unsigned int emissionSteps = 0;

    Vector_t um, a, s;
    Vector_t externalE, externalB;
    BorisPusher pusher(itsReference);
    Vector_t rmin, rmax;

    bool global_EOL;

    bool hasSwitchedToTEmission = false;
    bool hasSwitchedBackToTTrack = false;

    size_t totalParticles_i = itsBunch->getTotalNum();

258 259 260
    msg << "*****************************************************************" << endl;
    msg << " Estimate Schottky correction                                    " << endl;
    msg << "*****************************************************************" << endl;
gsell's avatar
gsell committed
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316

    double margin = 0.0;
    if(!mpacflg_m) {
        for(unsigned int i = 0; i < itsBunch->getLocalNum(); ++i) {
            long &l = itsBunch->LastSection[i];
            l = -1;
            itsOpalBeamline_m.getSectionIndexAt(itsBunch->R[i], l);
            itsBunch->ResetLocalCoordinateSystem(i, itsOpalBeamline_m.getOrientation(l), itsOpalBeamline_m.getSectionStart(l));
        }

        if(!(itsBunch->weHaveBins())) {
            IpplTimings::startTimer(BinRepartTimer_m);
            itsBunch->do_binaryRepart();
            IpplTimings::stopTimer(BinRepartTimer_m);
            Ippl::Comm->barrier();
        }

        // Check if there are any particles in simulation. If there are,
        // as in a restart, use the usual function to calculate beam
        // parameters. If not, calculate beam parameters of the initial
        // beam distribution.
        if(totalParticles_i == 0) {// fixme: maybe cause nonsense output if initialized momenta=0; Q: by Chuan.
            itsBunch->calcBeamParametersInitial();
        } else {
            itsBunch->calcBeamParameters();
        }

        RefPartR_suv_m = RefPartR_zxy_m = itsBunch->get_rmean();
        RefPartP_suv_m = RefPartP_zxy_m = itsBunch->get_pmean();

        if(!OpalData::getInstance()->hasBunchAllocated()) {
            updateSpaceOrientation(false);  // vec{p} = (0,0,p_z), vec{r} = (0,0,z)
        }

        RefPartR_suv_m = itsBunch->get_rmean();
        RefPartP_suv_m = itsBunch->get_pmean();
        /* Activate all elements which influence the particles when the simulation starts;
         *  mark all elements which are already past.
         */

        /*
          increase margin from 3.*c*dt to 10.*c*dt to prevent that fieldmaps are accessed
          before they are allocated when increasing the timestep in the gun.
        */
        itsBunch->get_bounds(rmin, rmax);
        margin = 10. * RefPartP_suv_m(2) * scaleFactor_m / sqrt(1.0 + dot(RefPartP_suv_m, RefPartP_suv_m));
        margin = 0.01 > margin ? 0.01 : margin;
        itsOpalBeamline_m.switchElements(rmin(2) - margin, rmax(2) + margin);
    }

    double minBinEmitted  = 10.0;
    RealVariable *ar = dynamic_cast<RealVariable *>(OpalData::getInstance()->find("MINBINEMITTED"));
    if(ar) {
        minBinEmitted = ar->getReal();  // the space charge solver crashes if we use less than ~10 particles.
        // This variable controls the number of particles to be emitted before we use
        // the space charge solver.
317
        msg << "MINBINEMITTED " << minBinEmitted << endl;
gsell's avatar
gsell committed
318 319 320 321 322 323 324 325
    }


    double minStepforReBin  = 10000.0;
    RealVariable *br = dynamic_cast<RealVariable *>(OpalData::getInstance()->find("MINSTEPFORREBIN"));
    if(br) {
        minStepforReBin = br->getReal();  // this variable controls the minimal number of steps of emission (using bins)
        // before we can merge the bins
326
        msg << "MINSTEPFORREBIN " << minStepforReBin << endl;
gsell's avatar
gsell committed
327 328 329 330 331 332
    }

    int repartFreq = 1000;
    RealVariable *rep = dynamic_cast<RealVariable *>(OpalData::getInstance()->find("REPARTFREQ"));
    if(rep) {
        repartFreq = static_cast<int>(rep->getReal());  // this variable controls the minimal number of steps until we repartition the particles
333
        msg << "REPARTFREQ " << repartFreq << endl;
gsell's avatar
gsell committed
334 335 336 337 338 339 340 341
    }

    // there is no point to do repartitioning with one node
    if(Ippl::getNodes() == 1)
        repartFreq = 1000000;

    size_t totalParticles_f = 0;

342
    for(; step < localTrackSteps_m; ++step) {
gsell's avatar
gsell committed
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 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
        global_EOL = true;  // check if any particle hasn't reached the end of the field from the last element

        itsOpalBeamline_m.resetStatus();

        IpplTimings::startTimer(timeIntegrationTimer1_m);

        // reset E and B to Vector_t(0.0) for every step

        itsBunch->Ef = Vector_t(0.0);
        itsBunch->Bf = Vector_t(0.0);

        Nimpact_m = 0; // Initial parallel plate benchmark variable.
        SeyNum_m = 0; // Initial parallel plate benchmark variable.

        for(unsigned int i = 0; i < itsBunch->getLocalNum(); ++i) {
            //scale each particle with c*dt
            itsBunch->R[i] /= vscaleFactor;
            pusher.push(itsBunch->R[i], itsBunch->P[i], itsBunch->dt[i]);
            // update local coordinate system of particleInform &PartBunc
            itsBunch->X[i] /= vscaleFactor;
            pusher.push(itsBunch->X[i], TransformTo(itsBunch->P[i], itsOpalBeamline_m.getOrientation(itsBunch->LastSection[i])),
                        itsBunch->getdT());
            itsBunch->X[i] *= vscaleFactor;
        }

        if(totalParticles_i > minBinEmitted) {
            itsBunch->boundp();
        }

        IpplTimings::stopTimer(timeIntegrationTimer1_m);

        itsBunch->calcBeamParameters();


        /** \f[ Space Charge  \f]
         */
        if(itsBunch->hasFieldSolver() && totalParticles_i > minBinEmitted && fabs(itsBunch->getChargePerParticle()) > 0.0) {
            // Do repartition if we have enough particles.
            if(totalParticles_i > 1000 && (((step + 1) % repartFreq) == 0)) {
                INFOMSG("*****************************************************************" << endl);
                INFOMSG("do repartition because of repartFreq" << endl);
                INFOMSG("*****************************************************************" << endl);
                IpplTimings::startTimer(BinRepartTimer_m);
                itsBunch->do_binaryRepart();
                IpplTimings::stopTimer(BinRepartTimer_m);
                Ippl::Comm->barrier();
                INFOMSG("*****************************************************************" << endl);
                INFOMSG("do repartition done" << endl);
                INFOMSG("*****************************************************************" << endl);
            }

            // Calculate space charge.
            if(itsBunch->weHaveBins()) {
                // When we have energy bins.
                itsBunch->calcGammas();
                ParticleAttrib<double> Q_back = itsBunch->Q;
399
                itsBunch->resetInterpolationCache();
gsell's avatar
gsell committed
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
                for(int binNumber = 0; binNumber <= itsBunch->getLastemittedBin() && binNumber < itsBunch->getNumBins(); ++binNumber) {
                    itsBunch->setBinCharge(binNumber);
                    itsBunch->computeSelfFields(binNumber);
                    itsBunch->Q = Q_back;
                }
            } else {
                // When we don't.
                itsBunch->computeSelfFields();
                /**
                    Need this maybe for the adaptive time integration scheme
                pair<Vector_t,Vector_t> eExtrema = itsBunch->getEExtrema();
                INFOMSG("maxE= " << eExtrema.first << " minE= " << eExtrema.second << endl);
                */
            }
        }

        IpplTimings::startTimer(timeIntegrationTimer2_m);


        /*
          transport and emit particles
          that passed the cathode in the first
          half-step or that would pass it in the
          second half-step.

          to make IPPL and the field solver happy
          make sure that at least 10 particles are emitted

          also remember that node 0 has
          all the particles to be emitted

          this has to be done *after* the calculation of the
          space charges! thereby we neglect space charge effects
          in the very first step of a new-born particle.

        */

        if((itsBunch->weHaveBins())) {

            // switch to TEmission
            if(!hasSwitchedToTEmission) {
                dt = itsBunch->getTBin();
                itsBunch->setdT(dt);
                scaleFactor_m = dt * Physics::c;
                vscaleFactor = Vector_t(scaleFactor_m);
445
                msg << "Changing emission time step to: " << dt << endl;
gsell's avatar
gsell committed
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
                hasSwitchedToTEmission = true;
            }

            int ne = 0;
            ne += itsBunch->emitParticles();

            if(Options::schottkyCorrection && !hasSwitchedBackToTTrack)
                applySchottkyCorrection(*itsBunch, ne, t, rescale_coeff);

            reduce(ne, ne, OpAddAssign());
            totalParticles_i += ne;

            //emission has finished, reset to TTrack
            if(itsBunch->getNumBins() == itsBunch->getLastemittedBin() &&
               !hasSwitchedBackToTTrack) {
                //dt = dtTrack;
                itsBunch->setdT(dt);
                scaleFactor_m = dt * Physics::c;
                vscaleFactor = Vector_t(scaleFactor_m);
465
                msg << "Emission done. Switching back to track timestep: " << dt << endl;
gsell's avatar
gsell committed
466 467 468 469 470 471 472 473 474 475 476
                hasSwitchedBackToTTrack = true;
                break;
            }

        } else {
            //emission has finished, reset to TTrack
            if(!hasSwitchedBackToTTrack) {
                //dt = dtTrack;
                itsBunch->setdT(dt);
                scaleFactor_m = dt * Physics::c;
                vscaleFactor = Vector_t(scaleFactor_m);
477
                msg << "Emission done. Switching back to track timestep: " << dt << endl;
gsell's avatar
gsell committed
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
                hasSwitchedBackToTTrack = true;
            }

        }

        // push the reference particle by a half step
        recpgamma = 1.0 / sqrt(1.0 + dot(RefPartP_suv_m, RefPartP_suv_m));
        RefPartR_zxy_m += RefPartP_zxy_m * recpgamma / 2. * scaleFactor_m;

        //
        // get external fields for all particles
        //
        IpplTimings::startTimer(timeFieldEvaluation_m);
        for(unsigned int i = 0; i < itsBunch->getLocalNum(); ++i) {
            //FIXME: rethink scaling!
            itsBunch->R[i] *= Vector_t(Physics::c * itsBunch->dt[i], Physics::c * itsBunch->dt[i], Physics::c * itsBunch->dt[i]);

            long ls = itsBunch->LastSection[i];
            itsOpalBeamline_m.getSectionIndexAt(itsBunch->R[i], ls);
            if(ls != itsBunch->LastSection[i]) {
                if(!itsOpalBeamline_m.section_is_glued_to(itsBunch->LastSection[i], ls)) {
                    itsBunch->ResetLocalCoordinateSystem(i, itsOpalBeamline_m.getOrientation(ls), itsOpalBeamline_m.getSectionStart(ls));
                }
                itsBunch->LastSection[i] = ls;
            }
            const unsigned long rtv = itsOpalBeamline_m.getFieldAt(i, itsBunch->R[i], ls, t + itsBunch->dt[i] / 2., externalE, externalB);

            global_EOL = global_EOL && (rtv & BEAMLINE_EOL);

            // skip rest of the particle push if the
            // particle is out of bounds i.e. does not see
            // a E or B field
            if(rtv & BEAMLINE_OOB)
                itsBunch->Bin[i] = -1;


            itsBunch->Ef[i] += externalE;
            itsBunch->Bf[i] += externalB;

            itsBunch->R[i] /= Vector_t(Physics::c * itsBunch->dt[i], Physics::c * itsBunch->dt[i], Physics::c * itsBunch->dt[i]);

            // in case a particle is pushed behind the emission surface, delete the particle

            if(itsBunch->R[i](2) < 0)
                itsBunch->Bin[i] = -1;

        }

        IpplTimings::stopTimer(timeFieldEvaluation_m);

        //        if(itsBunch->getLocalNum() == 0)
        //    global_EOL = false;

        /**
           Delete marked particles.
        */

        bool globPartOutOfBounds = (min(itsBunch->Bin) < 0);
        size_t ne = 0;
        if(globPartOutOfBounds) {
            ne = itsBunch->boundp_destroyT();
        }

        totalParticles_f = totalParticles_i - ne;
        if(ne > 0)
543
            msg << "* Deleted " << ne << " particles, remaining " << totalParticles_f << " particles" << endl; //benchmark output
gsell's avatar
gsell committed
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622

        kickParticles(pusher);

        if(totalParticles_f > 0) {
            // none of the particles is in a bending element
            updateReferenceParticle();
        }

        itsBunch->RefPart_R = RefPartR_zxy_m;
        itsBunch->RefPart_P = RefPartP_zxy_m;

        // calculate the dimensions of the bunch and add a small margin to them; then decide which elements have to be triggered
        // when an element is triggered memory is allocated and the field map is read in
        itsBunch->get_bounds(rmin, rmax);

        // trigger the elements
        margin = 3. * RefPartP_suv_m(2) * recpgamma;
        margin = 0.01 > margin ? 0.01 : margin;
        itsOpalBeamline_m.switchElements((rmin(2) - margin)*scaleFactor_m, (rmax(2) + margin)*scaleFactor_m);

        // start normal particle loop part 2 for simulation without boundary geometry.
        for(unsigned int i = 0; i < itsBunch->getLocalNum(); ++i) {
            /** \f[ \vec{x}_{n+1} = \vec{x}_{n+1/2} + \frac{1}{2}\vec{v}_{n+1/2}\quad (= \vec{x}_{n+1/2} + \frac{\Delta t}{2} \frac{\vec{\beta}_{n+1/2}\gamma_{n+1/2}}{\gamma_{n+1/2}}) \f]
             * \code
             * R[i] += 0.5 * P[i] * recpgamma;
             * \endcode
             */
            pusher.push(itsBunch->R[i], itsBunch->P[i], itsBunch->dt[i]);
            //and scale back to dimensions
            itsBunch->R[i] *= Vector_t(Physics::c * itsBunch->dt[i], Physics::c * itsBunch->dt[i], Physics::c * itsBunch->dt[i]);
            // update local coordinate system
            itsBunch->X[i] /= vscaleFactor;
            pusher.push(itsBunch->X[i], TransformTo(itsBunch->P[i], itsOpalBeamline_m.getOrientation(itsBunch->LastSection[i])), itsBunch->getdT());
            itsBunch->X[i] *= vscaleFactor;
            //reset time step if particle was emitted in the first half-step
            //the particle is now in sync with the simulation timestep
            itsBunch->dt[i] = itsBunch->getdT();
        }

        IpplTimings::stopTimer(timeIntegrationTimer2_m);

        if(totalParticles_f > minBinEmitted)
            itsBunch->boundp();

        totalParticles_i = itsBunch->getTotalNum();


        t += itsBunch->getdT(); //t after a full global timestep with dT "synchronization point" for simulation time

        itsBunch->setT(t);

        //IFF: cheap step dump regulation
        OPALTimer::Timer myt2;
        double sposRef = 0.0;
        if(totalParticles_f > 0) {
            sposRef = itsBunch->get_sPos();
            if(totalParticles_f <= minBinEmitted) {
                INFOMSG(myt2.time() << " Step " << step << "; only " << totalParticles_f << " particles emitted; t= " << t
                        << " [s] E=" << itsBunch->get_meanEnergy() << " [MeV] " << endl);
            } else if(std::isnan(sposRef) || std::isinf(sposRef)) {
                INFOMSG(myt2.time() << " Step " << step << "; there seems to be something wrong with the position of the bunch!" << endl);
            } else {
                INFOMSG(myt2.time() << " Step " << step << " at " << sposRef << " [m] t= " << t << " [s] E=" << itsBunch->get_meanEnergy() << " [MeV] " << endl);
                if(step % Options::psDumpFreq == 0 || step % Options::statDumpFreq == 0) {
                    size_t nLoc = itsBunch->getLocalNum();
                    reduce(nLoc, nLoc, OpMultipplyAssign());
                    if((nLoc == 0) || ((step + 1) % repartFreq == 0)) {
                        INFOMSG("*****************************************************************" << endl);
                        INFOMSG("do repartition because of zero particles or repartition frequency" << endl);
                        IpplTimings::startTimer(BinRepartTimer_m);
                        itsBunch->do_binaryRepart();
                        IpplTimings::stopTimer(BinRepartTimer_m);
                        Ippl::Comm->barrier();
                        INFOMSG("done" << endl);
                        INFOMSG("*****************************************************************" << endl);
                    }
                }
            }
            /**
623
               Stop simulation if beyond zStop_m
gsell's avatar
gsell committed
624
            */
625
            if(sposRef > zStop_m) {
626
                localTrackSteps_m = step;
gsell's avatar
gsell committed
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
            }
        } else {
            INFOMSG("Step " << step << " no emission yet "  << " t= " << t << " [s]" << endl);
        }

        if(step > emissionSteps) {
            reduce(&global_EOL, &global_EOL + 1, &global_EOL, OpBitwiseAndAssign());
            if(global_EOL) {
                break;
            }
        }
        // this seams to fix Ticket #12
        //  Ippl::Comm->barrier();
        itsBunch->get_bounds(rmin, rmax);
        // trigger the elements
        RefPartP_suv_m = itsBunch->get_pmean();
        recpgamma = 1. / sqrt(1.0 + dot(RefPartP_suv_m, RefPartP_suv_m));

        margin = 10. * RefPartP_suv_m(2) * recpgamma * scaleFactor_m;
        margin = 0.01 > margin ? 0.01 : margin;
    }
    OPALTimer::Timer myt3;
    OpalData::getInstance()->setLastStep(step);
650
    msg << "done executing Schottky loop " << myt3.time() << endl;
gsell's avatar
gsell committed
651 652 653 654
    return itsBunch->getCharge();
}


655
void ParallelTTracker::checkCavity(double s, Component *& comp, double & cavity_start_pos) {
gsell's avatar
gsell committed
656

657 658 659 660 661 662 663 664
    comp = NULL;
    for(FieldList::iterator fit = cavities_m.begin(); fit != cavities_m.end(); ++ fit) {
        if((fit != currently_ap_cavity_m)
           && ((*fit).getStart() <= s) && (s <= (*fit).getEnd())) {
            comp = (*fit).getElement();
            cavity_start_pos = (*fit).getStart();
            currently_ap_cavity_m = fit;
            return;
gsell's avatar
gsell committed
665
        }
666
    }
gsell's avatar
gsell committed
667 668
}

669
void ParallelTTracker::doOneStep(BorisPusher & pusher) {
gsell's avatar
gsell committed
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
    bool global_EOL = true;  //check if any particle hasn't reached the end of the field from the last element
    unsigned long bends = 0;

    double recpgamma;
    double t = itsBunch->getT();

    const Vector_t vscaleFactor = Vector_t(scaleFactor_m);

    Vector_t externalE, externalB;

    Vector_t rmin, rmax;

    itsOpalBeamline_m.resetStatus();

    //reset E and B to Vector_t(0.0) for every step

    itsBunch->Ef = Vector_t(0.0);
    itsBunch->Bf = Vector_t(0.0);

    for(unsigned int i = 0; i < itsBunch->getLocalNum(); ++i) {
        //scale each particle with c*dt
        itsBunch->R[i] /= vscaleFactor;

        pusher.push(itsBunch->R[i], itsBunch->P[i], itsBunch->dt[i]);

        // update local coordinate system of particle
        itsBunch->X[i] /= vscaleFactor;
        pusher.push(itsBunch->X[i], TransformTo(itsBunch->P[i],
                                                itsOpalBeamline_m.getOrientation(itsBunch->LastSection[i])), itsBunch->dt[0]);
        itsBunch->X[i] *= vscaleFactor;
    }
    //    itsBunch->calcBeamParameters();

    // push the reference particle by a half step
    recpgamma = 1.0 / sqrt(1.0 + dot(RefPartP_suv_m, RefPartP_suv_m));
    RefPartR_zxy_m += RefPartP_zxy_m * recpgamma / 2. * scaleFactor_m;

    //
    // get external fields for all particles
    //
    for(unsigned int i = 0; i < itsBunch->getLocalNum(); ++i) {
        //FIXME: rethink scaling!
        itsBunch->R[i] *= Vector_t(Physics::c * itsBunch->dt[i], Physics::c
                                   * itsBunch->dt[i], Physics::c * itsBunch->dt[i]);

        long ls = itsBunch->LastSection[i];
        itsOpalBeamline_m.getSectionIndexAt(itsBunch->R[i], ls);
        if(ls != itsBunch->LastSection[i]) {
            if(!itsOpalBeamline_m.section_is_glued_to(itsBunch->LastSection[i], ls)) {
                itsBunch->ResetLocalCoordinateSystem(i, itsOpalBeamline_m.getOrientation(ls),
                                                     itsOpalBeamline_m.getSectionStart(ls));
            }
            itsBunch->LastSection[i] = ls;
        }
        const unsigned long rtv = itsOpalBeamline_m.getFieldAt(i, itsBunch->R[i], ls,
                                  t + itsBunch->dt[i] / 2., externalE, externalB);
        global_EOL = global_EOL && (rtv & BEAMLINE_EOL);

        bends = bends || (rtv & BEAMLINE_BEND);

        // skip rest of the particle push if the
        // particle is out of bounds i.e. does not see
        // a E or B field
        if(rtv & BEAMLINE_OOB)
            itsBunch->Bin[i] = -1;

        itsBunch->Ef[i] += externalE;
        itsBunch->Bf[i] += externalB;

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

    kickParticlesAutophase(pusher);

    if(bends == 0) {
        updateReferenceParticleAutophase();
    } else {
748 749 750 751 752 753 754 755
        /*
           at least one of the elements bends the beam; until all
           particles have left the bending elements we track the
           reference particle as if it were a regular particle; from
           the moment when the reference particle has reached the
           bending field until it leaves it again we rotate the bunch
           about the position of the reference particle such that the
           momentum of the reference particle points in z direction
gsell's avatar
gsell committed
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 817 818
         */
        RefPartP_suv_m = itsBunch->P[0];
        RefPartR_suv_m = itsBunch->R[0];
        recpgamma = 1. / sqrt(1.0 + dot(RefPartP_suv_m, RefPartP_suv_m));
        updateSpaceOrientation(false);

        // First update the momentum of the reference particle in zxy coordinate system, then update its position
        RefPartP_zxy_m = dot(space_orientation_m, RefPartP_suv_m);
        RefPartR_zxy_m += RefPartP_zxy_m * recpgamma * scaleFactor_m / 2.;

        RefPartP_suv_m = Vector_t(0.0, 0.0, sqrt(dot(RefPartP_suv_m, RefPartP_suv_m)));
        RefPartR_suv_m += RefPartP_suv_m * recpgamma / 2.;
        RefPartR_suv_m *= vscaleFactor;
    }

    itsBunch->RefPart_R = RefPartR_zxy_m;
    itsBunch->RefPart_P = RefPartP_zxy_m;

    // calculate the dimensions of the bunch and add a small margin to them;
    // then decide which elements have to be triggered
    // when an element is triggered memory is allocated and the field map is read in
    rmin = rmax = itsBunch->R[0];

    // trigger the elements
    double margin = 3. * RefPartP_suv_m(2) * recpgamma;
    margin = 0.01 > margin ? 0.01 : margin;
    itsOpalBeamline_m.switchElements((rmin(2) - margin)*scaleFactor_m, (rmax(2) + margin)*scaleFactor_m, true);

    // start particle loop part 2
    for(unsigned int i = 0; i < itsBunch->getLocalNum(); ++i) {
        /** \f[ \vec{x}_{n+1} = \vec{x}_{n+1/2} + \frac{1}{2}\vec{v}_{n+1/2}\quad (= \vec{x}_{n+1/2} +
            \frac{\Delta t}{2} \frac{\vec{\beta}_{n+1/2}\gamma_{n+1/2}}{\gamma_{n+1/2}}) \f]
            * \code
            * R[i] += 0.5 * P[i] * recpgamma;
            * \endcode
            */
        pusher.push(itsBunch->R[i], itsBunch->P[i], itsBunch->dt[i]);
        //and scale back to dimensions
        itsBunch->R[i] *= Vector_t(Physics::c * itsBunch->dt[i], Physics::c * itsBunch->dt[i],
                                   Physics::c * itsBunch->dt[i]);
        // update local coordinate system
        itsBunch->X[i] /= vscaleFactor;
        pusher.push(itsBunch->X[i], TransformTo(itsBunch->P[i],
                                                itsOpalBeamline_m.getOrientation(itsBunch->LastSection[i])), itsBunch->dt[0]);
        itsBunch->X[i] *= vscaleFactor;
    }

    t += itsBunch->dt[0]; //t after a full global timestep with dT "synchronization point" for simulation time

    itsBunch->setT(t);
}


void ParallelTTracker::applyEntranceFringe(double angle, double curve,
        const BMultipoleField &field, double scale) {
}


void ParallelTTracker::applyExitFringe(double angle, double curve,
                                       const BMultipoleField &field, double scale) {
}


819
void ParallelTTracker::showCavities(Inform &msg) {
gsell's avatar
gsell committed
820

821
    msg << "Found the following cavities:" << endl;
gsell's avatar
gsell committed
822 823

    for(FieldList::iterator fit = cavities_m.begin(); fit != cavities_m.end(); ++ fit) {
824 825 826
        msg << (*fit).getElement()->getName()
            << " from " << (*fit).getStart() << " to "
            << (*fit).getEnd() << " (m) phi=";
gsell's avatar
gsell committed
827
        if((*fit).getElement()->getType() == "TravelingWave")
828
            msg << static_cast<TravelingWave *>((*fit).getElement())->getPhasem() / Physics::pi * 180.0 << endl;
gsell's avatar
gsell committed
829
        else
830
            msg << static_cast<RFCavity *>((*fit).getElement())->getPhasem() / Physics::pi * 180.0 << endl;
gsell's avatar
gsell committed
831
    }
832
    msg << endl << endl;
gsell's avatar
gsell committed
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
}


void ParallelTTracker::updateRFElement(string elName, double maxPhi) {
    /**
       The maximum phase is added to the nominal phase of
       the element. This is done on all nodes except node 0 where
       the Autophase took place.
    */
    double phi  = 0.0;
    for(FieldList::iterator fit = cavities_m.begin(); fit != cavities_m.end(); ++ fit) {
        if((*fit).getElement()->getName() == elName) {
            if((*fit).getElement()->getType() == "TravelingWave") {
                phi  =  static_cast<TravelingWave *>((*fit).getElement())->getPhasem();
                phi += maxPhi;
                static_cast<TravelingWave *>((*fit).getElement())->updatePhasem(phi);
            } else {
                phi  = static_cast<RFCavity *>((*fit).getElement())->getPhasem();
                phi += maxPhi;
                static_cast<RFCavity *>((*fit).getElement())->updatePhasem(phi);
            }
        }
    }
}


void ParallelTTracker::updateAllRFElements(double phiShift) {
    /**
       All RF-Elements gets updated, where the phiShift is the
       global phase shift in units of seconds.
    */
864
    Inform msg("ParallelTTracker ");
gsell's avatar
gsell committed
865 866 867 868
    double phi = 0;
    double freq = 0.0;
    const double RADDEG = 1.0 / Physics::pi * 180.0;
    //   Inform m ("updateALLRFElements ",INFORM_ALL_NODES);
869
    msg << "\n-------------------------------------------------------------------------------------\n";
gsell's avatar
gsell committed
870 871
    for(FieldList::iterator fit = cavities_m.begin(); fit != cavities_m.end(); ++ fit) {
        if(fit != cavities_m.begin())
872
            msg << "\n";
gsell's avatar
gsell committed
873 874 875
        if((*fit).getElement()->getType() == "TravelingWave") {
            freq = static_cast<TravelingWave *>((*fit).getElement())->getFrequencym();
            phi = static_cast<TravelingWave *>((*fit).getElement())->getPhasem();
876
            msg << (*fit).getElement()->getName()
gsell's avatar
gsell committed
877 878 879 880 881 882 883
                  << ": phi_orig= phi_nom + phi_maxE= " << phi *RADDEG << " degree, "
                  << "global phase shift= " << -phiShift *freq *RADDEG << " degree\n";
            phi -= (phiShift * freq);
            static_cast<TravelingWave *>((*fit).getElement())->updatePhasem(phi);
        } else {
            freq = static_cast<RFCavity *>((*fit).getElement())->getFrequencym();
            phi = static_cast<RFCavity *>((*fit).getElement())->getPhasem();
884
            msg << (*fit).getElement()->getName()
gsell's avatar
gsell committed
885 886 887 888 889 890
                  << ": phi_orig= phi_nom + phi_maxE= " << phi *RADDEG << " degree, "
                  << "global phase shift= " << -phiShift *freq *RADDEG << " degree\n";
            phi -= (phiShift * freq);
            static_cast<RFCavity *>((*fit).getElement())->updatePhasem(phi);
        }
    }
891
    msg << "-------------------------------------------------------------------------------------\n"
gsell's avatar
gsell committed
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
          << endl;
}


FieldList ParallelTTracker::executeAutoPhaseForSliceTracker() {
    Inform msg("executeAutoPhaseForSliceTracker ");

    double gPhaseSave;

    gPhaseSave = OpalData::getInstance()->getGlobalPhaseShift();
    OpalData::getInstance()->setGlobalPhaseShift(0.0);

    itsBeamline_m.accept(*this);
    // make sure that no monitor has overlap with two tracks
    FieldList monitors = itsOpalBeamline_m.getElementByType("Monitor");
    for(FieldList::iterator it = monitors.begin(); it != monitors.end(); ++ it) {
        double zbegin, zend;
        it->getElement()->getDimensions(zbegin, zend);
910
        if(zbegin < zStop_m && zend >= zStop_m) {
911
            msg << "\033[0;31m"
gsell's avatar
gsell committed
912 913 914 915 916 917 918 919 920 921 922 923 924
                  << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"
                  << "% Removing '" << it->getElement()->getName() << "' since it resides in two tracks.   %\n"
                  << "% Please adjust zstop or place your monitor at a different position to prevent this. %\n "
                  << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"
                  << "\033[0m"
                  << endl;
            static_cast<Monitor *>(it->getElement())->moveBy(-zend - 0.001);
            itsOpalBeamline_m.removeElement(it->getElement()->getName());
        }
    }
    itsOpalBeamline_m.prepareSections();

    cavities_m = itsOpalBeamline_m.getElementByType("RFCavity");
925
    currently_ap_cavity_m = cavities_m.end();
926 927
    FieldList travelingwaves = itsOpalBeamline_m.getElementByType("TravelingWave");
    cavities_m.merge(travelingwaves, OpalField::SortAsc);
gsell's avatar
gsell committed
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958

    int tag = 101;
    int Parent = 0;
    Vector_t iniR(0.0);
    Vector_t iniP(0.0, 0.0, 1E-6);
    PID_t id;
    Ppos_t r, p, x;
    ParticleAttrib<double> q, dt;
    ParticleAttrib<int> bin;
    ParticleAttrib<long> ls;
    ParticleAttrib<short> ptype;

    double zStop = itsOpalBeamline_m.calcBeamlineLenght();

    msg << "Preparation done zstop= " << zStop << endl;


    if(Ippl::myNode() == 0) {
        itsBunch->create(1);
        itsBunch->R[0] = iniR;
        itsBunch->P[0] = iniP;
        itsBunch->Bin[0] = 0;
        itsBunch->Q[0] = itsBunch->getChargePerParticle();
        itsBunch->PType[0] = 0;
        itsBunch->LastSection[0] = 0;

        executeAutoPhase(Options::autoPhase, zStop);
        itsBunch->destroy(1, 0);

        // need to rebuild for updateAllRFElements
        cavities_m = itsOpalBeamline_m.getElementByType("RFCavity");
959 960
        travelingwaves = itsOpalBeamline_m.getElementByType("TravelingWave");
        cavities_m.merge(travelingwaves, OpalField::SortAsc);
gsell's avatar
gsell committed
961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999


        // now send all max phases and names of the cavities to
        // all the other nodes for updating.
        Message *mess = new Message();
        putMessage(*mess, OpalData::getInstance()->getNumberOfMaxPhases());

        for(vector<MaxPhasesT>::iterator it = OpalData::getInstance()->getFirstMaxPhases(); it < OpalData::getInstance()->getLastMaxPhases(); it++) {
            putMessage(*mess, (*it).first);
            putMessage(*mess, (*it).second);
        }
        Ippl::Comm->broadcast_all(mess, tag);
    } else {
        // receive max phases and names and update the structures
        int nData = 0;
        Message *mess = Ippl::Comm->receive_block(Parent, tag);
        getMessage(*mess, nData);
        for(int i = 0; i < nData; i++) {
            string elName;
            double maxPhi;
            getMessage(*mess, elName);
            getMessage(*mess, maxPhi);
            updateRFElement(elName, maxPhi);
            OpalData::getInstance()->setMaxPhase(elName, maxPhi);
        }
    }

    OpalData::getInstance()->setGlobalPhaseShift(gPhaseSave);
    return cavities_m;
}


void ParallelTTracker::executeAutoPhase(int numRefs, double zStop) {
    Inform msg("Autophasing ");

    const double RADDEG = 180.0 / Physics::pi;

    Vector_t rmin, rmax;

1000
    size_t maxStepsSave = localTrackSteps_m;
gsell's avatar
gsell committed
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
    size_t step = 0;
    int dtfraction = 2;
    itsBunch->dt = itsBunch->getdT() / dtfraction;         // need to fix this and make the factor 2 selectable

    double scaleFactorSave = scaleFactor_m;
    scaleFactor_m = itsBunch->dt[0] * Physics::c;

    double tSave = itsBunch->getT();


    Vector_t vscaleFactor = Vector_t(scaleFactor_m);

    BorisPusher pusher(itsReference);

    msg << "\n"
        << "start at t= " << itsBunch->getT() << " [s], zstop at: "
        << zStop << " [m], Nplocal= " << itsBunch->getLocalNum() << "\n"
        << "initial DT " << itsBunch->dt[0] << " [s], step= "
        << step << ", R =  " << itsBunch->R[0] << " [m]" << endl;

    //    showCavities(m);

    for(unsigned int i = 0; i < itsBunch->getLocalNum(); ++i) {
        long &l = itsBunch->LastSection[i];
        l = -1;
        itsOpalBeamline_m.getSectionIndexAt(itsBunch->R[i], l);
        itsBunch->ResetLocalCoordinateSystem(i, itsOpalBeamline_m.getOrientation(l),
                                             itsOpalBeamline_m.getSectionStart(l));
    }

    RefPartR_suv_m = RefPartR_zxy_m = rmin = rmax = itsBunch->R[0];
    RefPartP_suv_m = RefPartP_zxy_m = itsBunch->P[0];

    /* Activate all elements which influence the particles when the simulation starts;
     * mark all elements which are already past.
     *
     * Increase margin from 3.*c*dt to 10.*c*dt to prevent that fieldmaps are accessed
     * before they are allocated when increasing the timestep in the gun.
     */

    double margin = 10. * RefPartP_suv_m(2) * scaleFactor_m / sqrt(1.0 + dot(RefPartP_suv_m, RefPartP_suv_m));

    margin = 0.01 > margin ? 0.01 : margin;

    itsOpalBeamline_m.switchElements(rmin(2) - margin, rmax(2) + margin, true);

1047 1048 1049
    double cavity_start = 0.0;
    Component *cavity = NULL;

1050
    for(; step < localTrackSteps_m * dtfraction; ++step) {
gsell's avatar
gsell committed
1051 1052 1053 1054 1055

        // let's do a drifting step to probe if the particle will reach element in next step
        Vector_t R_drift = itsBunch->R[0] + itsBunch->P[0] / sqrt(1.0 + dot(itsBunch->P[0],
                           itsBunch->P[0])) * vscaleFactor;

1056
        checkCavity(R_drift[2], cavity, cavity_start);
gsell's avatar
gsell committed
1057

1058
        if(cavity != NULL) {
gsell's avatar
gsell committed
1059
            double orig_phi = 0.0;
1060
            double Phimax = 0.0, Emax = 0.0;
gsell's avatar
gsell committed
1061 1062 1063
            double PhiAstra;
            //////
            const double beta = sqrt(1. - 1 / (itsBunch->P[0](2) * itsBunch->P[0](2) + 1.));
1064
            const double tErr  = (cavity_start - itsBunch->R[0](2)) / (Physics::c * beta);
gsell's avatar
gsell committed
1065 1066 1067

            bool apVeto;

1068
            INFOMSG("Found " << cavity->getName()
gsell's avatar
gsell committed
1069 1070 1071 1072 1073 1074 1075
                    << " at " << itsBunch->R[0](2) << " [m], "
                    << "step  " << step << ", "
                    << "t= " << itsBunch->getT() << " [s],\n"
                    << "E= " << getEnergyMeV(itsBunch->P[0]) << " [MeV]\n"
                    << "start phase scan ... " << endl);

            INFOMSG("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n");
1076 1077 1078 1079
            if(cavity->getType() == "TravelingWave") {
                orig_phi = static_cast<TravelingWave *>(cavity)->getPhasem();
                apVeto = static_cast<TravelingWave *>(cavity)->getAutophaseVeto();
                if(apVeto) {
gsell's avatar
gsell committed
1080
                    msg << " ----> APVETO -----> "
1081 1082 1083 1084
                        << static_cast<TravelingWave *>(cavity)->getName() <<  endl;
                    Phimax = orig_phi;
                }
                INFOMSG(cavity->getName() << ", "
gsell's avatar
gsell committed
1085 1086 1087 1088
                        << "start Ekin= " << getEnergyMeV(itsBunch->P[0]) << " MeV, "
                        << "t= " << itsBunch->getT() << " s, "
                        << "phi= " << orig_phi << ", " << endl;);

1089 1090
                if(!apVeto) {
                    TravelingWave *element = static_cast<TravelingWave *>(cavity);
gsell's avatar
gsell committed
1091 1092 1093 1094 1095 1096
                    Phimax = element->getAutoPhaseEstimate(getEnergyMeV(itsBunch->P[0]),
                                                           itsBunch->getT() + tErr,
                                                           itsReference.getQ(),
                                                           itsReference.getM() * 1e-6);
                }
            } else {
1097 1098 1099
                orig_phi = static_cast<RFCavity *>(cavity)->getPhasem();
                apVeto = static_cast<RFCavity *>(cavity)->getAutophaseVeto();
                if(apVeto) {
gsell's avatar
gsell committed
1100
                    msg << " ----> APVETO -----> "
1101 1102 1103 1104
                        << static_cast<RFCavity *>(cavity)->getName() << endl;
                    Phimax = orig_phi;
                }
                INFOMSG(cavity->getName() << ", "
gsell's avatar
gsell committed
1105 1106 1107 1108
                        << "start Ekin= " << getEnergyMeV(itsBunch->P[0]) << " MeV, "
                        << "t= " << itsBunch->getT() << " s, "
                        << "phi= " << orig_phi << ", " << endl;);

1109 1110
                if(!apVeto) {
                    RFCavity *element = static_cast<RFCavity *>(cavity);
gsell's avatar
gsell committed
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
                    Phimax = element->getAutoPhaseEstimate(getEnergyMeV(itsBunch->P[0]),
                                                           itsBunch->getT() + tErr,
                                                           itsReference.getQ(),
                                                           itsReference.getM() * 1e-6);
                }
            }

            double Phiini = Phimax;
            double phi = Phiini;
            double dphi = Physics::pi / 360.0;
            int j = -1;

1123
            double E = APtrack(cavity, cavity_start, phi);
gsell's avatar
gsell committed
1124
            if(!apVeto) {
1125
                msg << "Did APtrack with phi= " << phi << " result E= " << E << endl;
gsell's avatar
gsell committed
1126 1127 1128 1129 1130 1131 1132
                INFOMSG("do fine scan around effective max energy (" << E << " MeV)" << ", dphi= " << dphi << endl;);
                do {
                    j ++;
                    Emax = E;
                    Phiini = phi;
                    phi -= dphi;
                    INFOMSG("try phi= " << phi << " rad -> DEkin= ";);
1133
                    E = APtrack(cavity, cavity_start, phi);
gsell's avatar
gsell committed
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
                    if(E > Emax) {
                        INFOMSG(E - Emax << " MeV: accepted" << endl;);
                    } else {
                        INFOMSG(E - Emax << " MeV: rejected" << " E= " << E << " Emax= " << Emax << endl;);
                    }
                } while(E > Emax);

                if(j == 0) {
                    phi = Phiini;
                    E = Emax;
                    j = -1;
                    do {
                        j ++;
                        Emax = E;
                        Phiini = phi;
                        phi += dphi;
                        INFOMSG("try phi= " << phi << " rad -> DEkin= ";);
1151
                        E = APtrack(cavity, cavity_start, phi);
gsell's avatar
gsell committed
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
                        if(E > Emax) {
                            INFOMSG(E - Emax << " MeV: accepted" << endl;);
                        } else {
                            INFOMSG(E - Emax << " MeV: rejected" << endl;);
                        }
                    } while(E > Emax);
                }
                for(int refinement_level = 0; refinement_level < numRefs; refinement_level ++) {
                    dphi /= 2.;
                    INFOMSG("refinement level: " << refinement_level + 1 << ", dphi= " << dphi << endl;);
                    phi = Phiini - dphi;
                    INFOMSG("try phi= " << phi << " rad -> DEkin= ";);
1164
                    E = APtrack(cavity, cavity_start, phi);
gsell's avatar
gsell committed
1165 1166 1167 1168 1169 1170 1171 1172
                    if(E > Emax) {
                        INFOMSG(E - Emax << " MeV: accepted" << endl;);
                        Phiini = phi;
                        Emax = E;
                    } else {
                        INFOMSG(E - Emax << " MeV: rejected" << endl;);
                        phi = Phiini + dphi;
                        INFOMSG("try phi= " << phi << " rad -> DEkin= ";);
1173
                        E = APtrack(cavity, cavity_start, phi);
gsell's avatar
gsell committed
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
                        if(E > Emax) {
                            INFOMSG(E - Emax << " MeV: accepted" << endl;);
                            Phiini = phi;
                            Emax = E;
                        } else {
                            INFOMSG(E - Emax << " MeV: rejected" << endl;);
                        }
                    }
                }
                Phimax = Phiini;
1184
                phi = Phimax + orig_phi;
gsell's avatar
gsell committed
1185 1186
                INFOMSG("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n");
            } else {
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197

                msg << "Tracking with phi= " << orig_phi << " result E= " << E << endl;
                phi = orig_phi;
                Emax = E;
                E = APtrack(cavity, cavity_start, phi - Physics::pi);
                msg << "Tracking with phi= " << orig_phi - Physics::pi << " result E= " << E << endl;
                if (E > Emax) {
                    phi = orig_phi - Physics::pi;
                    Phimax = phi;
                    Emax = E;
                }
gsell's avatar
gsell committed
1198 1199 1200
            }


1201 1202
            if(cavity->getType() == "TravelingWave") {
                static_cast<TravelingWave *>(cavity)->updatePhasem(phi);
gsell's avatar
gsell committed
1203
            } else {
1204
                static_cast<RFCavity *>(cavity)->updatePhasem(phi);
gsell's avatar
gsell committed
1205 1206 1207 1208 1209
            }

            PhiAstra = (Phimax * RADDEG) + 90.0;
            PhiAstra -= floor(PhiAstra / 360.) * 360.;

1210
            msg << cavity->getName() << "_phi= "  << Phimax << " rad / "
gsell's avatar
gsell committed
1211 1212 1213
                << Phimax *RADDEG <<  " deg, AstraPhi= " << PhiAstra << " deg,\n"
                << "E= " << Emax << " (MeV), " << "phi_nom= " << orig_phi *RADDEG << endl;

1214 1215
            OpalData::getInstance()->setMaxPhase(cavity->getName(), Phimax);
            //cavities_m.erase(res.first);
gsell's avatar
gsell committed
1216 1217 1218
        }

        doOneStep(pusher);
1219
        //checkCavity(itsBunch->R[0](2), cavity, cavity_start);
gsell's avatar
gsell committed
1220 1221 1222
        double sposRef = itsBunch->R[0](2);

        if(sposRef > zStop)
1223
            localTrackSteps_m = floor(step / dtfraction);
gsell's avatar
gsell committed
1224 1225 1226 1227 1228 1229

        if(!(step % 1000)) {
            INFOMSG("step = " << step << ", spos = " << sposRef << " [m], t= " << itsBunch->getT() << " [s], "
                    << "E= " << getEnergyMeV(itsBunch->P[0]) << " [MeV] " << endl);
        }
    }
1230
    localTrackSteps_m = maxStepsSave;
gsell's avatar
gsell committed
1231 1232 1233 1234
    scaleFactor_m = scaleFactorSave;
    itsBunch->setT(tSave);
}

1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
double ParallelTTracker::APtrack(Component *cavity, double cavity_start_pos, const double &phi) const {
    double beta = std::max(sqrt(1. - 1 / (itsBunch->P[0](2) * itsBunch->P[0](2) + 1.)), 0.0001);
    double tErr  = (cavity_start_pos - itsBunch->R[0](2)) / (Physics::c * beta);

    INFOMSG("beta = " << beta << " tErr = " << tErr << endl;);

    double finalMomentum = 0.0;
    if(cavity->getType() == "TravelingWave") {
        TravelingWave *tws = static_cast<TravelingWave *>(cavity);
        tws->updatePhasem(phi);
        std::pair<double, double> pe = tws->trackOnAxisParticle(itsBunch->P[0](2),
                                                                itsBunch->getT() + tErr,
                                                                itsBunch->dt[0],
                                                                itsBunch->getQ(),
                                                                itsBunch->getM() * 1e-6);
        finalMomentum = pe.first;
    } else {
        RFCavity *rfc = static_cast<RFCavity *>(cavity);
        rfc->updatePhasem(phi);

        std::pair<double, double> pe = rfc->trackOnAxisParticle(itsBunch->P[0](2),
                                                                itsBunch->getT() + tErr,
                                                                itsBunch->dt[0],
                                                                itsBunch->getQ(),
                                                                itsBunch->getM() * 1e-6);
        finalMomentum = pe.first;
    }
    double finalGamma = sqrt(1.0 + finalMomentum * finalMomentum);
    double finalKineticEnergy = (finalGamma - 1.0) * itsBunch->getM() * 1e-6;
    return finalKineticEnergy;
}

gsell's avatar
gsell committed
1267
void ParallelTTracker::execute() {
1268
    Inform msg("ParallelTTracker ");
1269 1270 1271 1272
    const Vector_t vscaleFactor_m = Vector_t(scaleFactor_m);
    BorisPusher pusher(itsReference);
    secondaryFlg_m = false;
    dtTrack_m = itsBunch->getdT();
gsell's avatar
gsell committed
1273

1274 1275 1276 1277
    // upper limit of particle number when we do field emission and secondary emission
    // simulation. Could be reset to another value in input file with MAXPARTSNUM.
    maxNparts_m = 100000000;
    nEmissionMode_m = true;
gsell's avatar
gsell committed
1278

1279
    prepareSections();
gsell's avatar
gsell committed
1280

1281 1282
    // do autophasing before tracking without a global phase shift!
    doAutoPhasing();
1283

1284
    numParticlesInSimulation_m = itsBunch->getTotalNum();
gsell's avatar
gsell committed
1285

1286
    OPALTimer::Timer myt1;
gsell's avatar
gsell committed
1287

1288
    setTime();
1289

1290
    double t = itsBunch->getT();
1291 1292

    unsigned long long step = itsBunch->getLocalTrackStep();
1293

1294
    msg << "Track start at: " << myt1.time() << ", t= " << t << "; zstop at: " << zStop_m << " [m]" << endl;
1295 1296 1297 1298 1299 1300

    gunSubTimeSteps_m = 10;
    prepareEmission();

    doSchottyRenormalization();

1301
    msg << "Executing ParallelTTracker, initial DT " << itsBunch->getdT() << " [s];\n"
1302
        << "max integration steps " << localTrackSteps_m << ", next step= " << step << endl;
1303 1304 1305

    // itsBeamline_m.accept(*this);
    // itsOpalBeamline_m.prepareSections();
1306
    itsOpalBeamline_m.print(msg);
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324

    setupSUV();

    // increase margin from 3.*c*dt to 10.*c*dt to prevent that fieldmaps are accessed
    // before they are allocated when increasing the timestep in the gun.
    switchElements(10.0);

    initializeBoundaryGeometry();

    setOptionalVariables();

    // there is no point to do repartitioning with one node
    if(Ippl::getNodes() == 1)
        repartFreq_m = 1000000;

    wakeStatus_m = false;
    surfaceStatus_m = false;

1325
    for(; step < localTrackSteps_m; ++step) {
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 1356 1357 1358
        bends_m = 0;
        numberOfFieldEmittedParticles_m = 0;

        itsOpalBeamline_m.resetStatus();

        timeIntegration1(pusher);
        timeIntegration1_bgf(pusher);

        itsBunch->calcBeamParameters();

        // reset E and B to Vector_t(0.0) for every step
        itsBunch->Ef = Vector_t(0.0);
        itsBunch->Bf = Vector_t(0.0);

        doBinaryRepartition(step);
        computeSpaceChargeFields();

        selectDT();
        emitParticles(step);
        selectDT();

        computeExternalFields();

        timeIntegration2(pusher);
        timeIntegration2_bgf(pusher);

        bgf_main_collision_test();

        //t after a full global timestep with dT "synchronization point" for simulation time
        t += itsBunch->getdT();
        itsBunch->setT(t);

        dumpStats(step);
gsell's avatar
gsell committed
1359

1360
        if(hasEndOfLineReached()) break;
gsell's avatar
gsell committed
1361

1362
        double margin = 0.1;
1363
        switchElements(margin);
1364 1365 1366

        itsBunch->incTrackSteps();

1367
    }
1368

1369 1370 1371 1372 1373 1374 1375
    if(numParticlesInSimulation_m > minBinEmitted_m) {
        itsBunch->boundp();
        numParticlesInSimulation_m = itsBunch->getTotalNum();
    }

    bool doDump = true;
    writePhaseSpace((step + 1), itsBunch->get_sPos(), doDump);
1376
    msg << "Dump phase space of last step" << endl;
1377 1378
    OPALTimer::Timer myt3;
    itsOpalBeamline_m.switchElementsOff();
1379
    msg << "done executing ParallelTTracker at " << myt3.time() << endl;
1380
}
gsell's avatar
gsell committed
1381 1382


1383 1384 1385 1386 1387
/**
 *  COMPONENTS
 */

double ParallelTTracker::getGlobalPhaseShift() {
gsell's avatar
gsell committed
1388 1389

    if(Options::autoPhase > 0) {
1390
        double gPhaseSave = OpalData::getInstance()->getGlobalPhaseShift();
gsell's avatar
gsell committed
1391
        OpalData::getInstance()->setGlobalPhaseShift(0.0);
1392 1393 1394
        return gPhaseSave;
    } else
        return 0;
gsell's avatar
gsell committed
1395

1396
}
gsell's avatar
gsell committed
1397

1398
void ParallelTTracker::handleOverlappingMonitors() {
gsell's avatar
gsell committed
1399
    // make sure that no monitor has overlap with two tracks
1400
    Inform msg("ParallelTTracker ");
gsell's avatar
gsell committed
1401 1402 1403 1404
    FieldList monitors = itsOpalBeamline_m.getElementByType("Monitor");
    for(FieldList::iterator it = monitors.begin(); it != monitors.end(); ++ it) {
        double zbegin, zend;
        it->getElement()->getDimensions(zbegin, zend);
1405
        if(zbegin < zStop_m && zend >= zStop_m) {
1406
            msg << "\033[0;31m"
gsell's avatar
gsell committed
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416
                  << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"
                  << "% Removing '" << it->getElement()->getName() << "' since it resides in two tracks.   %\n"
                  << "% Please adjust zstop or place your monitor at a different position to prevent this. %\n "
                  << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"
                  << "\033[0m"
                  << endl;
            static_cast<Monitor *>(it->getElement())->moveBy(-zend - 0.001);
            itsOpalBeamline_m.removeElement(it->getElement()->getName());
        }
    }
1417
}
gsell's avatar
gsell committed
1418