ParallelTTracker.cpp 112 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
// ------------------------------------------------------------------------
// $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 $
//
// ------------------------------------------------------------------------

kraus's avatar
kraus committed
20 21
#include "Algorithms/ParallelTTracker.h"

gsell's avatar
gsell committed
22 23 24 25 26 27
#include <cfloat>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <string>
28
#include <limits>
adelmann's avatar
adelmann committed
29
#include <cmath>
gsell's avatar
gsell committed
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
#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"
56 57
//--------- Added by Xiaoying Pang 04/22/2014 ---------------
#include "Solvers/CSRWakeFunction.hh"
gsell's avatar
gsell committed
58 59 60 61

#include "AbstractObjects/OpalData.h"

#include "BasicActions/Option.h"
kraus's avatar
kraus committed
62 63
#include "Utilities/OpalOptions.h"
#include "Utilities/Options.h"
gsell's avatar
gsell committed
64 65

#include "Distribution/Distribution.h"
66
#include "ValueDefinitions/RealVariable.h"
gsell's avatar
gsell committed
67 68
#include "Utilities/Timer.h"
#include "Utilities/OpalException.h"
69
#include "Solvers/SurfacePhysicsHandler.hh"
gsell's avatar
gsell committed
70 71 72 73 74 75 76 77 78
#include "Structure/BoundaryGeometry.h"

class PartData;

using namespace std;

ParallelTTracker::ParallelTTracker(const Beamline &beamline,
                                   const PartData &reference,
                                   bool revBeam,
adelmann's avatar
adelmann committed
79 80
                                   bool revTrack,
				   size_t N):
81 82 83 84 85 86 87 88 89 90 91 92
Tracker(beamline, reference, revBeam, revTrack),
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),
93 94
//--------- Added by Xiaoying Pang 04/22/2014 ---------------
wakeFunction_m(NULL),
95 96 97 98
surfaceStatus_m(false),
secondaryFlg_m(false),
mpacflg_m(true),
nEmissionMode_m(false),
99
zStop_m(),
100 101 102 103
scaleFactor_m(1.0),
vscaleFactor_m(scaleFactor_m),
recpGamma_m(1.0),
rescale_coeff_m(1.0),
104 105
dtCurrentTrack_m(0.0),
dtAllTracks_m(),
106
surfaceEmissionStop_m(-1),
107
specifiedNPart_m(N),
108 109 110 111 112 113 114
minStepforReBin_m(-1),
minBinEmitted_m(std::numeric_limits<size_t>::max()),
repartFreq_m(-1),
lastVisited_m(-1),
numRefs_m(-1),
gunSubTimeSteps_m(-1),
emissionSteps_m(std::numeric_limits<unsigned int>::max()),
115
localTrackSteps_m(),
116 117 118 119
maxNparts_m(0),
numberOfFieldEmittedParticles_m(std::numeric_limits<size_t>::max()),
bends_m(0),
numParticlesInSimulation_m(0),
kraus's avatar
kraus committed
120
space_orientation_m(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0),
121 122 123 124 125 126
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")),
Nimpact_m(0),
127
SeyNum_m(0.0),
128 129 130 131 132
timeIntegrationTimer1Loop1_m(IpplTimings::getTimer("TIntegration1Loop1")),
timeIntegrationTimer1Loop2_m(IpplTimings::getTimer("TIntegration1Loop2")),
timeIntegrationTimer2Loop1_m(IpplTimings::getTimer("TIntegration2Loop1")),
timeIntegrationTimer2Loop2_m(IpplTimings::getTimer("TIntegration2Loop2"))
{
gsell's avatar
gsell committed
133 134 135 136 137 138 139 140
}

ParallelTTracker::ParallelTTracker(const Beamline &beamline,
                                   PartBunch &bunch,
                                   DataSink &ds,
                                   const PartData &reference,
                                   bool revBeam,
                                   bool revTrack,
141
                                   const std::vector<unsigned long long> &maxSteps,
142
                                   const std::vector<double> &zstop,
adelmann's avatar
adelmann committed
143
                                   int timeIntegrator,
144
                                   const std::vector<double> &dt,
adelmann's avatar
adelmann committed
145
				   size_t N):
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
Tracker(beamline, reference, revBeam, revTrack),
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),
scaleFactor_m(itsBunch->getdT() * Physics::c),
vscaleFactor_m(scaleFactor_m),
recpGamma_m(1.0),
rescale_coeff_m(1.0),
166
dtCurrentTrack_m(0.0),
167
surfaceEmissionStop_m(-1),
168
specifiedNPart_m(N),
169 170 171 172 173 174 175 176 177 178 179
minStepforReBin_m(-1),
minBinEmitted_m(std::numeric_limits<size_t>::max()),
repartFreq_m(-1),
lastVisited_m(-1),
numRefs_m(-1),
gunSubTimeSteps_m(-1),
emissionSteps_m(numeric_limits<unsigned int>::max()),
maxNparts_m(0),
numberOfFieldEmittedParticles_m(numeric_limits<size_t>::max()),
bends_m(0),
numParticlesInSimulation_m(0),
kraus's avatar
kraus committed
180
space_orientation_m(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0),
181 182 183 184 185 186 187
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")),
timeIntegrator_m(timeIntegrator),
Nimpact_m(0),
188 189 190 191 192 193
SeyNum_m(0.0),
timeIntegrationTimer1Loop1_m(IpplTimings::getTimer("TIntegration1Loop1")),
timeIntegrationTimer1Loop2_m(IpplTimings::getTimer("TIntegration1Loop2")),
timeIntegrationTimer2Loop1_m(IpplTimings::getTimer("TIntegration2Loop1")),
timeIntegrationTimer2Loop2_m(IpplTimings::getTimer("TIntegration2Loop2"))
{
194

195 196 197 198 199 200 201 202 203 204
    for (std::vector<unsigned long long>::const_iterator it = maxSteps.begin(); it != maxSteps.end(); ++ it) {
        localTrackSteps_m.push(*it);
    }
    for (std::vector<double>::const_iterator it = dt.begin(); it != dt.end(); ++ it) {
        dtAllTracks_m.push(*it);
    }
    for (std::vector<double>::const_iterator it = zstop.begin(); it != zstop.end(); ++ it) {
        zStop_m.push(*it);
    }

205
    //    itsBeamline = dynamic_cast<Beamline*>(beamline.clone());
206

207 208 209 210 211 212
#ifdef OPAL_DKS
    dksbase.setAPI("Cuda", 4);
    dksbase.setDevice("-gpu", 4);
    dksbase.initDevice();
#endif

gsell's avatar
gsell committed
213 214
}

215 216 217 218 219 220 221
#ifdef HAVE_AMR_SOLVER
ParallelTTracker::ParallelTTracker(const Beamline &beamline,
                                   PartBunch &bunch,
                                   DataSink &ds,
                                   const PartData &reference,
                                   bool revBeam,
                                   bool revTrack,
222
                                   const std::vector<unsigned long long> &maxSteps,
223
                                   const std::vector<double> &zstop,
224
                                   int timeIntegrator,
225
                                   const std::vector<double> &dt,
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
				   size_t N,
				   Amr* amrptr_in):
Tracker(beamline, reference, revBeam, revTrack),
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),
scaleFactor_m(itsBunch->getdT() * Physics::c),
vscaleFactor_m(scaleFactor_m),
recpGamma_m(1.0),
rescale_coeff_m(1.0),
248
dtCurrentTrack_m(0.0),
249
surfaceEmissionStop_m(-1),
250
specifiedNPart_m(N),
251 252 253 254 255 256 257 258 259 260 261
minStepforReBin_m(-1),
minBinEmitted_m(std::numeric_limits<size_t>::max()),
repartFreq_m(-1),
lastVisited_m(-1),
numRefs_m(-1),
gunSubTimeSteps_m(-1),
emissionSteps_m(numeric_limits<unsigned int>::max()),
maxNparts_m(0),
numberOfFieldEmittedParticles_m(numeric_limits<size_t>::max()),
bends_m(0),
numParticlesInSimulation_m(0),
kraus's avatar
kraus committed
262
space_orientation_m(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0),
263 264 265 266 267 268 269 270
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")),
timeIntegrator_m(timeIntegrator),
Nimpact_m(0),
SeyNum_m(0.0),
271 272 273 274 275 276
amrptr(amrptr_in),
timeIntegrationTimer1Loop1_m(IpplTimings::getTimer("TIntegration1Loop1")),
timeIntegrationTimer1Loop2_m(IpplTimings::getTimer("TIntegration1Loop2")),
timeIntegrationTimer2Loop1_m(IpplTimings::getTimer("TIntegration2Loop1")),
timeIntegrationTimer2Loop2_m(IpplTimings::getTimer("TIntegration2Loop2"))
{
277 278 279 280 281 282 283 284 285 286

    for (std::vector<unsigned long long>::const_iterator it = maxSteps.begin(); it != maxSteps.end(); ++ it) {
        localTrackSteps_m.push(*it);
    }
    for (std::vector<double>::const_iterator it = dt.begin(); it != dt.end(); ++ it) {
        dtAllTracks_m.push(*it);
    }
    for (std::vector<double>::const_iterator it = zstop.begin(); it != zstop.end(); ++ it) {
        zStop_m.push(*it);
    }
287 288 289 290 291 292 293

#ifdef OPAL_DKS
    dksbase.setAPI("Cuda", 4);
    dksbase.setDevice("-gpu", 4);
    dksbase.initDevice();
#endif

294 295
}
#endif
gsell's avatar
gsell committed
296 297

ParallelTTracker::~ParallelTTracker() {
298

gsell's avatar
gsell committed
299 300
}

301 302 303
void ParallelTTracker::applyEntranceFringe(double angle, double curve,
                                           const BMultipoleField &field, double scale) {
}
304 305


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

310
void ParallelTTracker::updateRFElement(std::string elName, double maxPhase) {
311 312 313 314 315
    /**
     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.
     */
316 317 318 319 320
    double phase = 0.0;
    double frequency = 0.0;
    double globalTimeShift = OpalData::getInstance()->getGlobalPhaseShift();
    for (FieldList::iterator fit = cavities_m.begin(); fit != cavities_m.end(); ++fit) {
        if ((*fit).getElement()->getName() == elName) {
321
            if ((*fit).getElement()->getType() == ElementBase::TRAVELINGWAVE) {
322 323 324 325 326
                phase  =  static_cast<TravelingWave *>((*fit).getElement().get())->getPhasem();
                frequency = static_cast<TravelingWave *>((*fit).getElement().get())->getFrequencym();
                maxPhase -= frequency * globalTimeShift;

                static_cast<TravelingWave *>((*fit).getElement().get())->updatePhasem(phase + maxPhase);
327
            } else {
328 329 330 331 332
                phase  = static_cast<RFCavity *>((*fit).getElement().get())->getPhasem();
                frequency = static_cast<RFCavity *>((*fit).getElement().get())->getFrequencym();
                maxPhase -= frequency * globalTimeShift;

                static_cast<RFCavity *>((*fit).getElement().get())->updatePhasem(phase + maxPhase);
333
            }
334 335

            break;
336
        }
gsell's avatar
gsell committed
337 338 339
    }
}

340
void ParallelTTracker::handleAutoPhasing() {
341
    typedef std::vector<MaxPhasesT>::iterator iterator_t;
342

343
    if(Options::autoPhase == 0) return;
344

345
    if(!OpalData::getInstance()->inRestartRun()) {
346 347
        itsDataSink_m->storeCavityInformation();
    }
348

349 350 351 352
    iterator_t it = OpalData::getInstance()->getFirstMaxPhases();
    iterator_t end = OpalData::getInstance()->getLastMaxPhases();
    for(; it < end; ++ it) {
        updateRFElement((*it).first, (*it).second);
gsell's avatar
gsell committed
353 354 355
    }
}

356 357 358 359 360 361 362 363
void ParallelTTracker::execute() {
#ifdef HAVE_AMR_SOLVER
    executeAMRTracker();
#else
    if(timeIntegrator_m == 3) {
        executeAMTSTracker();
    } else {
        executeDefaultTracker();
gsell's avatar
gsell committed
364
    }
365
#endif
gsell's avatar
gsell committed
366 367
}

368
void ParallelTTracker::executeDefaultTracker() {
kraus's avatar
kraus committed
369
    Inform msg("ParallelTTracker ", *gmsg);
370 371 372 373
    const Vector_t vscaleFactor_m = Vector_t(scaleFactor_m);
    BorisPusher pusher(itsReference);
    secondaryFlg_m = false;
    dtCurrentTrack_m = itsBunch->getdT();
gsell's avatar
gsell committed
374

375 376 377 378
    // 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;
379

380
    prepareSections();
381

382 383 384 385 386 387 388
    if (OpalData::getInstance()->hasBunchAllocated()) {
        // delete last entry of sdds file and load balance file
        // if we are in a follow-up track
        itsDataSink_m->rewindLinesSDDS(1);
        itsDataSink_m->rewindLinesLBal(1);
    }

389
    handleAutoPhasing();
390

391
    numParticlesInSimulation_m = itsBunch->getTotalNum();
392

393
    OPALTimer::Timer myt1;
394

395
    setTime();
396

397
    double t = itsBunch->getT();
398

399
    unsigned long long step = itsBunch->getLocalTrackStep();
400

kraus's avatar
kraus committed
401
    *gmsg << "Track start at: " << myt1.time() << ", t= " << t << "; zstop at: " << zStop_m.front() << " [m]" << endl;
402

403 404
    gunSubTimeSteps_m = 10;
    prepareEmission();
405

406
    doSchottyRenormalization();
407

kraus's avatar
kraus committed
408 409 410 411
    *gmsg << level1
          << "Executing ParallelTTracker, initial DT " << itsBunch->getdT() << " [s];\n"
          << "max integration steps " << localTrackSteps_m.front() << ", next step= " << step << "\n";
    *gmsg << "Using default (Boris-Buneman) integrator" << endl;
412

kraus's avatar
kraus committed
413
    itsOpalBeamline_m.print(*gmsg);
414

415
    setupSUV(!(OpalData::getInstance()->inRestartRun() || (OpalData::getInstance()->hasBunchAllocated() && !Options::scan)));
416

417 418 419
    // 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);
420

421
    initializeBoundaryGeometry();
422

423
    setOptionalVariables();
gsell's avatar
gsell committed
424

425 426 427
    // there is no point to do repartitioning with one node
    if(Ippl::getNodes() == 1)
        repartFreq_m = 1000000;
gsell's avatar
gsell committed
428

429 430
    wakeStatus_m = false;
    surfaceStatus_m = false;
431

432 433 434 435 436 437 438 439 440 441 442 443
#ifdef OPAL_DKS

    //get number of elements in the bunch
    numDeviceElements = itsBunch->getLocalNum();

    //allocate memory on device
    r_ptr = dksbase.allocateMemory<Vector_t>(numDeviceElements, ierr);
    p_ptr = dksbase.allocateMemory<Vector_t>(numDeviceElements, ierr);
    x_ptr = dksbase.allocateMemory<Vector_t>(numDeviceElements, ierr);

    lastSec_ptr = dksbase.allocateMemory<long>(numDeviceElements, ierr);
    dt_ptr = dksbase.allocateMemory<double>(numDeviceElements, ierr);
444

445 446 447 448 449 450 451 452 453 454 455 456
    orient_ptr = dksbase.allocateMemory<Vector_t>(itsOpalBeamline_m.sections_m.size(), ierr);

    //get all the section orientations
    int nsec = itsOpalBeamline_m.sections_m.size();
    Vector_t *orientation = new Vector_t[nsec];
    for (long i = 0; i < nsec; i++) {
        orientation[i] = itsOpalBeamline_m.getOrientation(i);
    }

    //write orientations to device
    dksbase.writeData<Vector_t>(orient_ptr, orientation, nsec);

457 458
    //free local orientation memory
    delete[] orientation;
459

460 461
    //allocate memory on device for particle
    allocateDeviceMemory();
kraus's avatar
kraus committed
462

463 464
    //page lock itsBunch->X, itsBunch->R, itsBunch-P
    registerHostMemory();
kraus's avatar
kraus committed
465

466
    //write R, P and X data to device
467 468 469
    dksbase.writeDataAsync<Vector_t>(r_ptr, &itsBunch->R[0], itsBunch->getLocalNum());
    dksbase.writeDataAsync<Vector_t>(p_ptr, &itsBunch->P[0], itsBunch->getLocalNum());
    dksbase.writeDataAsync<Vector_t>(x_ptr, &itsBunch->X[0], itsBunch->getLocalNum());
470 471 472 473 474 475

    //create two new streams
    dksbase.createStream(stream1);
    dksbase.createStream(stream2);
#endif

476 477 478 479
    while (localTrackSteps_m.size() > 0) {
        localTrackSteps_m.front() += step;
        dtCurrentTrack_m = dtAllTracks_m.front();
        changeDT();
480

481 482 483
        for(; step < localTrackSteps_m.front(); ++step) {
            bends_m = 0;
            numberOfFieldEmittedParticles_m = 0;
484

485
            itsOpalBeamline_m.resetStatus();
486

487 488
            // we dump later, after one step.
            // dumpStats(step, true, true);
489 490


491 492
            timeIntegration1(pusher);
            timeIntegration1_bgf(pusher);
493

494
            itsBunch->calcBeamParameters();
495

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

500 501 502
            if(step % repartFreq_m == 0 && step != 0) {
                doBinaryRepartition();
            }
503

504
            computeSpaceChargeFields();
505

kraus's avatar
kraus committed
506 507
            switchElements(10.0);

508 509 510
            selectDT();
            emitParticles(step);
            selectDT();
511

512
            computeExternalFields();
513

514 515
            timeIntegration2(pusher);
            timeIntegration2_bgf(pusher);
516

517
            bgf_main_collision_test();
518

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

523 524
            bool const psDump = itsBunch->getGlobalTrackStep() % Options::psDumpFreq == 0;
            bool const statDump = itsBunch->getGlobalTrackStep() % Options::statDumpFreq == 0;
525
            dumpStats(step, psDump, statDump);
526

527
            if(hasEndOfLineReached()) break;
528

529
            itsBunch->incTrackSteps();
530

531
        }
532

533 534 535
        dtAllTracks_m.pop();
        localTrackSteps_m.pop();
        zStop_m.pop();
536 537
    }

538 539 540
    if(numParticlesInSimulation_m > minBinEmitted_m) {
        itsBunch->boundp();
        numParticlesInSimulation_m = itsBunch->getTotalNum();
541
    }
542 543 544 545

    bool const psDump = (itsBunch->getGlobalTrackStep() - 1) % Options::psDumpFreq != 0;
    bool const statDump = (itsBunch->getGlobalTrackStep() - 1) % Options::statDumpFreq != 0;
    writePhaseSpace((step + 1), itsBunch->get_sPos(), psDump, statDump);
kraus's avatar
kraus committed
546
    msg << level2 << "Dump phase space of last step" << endl;
547 548
    OPALTimer::Timer myt3;
    itsOpalBeamline_m.switchElementsOff();
kraus's avatar
kraus committed
549
    *gmsg << "done executing ParallelTTracker at " << myt3.time() << endl;
550 551 552

#ifdef OPAL_DKS
    //free device memory
553
    freeDeviceMemory();
554 555 556
    dksbase.freeMemory<Vector_t>(orient_ptr, itsOpalBeamline_m.sections_m.size());

    //unregister page lock itsBunch->X, itsBunch->R, itsBunch-P
557
    unregisterHostMemory();
kraus's avatar
kraus committed
558

559
#endif
560 561
}

562
void ParallelTTracker::executeAMTSTracker() {
kraus's avatar
kraus committed
563
    Inform msg("ParallelTTracker ", *gmsg);
564
    const Vector_t vscaleFactor_m = Vector_t(scaleFactor_m);
565
    dtCurrentTrack_m = itsBunch->getdT();
566 567 568 569 570 571 572

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

    prepareSections();

573
    handleAutoPhasing();
574 575 576 577

    numParticlesInSimulation_m = itsBunch->getTotalNum();
    setTime();
    unsigned long long step = itsBunch->getLocalTrackStep();
578 579 580
    msg << "Track start at: " << OPALTimer::Timer().time() << ", t = " << itsBunch->getT() << "; zstop at: " << zStop_m.front() << " [m]" << endl;
    msg << "Executing ParallelTTracker, next step = " << step << endl;
    msg << "Using AMTS (adaptive multiple-time-stepping) integrator" << endl;
581 582 583
    itsOpalBeamline_m.print(msg);
    setupSUV();

584
    itsOpalBeamline_m.switchAllElements();
585 586 587 588 589 590 591 592 593 594

    setOptionalVariables();

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

    wakeStatus_m = false;
    surfaceStatus_m = false;

595 596 597 598 599
    // Count inner steps
    int totalInnerSteps = 0;

    itsBunch->boundp();
    itsBunch->calcBeamParameters();
600 601
    itsBunch->Ef = Vector_t(0.0);
    itsBunch->Bf = Vector_t(0.0);
602 603 604 605 606
    computeSpaceChargeFields();
    if(itsBunch->WeHaveEnergyBins()) {
        itsBunch->Rebin();
        itsBunch->resetInterpolationCache(true);
    }
607

608 609 610 611 612 613 614 615 616 617 618 619 620 621
    // AMTS step size initialization
    double const dt_inner_target = itsBunch->getdT();
    msg << "AMTS initialization: dt_inner_target = " << dt_inner_target << endl;
    double dt_outer, deltaTau;
    if(itsBunch->deltaTau_m != -1.0) {
        // DTAU is set in the inputfile, calc initial outer time step from that
        deltaTau = itsBunch->deltaTau_m;
        dt_outer = calcG() * deltaTau;
    } else {
        // Otherwise use DTSCINIT
        dt_outer = itsBunch->dtScInit_m;
        deltaTau = dt_outer / calcG();
    }
    msg << "AMTS initialization: dt_outer = " << dt_outer << " deltaTau = " << deltaTau << endl;
622

623 624 625 626 627 628 629 630 631 632 633
    // AMTS calculation of stopping times
    double const tEnd = itsBunch->getT() + double(localTrackSteps_m.front() - step) * dt_inner_target;
    double const psDumpInterval = double(Options::psDumpFreq) * dt_inner_target;
    double const statDumpInterval = double(Options::statDumpFreq) * dt_inner_target;
    double const repartInterval = double(repartFreq_m) * dt_inner_target;
    double const tTrackStart = itsBunch->getT() - double(step) * dt_inner_target; // we could be in a restarted simulation!
    double tNextPsDump = tTrackStart + psDumpInterval;
    while(tNextPsDump < itsBunch->getT()) tNextPsDump += psDumpInterval;
    double tNextStatDump = tTrackStart + statDumpInterval;
    while(tNextStatDump < itsBunch->getT()) tNextStatDump += statDumpInterval;
    double tDoNotRepartBefore = itsBunch->getT() + repartInterval;
634

635
    IpplTimings::startTimer(IpplTimings::getTimer("AMTS"));
636

637 638 639
    bool finished = false;
    for(; !finished; ++step) {
        itsOpalBeamline_m.resetStatus();
640

641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 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
        // AMTS choose new timestep
        IpplTimings::startTimer(IpplTimings::getTimer("AMTS-TimestepSelection"));
        dt_outer = calcG() * deltaTau;
        double tAfterStep = itsBunch->getT() + dt_outer;
        double const tNextStop = std::min(std::min(tEnd, tNextPsDump), tNextStatDump);
        bool psDump = false, statDump = false;
        if(tAfterStep > tNextStop) {
            dt_outer = tNextStop - itsBunch->getT();
            tAfterStep = tNextStop;
        }
        double const eps = 1e-14; // To test approx. equality of times
        if(std::fabs(tAfterStep - tEnd) < eps) {
            finished = true;
        }
        if(std::fabs(tAfterStep - tNextPsDump) < eps) {
            psDump = true;
            tNextPsDump += psDumpInterval;
        }
        if(std::fabs(tAfterStep - tNextStatDump) < eps) {
            statDump = true;
            tNextStatDump += statDumpInterval;
        }
        msg << "AMTS: dt_outer = " << dt_outer;
        double numSubsteps = std::max(round(dt_outer / dt_inner_target), 1.0);
        msg << " numSubsteps = " << numSubsteps;
        double dt_inner = dt_outer / numSubsteps;
        msg << " dt_inner = " << dt_inner << endl;
        IpplTimings::stopTimer(IpplTimings::getTimer("AMTS-TimestepSelection"));

        IpplTimings::startTimer(IpplTimings::getTimer("AMTS-Kick"));
        if(itsBunch->hasFieldSolver()) {
            kick(0.5 * dt_outer);
        }
        IpplTimings::stopTimer(IpplTimings::getTimer("AMTS-Kick"));

        for(int n = 0; n < numSubsteps; ++n) {
            bool const isFirstSubstep = (n == 0);
            bool const isLastSubstep = (n == numSubsteps - 1);
            borisExternalFields(dt_inner, isFirstSubstep, isLastSubstep);
            ++totalInnerSteps;
        }

        IpplTimings::startTimer(IpplTimings::getTimer("AMTS-SpaceCharge"));
        if(itsBunch->hasFieldSolver()) {
            itsBunch->boundp();
            itsBunch->Ef = Vector_t(0.0);
            itsBunch->Bf = Vector_t(0.0);
            if(itsBunch->getT() >= tDoNotRepartBefore) {
            	doBinaryRepartition();
            	tDoNotRepartBefore = itsBunch->getT() + repartInterval;
            }
            computeSpaceChargeFields();
            if(itsBunch->WeHaveEnergyBins()) {
                itsBunch->rebin();
                itsBunch->resetInterpolationCache(true);
            }
        }
        IpplTimings::stopTimer(IpplTimings::getTimer("AMTS-SpaceCharge"));

        IpplTimings::startTimer(IpplTimings::getTimer("AMTS-Kick"));
        if(itsBunch->hasFieldSolver()) {
            kick(0.5 * dt_outer);
        }
        IpplTimings::stopTimer(IpplTimings::getTimer("AMTS-Kick"));

        IpplTimings::startTimer(IpplTimings::getTimer("AMTS-Dump"));
        itsBunch->RefPart_R = RefPartR_zxy_m;
        itsBunch->RefPart_P = RefPartP_zxy_m;
        itsBunch->calcBeamParameters();
        dumpStats(step, psDump, statDump);
        IpplTimings::stopTimer(IpplTimings::getTimer("AMTS-Dump"));

        if(hasEndOfLineReached()) break;
        itsBunch->incTrackSteps();
    }

    IpplTimings::stopTimer(IpplTimings::getTimer("AMTS"));

    msg << "totalInnerSteps = " << totalInnerSteps << endl;

    itsBunch->boundp();
    numParticlesInSimulation_m = itsBunch->getTotalNum();
    writePhaseSpace((step + 1), itsBunch->get_sPos(), true, true);
    msg << "Dump phase space of last step" << endl;
    itsOpalBeamline_m.switchElementsOff();
    msg << "done executing ParallelTTracker at " << OPALTimer::Timer().time() << endl;
}

#ifdef HAVE_AMR_SOLVER
void ParallelTTracker::executeAMRTracker()
{
    Inform msg("ParallelTTracker ");
    const Vector_t vscaleFactor_m = Vector_t(scaleFactor_m);
    BorisPusher pusher(itsReference);
    secondaryFlg_m = false;
    dtCurrentTrack_m = itsBunch->getdT();

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

    prepareSections();

745
    handleAutoPhasing();
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824

    numParticlesInSimulation_m = itsBunch->getTotalNum();

    OPALTimer::Timer myt1;

    setTime();

    double t = itsBunch->getT();

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

    msg << "Track start at: " << myt1.time() << ", t= " << t << "; zstop at: " << zStop_m.front() << " [m]" << endl;

    gunSubTimeSteps_m = 10;
    prepareEmission();

    doSchottyRenormalization();

    msg << "Executing ParallelTTracker, initial DT " << itsBunch->getdT() << " [s];\n"
    << "max integration steps " << localTrackSteps_m.front() << ", next step= " << step << endl;
    msg << "Using default (Boris-Buneman) integrator" << endl;

    // itsBeamline_m.accept(*this);
    // itsOpalBeamline_m.prepareSections();
    itsOpalBeamline_m.print(msg);

    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;

    // 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(; step < localTrackSteps_m.front(); ++step)
    {
        bends_m = 0;
        numberOfFieldEmittedParticles_m = 0;

        itsOpalBeamline_m.resetStatus();

        // we dump later, after one step.
        // dumpStats(step, true, true);

        Real stop_time = -1.;

        std::cout << "                " << std::endl;
        std::cout << " ************** " << std::endl;
        std::cout << " DOING STEP ... " << step << std::endl;
        std::cout << " ************** " << std::endl;
        std::cout << "                " << std::endl;

        Real dt_from_amr = amrptr->coarseTimeStepDt(stop_time);

        std::cout << "                " << std::endl;
        std::cout << " ************** " << std::endl;
        std::cout << " COMPLETED STEP ... " << step << " WITH DT = " << dt_from_amr << std::endl;
        std::cout << " ************** " << std::endl;
        std::cout << "                " << std::endl;

        t += dt_from_amr;
        itsBunch->setT(t);

        bool const psDump = step % Options::psDumpFreq == 0;
        bool const statDump = step % Options::statDumpFreq == 0;
        dumpStats(step, psDump, statDump);
825 826 827

        if(hasEndOfLineReached()) break;

kraus's avatar
kraus committed
828
        switchElements(10.0);
829 830 831 832 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 864 865 866 867 868 869 870 871 872 873 874 875

        itsBunch->incTrackSteps();

        // These routines return the particle data for all of the particles and on all of the processes

        Array<int> particle_ids;
        amrptr->GetParticleIDs(particle_ids);

        Array<int> particle_cpu;
        amrptr->GetParticleCPU(particle_cpu);

        Array<Real> locs;
        amrptr->GetParticleLocations(locs);

        // Here we assume that we have stored, Q, V, ... in the particle data in TrackRun.cpp
        int start_comp = 1;
        int   num_comp = 3;
	Array<Real> Qs;
        Array<Real> vels;
        Array<Real> Evec;

        amrptr->GetParticleData(Qs,0,1);
        amrptr->GetParticleData(vels,start_comp,num_comp);
    	//amrptr->GetParticleData(vels,start_comp,6);
        amrptr->GetParticleData(Evec,4,num_comp);

        std::cout << "SIZE OF PARTICLE IDs "  << particle_ids.size() << std::endl;
        std::cout << "SIZE OF PARTICLE CPU "  << particle_cpu.size() << std::endl;
        std::cout << "SIZE OF PARTICLE LOCS " << locs.size() << std::endl;
        std::cout << "SIZE OF PARTICLE VELS " << vels.size() << std::endl;
        std::cout << "SIZE OF PARTICLE EFIELD " << Evec.size() << std::endl;


        int num_particles_total = particle_ids.size();

	double gamma=itsReference.getGamma();
	std:: cout << " GAMMA" << gamma << std::endl;

        Vector_t rmin;
        Vector_t rmax;
        itsBunch->get_bounds(rmin, rmax);

        FVector<double,6> six_vect;

	for (int i = 0; i < num_particles_total; i++)
        {
             if (i < 3 ) std::cout << "PARTICLE ID " << particle_ids[i] << "\n"
kraus's avatar
kraus committed
876
				    << Qs[i] << "\n"
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
                                    << "  " << locs[3*i  ] << " " << vels[3*i  ] << "\n"
		 		    << "  " << locs[3*i+1] << " " << vels[3*i+1] << "\n"
		 		    << "  " << locs[3*i+2] << " " << vels[3*i+2] << "\n"
#if 0
		 		    << "  " << locs[3*i]   << " " << vels[3*i+3] << "\n"
		 		    << "  " << locs[3*i+1] << " " << vels[3*i+4] << "\n"
		 		    << "  " << locs[3*i+2] << " " << vels[3*i+5] << "\n"
#endif
                                    << "  " << locs[3*i  ] << " " << Evec[3*i  ] << "\n"
		 		    << "  " << locs[3*i+1] << " " << Evec[3*i+1] << "\n"
		 		    << "  " << locs[3*i+2] << " " << Evec[3*i+2] << "\n"
		 		    << std::endl;
             if (particle_cpu[i] == Ippl::myNode())
             {
                 six_vect[0] = locs[3*i  ];
                 six_vect[1] = vels[3*i  ] * gamma / Physics::c;
                 six_vect[2] = locs[3*i+1];
                 six_vect[3] = vels[3*i+1] * gamma / Physics::c;
                 six_vect[4] = locs[3*i+2];
                 six_vect[5] = vels[3*i+2] * gamma / Physics::c;

kraus's avatar
kraus committed
898
                 // We subtract one from the particle_id because we added one to it when we
899
                 //    passed the particle into the AMR stuff.
kraus's avatar
kraus committed
900 901
                 // std::cout << "ON NODE ID " << Ippl::myNode() << " ADDING PARTICLE "
                 //          << particle_ids[i] << " WITH X,Y,Z "
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
                 //          << locs[3*i] << " " << locs[3*i+1] << " " << locs[3*i+2] << std::endl;
                 itsBunch->set_part(six_vect, particle_ids[i]-1);
		 for (int k=0; k<3; k++)
			itsBunch->Ef[particle_ids[i]-1](k) = Evec[3*i+k];
             }
	}
    }

    Vector_t rmin;
    Vector_t rmax;
    itsBunch->get_bounds(rmin, rmax);

    if(numParticlesInSimulation_m > minBinEmitted_m) {
        itsBunch->boundp();
        numParticlesInSimulation_m = itsBunch->getTotalNum();
    }

    writePhaseSpace((step + 1), itsBunch->get_sPos(), true, true);
    msg << "Dump phase space of last step" << endl;
    OPALTimer::Timer myt3;
    itsOpalBeamline_m.switchElementsOff();
    msg << "done executing ParallelTTracker at " << myt3.time() << endl;
}
#endif

927
void ParallelTTracker::doSchottyRenormalization() {
kraus's avatar
kraus committed
928
    Inform msg("ParallelTTracker ", *gmsg);
929 930 931
    double init_erg = itsBunch->getEkin();
    double tol_iter = 1e-5;
    rescale_coeff_m = 1 / init_erg / init_erg;
932

933 934 935 936 937 938
    if(Options::schottkyRennormalization > 0) {
        rescale_coeff_m = Options:: schottkyRennormalization;
        msg << "Set schottky scale coefficient to  " << rescale_coeff_m << endl;
    } else if(Options::schottkyCorrection) {
        while(true) {
            double real_charge = schottkyLoop(rescale_coeff_m);
939

940 941 942 943 944 945 946 947 948 949 950
            double total_charge = itsBunch->getTotalNum() * itsBunch->getChargePerParticle();
            msg << "Schottky scale coefficient " << rescale_coeff_m << ", actual emitted charge " << real_charge << " (Cb)" << endl;
            itsBunch->cleanUpParticles();
            itsBunch->setT(0);
            double scale_error = total_charge / real_charge - 1;
            // TODO : send scale_error to all nodes
            rescale_coeff_m *= (1.3 * scale_error + 1);
            if(fabs(scale_error) < tol_iter)
                break;
        }
        msg << "Schottky scan, final scale coefficient " << rescale_coeff_m << " ()" << endl;
951 952
    }
}
953

954
double ParallelTTracker::schottkyLoop(double rescale_coeff) {
955

kraus's avatar
kraus committed
956
    Inform msg("ParallelTTracker ", *gmsg);
957

958 959 960 961
    double recpgamma;
    double t = 0.0;
    double dt = itsBunch->getdT();
    Vector_t vscaleFactor = Vector_t(scaleFactor_m);
962

963 964
    unsigned long long step = 0;
    unsigned int emissionSteps = 0;
965

966 967 968 969
    Vector_t um, a, s;
    Vector_t externalE, externalB;
    BorisPusher pusher(itsReference);
    Vector_t rmin, rmax;
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 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
    bool global_EOL;

    bool hasSwitchedToTEmission = false;
    bool hasSwitchedBackToTTrack = false;

    size_t totalParticles_i = itsBunch->getTotalNum();

    msg << "*****************************************************************" << endl;
    msg << " Estimate Schottky correction                                    " << endl;
    msg << "*****************************************************************" << endl;

    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->WeHaveEnergyBins())) {
            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 + pSqr(RefPartP_suv_m, RefPartP_suv_m));
        margin = 0.01 > margin ? 0.01 : margin;
kraus's avatar
kraus committed
1028
        itsOpalBeamline_m.switchElements(rmin(2) - margin, rmax(2) + margin, getEnergyMeV(RefPartP_suv_m));
1029 1030 1031 1032 1033 1034 1035 1036
    }

    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.
1037

kraus's avatar
kraus committed
1038
        msg << level3 << "MINBINEMITTED " << minBinEmitted << endl;
1039 1040 1041 1042 1043 1044 1045 1046
    }


    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
kraus's avatar
kraus committed
1047
        msg << level3 << "MINSTEPFORREBIN " << minStepforReBin << endl;
1048 1049 1050 1051 1052 1053
    }

    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
kraus's avatar
kraus committed
1054
        msg << level3 << "REPARTFREQ " << repartFreq << endl;
1055
    }
1056

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

1061
    size_t totalParticles_f = 0;
1062

1063
    for(; step < localTrackSteps_m.front(); ++step) {
1064
        global_EOL = true;  // check if any particle hasn't reached the end of the field from the last element
1065

1066
        itsOpalBeamline_m.resetStatus();
1067

1068 1069 1070
        IpplTimings::startTimer(timeIntegrationTimer1_m);

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

1072 1073
        itsBunch->Ef = Vector_t(0.0);
        itsBunch->Bf = Vector_t(0.0);
1074

1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
        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);
1094

1095
        itsBunch->calcBeamParameters();
1096 1097


1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
        /** \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->WeHaveEnergyBins()) {
                // When we have energy bins.
                itsBunch->calcGammas();
                ParticleAttrib<double> Q_back = itsBunch->Q;
                itsBunch->resetInterpolationCache();
                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);
                 */
            }
1135
        }
1136

1137
        IpplTimings::startTimer(timeIntegrationTimer2_m);
1138 1139


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