TrackRun.cpp 34.2 KB
Newer Older
gsell's avatar
gsell committed
1
// -----------------------------------------------------------------------
2
// /*$RCSfile*/: TrackRun.cpp,v $
gsell's avatar
gsell committed
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
// ------------------------------------------------------------------------
// $Revision: 1.1.1.1.4.1 $
// ------------------------------------------------------------------------
// Copyright: see Copyright.readme
// ------------------------------------------------------------------------
//
// Class: TrackRun
//   The class for the OPAL RUN command.
//
// ------------------------------------------------------------------------
//
// $Date: 2004/11/12 20:10:11 $
// $Author: adelmann $
//
// ------------------------------------------------------------------------

#include "Track/TrackRun.h"
#include "AbstractObjects/BeamSequence.h"
#include "AbstractObjects/OpalData.h"
#include "AbstractObjects/ObjectFunction.h"
23
#include "Algorithms/Tracker.h"
gsell's avatar
gsell committed
24 25 26
#include "Algorithms/ThinTracker.h"
#include "Algorithms/ThickTracker.h"

27 28
#include "Algorithms/bet/EnvelopeBunch.h"

gsell's avatar
gsell committed
29 30 31
#include "Algorithms/ParallelTTracker.h"
#include "Algorithms/ParallelSliceTracker.h"
#include "Algorithms/ParallelCyclotronTracker.h"
32
#include "Algorithms/NilTracker.h"
gsell's avatar
gsell committed
33 34 35 36 37 38

#include "Attributes/Attributes.h"
#include "Beamlines/TBeamline.h"

#include "BasicActions/Option.h"

snuverink_j's avatar
snuverink_j committed
39
#include "Distribution/Distribution.h"
gsell's avatar
gsell committed
40 41
#include "Track/Track.h"
#include "Utilities/OpalException.h"
42
#include "Utilities/Util.h"
gsell's avatar
gsell committed
43
#include "Structure/Beam.h"
snuverink_j's avatar
snuverink_j committed
44
#include "Structure/BoundaryGeometry.h"
gsell's avatar
gsell committed
45 46
#include "Structure/FieldSolver.h"
#include "Structure/DataSink.h"
47 48 49 50
#include "Structure/H5PartWrapper.h"
#include "Structure/H5PartWrapperForPT.h"
#include "Structure/H5PartWrapperForPC.h"
#include "Structure/H5PartWrapperForPS.h"
gsell's avatar
gsell committed
51

52 53 54 55
#include "OPALconfig.h"
#include "changes.h"

#include <boost/algorithm/string.hpp>
56 57
#include <boost/regex.hpp>
#include <boost/filesystem.hpp>
58

59
#include <cmath>
gsell's avatar
gsell committed
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
#include <fstream>
#include <iomanip>

extern Inform *gmsg;

using namespace Physics;

// ------------------------------------------------------------------------

namespace {

    // The attributes of class TrackRun.
    enum {
        METHOD,       // Tracking method to use.
        TURNS,        // The number of turns to be tracked.
        MBMODE,       // The working way for multi-bunch mode for OPAL-cycl: "FORCE" or "AUTO"
frey_m's avatar
frey_m committed
76 77
        PARAMB,       // The control parameter for "AUTO" mode of multi-bunch,
        MB_ETA,       // The scale parameter for binning in multi-bunch mode
frey_m's avatar
frey_m committed
78
        MB_BINNING,   // The binning type in multi-bunch mode
gsell's avatar
gsell committed
79 80
        BEAM,         // The beam to track
        FIELDSOLVER,  // The field solver attached
81
        BOUNDARYGEOMETRY, // The boundary geometry
gsell's avatar
gsell committed
82
        DISTRIBUTION, // The particle distribution
83
        TRACKBACK,
gsell's avatar
gsell committed
84 85 86 87
        SIZE
    };
}

88 89
const std::string TrackRun::defaultDistribution("DISTRIBUTION");

gsell's avatar
gsell committed
90 91 92
TrackRun::TrackRun():
    Action(SIZE, "RUN",
           "The \"RUN\" sub-command tracks the defined particles through "
93 94 95 96
           "the given lattice."),
    itsTracker(NULL),
    dist(NULL),
    fs(NULL),
97 98
    ds(NULL),
    phaseSpaceSink_m(NULL) {
gsell's avatar
gsell committed
99 100
    itsAttr[METHOD] = Attributes::makeString
                      ("METHOD", "Name of tracking algorithm to use:\n"
101
                       "\t\t\t\"THIN\" (default) or \"THICK, OPAL-T,OPAL-T3D, OPAL-CYCL\".", "THIN");
gsell's avatar
gsell committed
102 103 104 105 106 107 108
    itsAttr[TURNS] = Attributes::makeReal
                     ("TURNS", "Number of turns to be tracked; Number of neighboring bunches to be tracked in cyclotron", 1.0);

    itsAttr[MBMODE] = Attributes::makeString
                      ("MBMODE", "The working way for multi-bunch mode for OPAL-cycl: FORCE or AUTO ", "FORCE");

    itsAttr[PARAMB] = Attributes::makeReal
frey_m's avatar
frey_m committed
109
                      ("PARAMB", "Control parameter to define when to start multi-bunch mode, only available in \"AUTO\" mode ", 5.0);
110

frey_m's avatar
frey_m committed
111 112 113
    itsAttr[MB_ETA] = Attributes::makeReal("MB_ETA",
                                           "The scale parameter for binning in multi-bunch mode",
                                           0.01);
114

frey_m's avatar
frey_m committed
115
    itsAttr[MB_BINNING] = Attributes::makeString
frey_m's avatar
frey_m committed
116
                          ("MB_BINNING", "Type of energy binning in multi-bunch mode: GAMMA or BUNCH", "GAMMA");
gsell's avatar
gsell committed
117 118 119 120 121

    itsAttr[BEAM] = Attributes::makeString
                    ("BEAM", "Name of beam ", "BEAM");
    itsAttr[FIELDSOLVER] = Attributes::makeString
                           ("FIELDSOLVER", "Field solver to be used ", "FIELDSOLVER");
122 123
    itsAttr[BOUNDARYGEOMETRY] = Attributes::makeString
                           ("BOUNDARYGEOMETRY", "Boundary geometry to be used NONE (default)", "NONE");
124 125
    itsAttr[DISTRIBUTION] = Attributes::makeStringArray
                             ("DISTRIBUTION", "List of particle distributions to be used ");
126 127
    itsAttr[TRACKBACK] = Attributes::makeBool
        ("TRACKBACK", "Track in reverse direction, default: false", false);
128 129
    registerOwnership(AttributeHandler::SUB_COMMAND);

130
    opal = OpalData::getInstance();
gsell's avatar
gsell committed
131 132 133
}


134
TrackRun::TrackRun(const std::string &name, TrackRun *parent):
135 136 137 138
    Action(name, parent),
    itsTracker(NULL),
    dist(NULL),
    fs(NULL),
139 140
    ds(NULL),
    phaseSpaceSink_m(NULL) {
141
    opal = OpalData::getInstance();
gsell's avatar
gsell committed
142 143 144 145
}


TrackRun::~TrackRun()
146 147 148
{
    delete phaseSpaceSink_m;
}
gsell's avatar
gsell committed
149 150


151
TrackRun *TrackRun::clone(const std::string &name) {
gsell's avatar
gsell committed
152 153 154 155 156
    return new TrackRun(name, this);
}


void TrackRun::execute() {
157
    const int currentVersion = ((OPAL_VERSION_MAJOR * 100) + OPAL_VERSION_MINOR) * 100;
158 159 160 161 162 163 164 165 166 167
    if (Options::version < currentVersion) {
        unsigned int fileVersion = Options::version / 100;
        bool newerChanges = false;
        for (auto it = Versions::changes.begin(); it != Versions::changes.end(); ++ it) {
            if (it->first > fileVersion) {
                newerChanges = true;
                break;
            }
        }
        if (newerChanges) {
168 169
            Inform errorMsg("Error");
            errorMsg << "\n******************** V E R S I O N   M I S M A T C H ***********************\n" << endl;
170 171
            for (auto it = Versions::changes.begin(); it != Versions::changes.end(); ++ it) {
                if (it->first > fileVersion) {
172
                    errorMsg << it->second << endl;
173 174
                }
            }
175 176 177 178 179
            errorMsg << "\n"
                     << "* Make sure you do understand these changes and adjust your input file \n"
                     << "* accordingly. Then add\n"
                     << "* OPTION, VERSION = " << currentVersion << ";\n"
                     << "* to your input file. " << endl;
180
            errorMsg << "\n****************************************************************************\n" << endl;
181 182 183
            throw OpalException("TrackRun::execute", "Version mismatch");
        }
    }
gsell's avatar
gsell committed
184 185

    // Get algorithm to use.
186
    std::string method = Util::toUpper(Attributes::getString(itsAttr[METHOD]));
gsell's avatar
gsell committed
187
    if(method == "THIN") {
188
        *gmsg << "  Method == \"THIN\"" << endl;
gsell's avatar
gsell committed
189
        itsTracker = new ThinTracker(*Track::block->use->fetchLine(),
frey_m's avatar
frey_m committed
190
                                     Track::block->bunch, Track::block->reference,
gsell's avatar
gsell committed
191 192
                                     false, false);
    } else if(method == "THICK") {
193
        setupThickTracker();
194 195
    } else if(method == "PARALLEL-SLICE" || method == "OPAL-E") {
        setupSliceTracker();
196
    } else if(method == "PARALLEL-T" || method == "OPAL-T") {
197
        setupTTracker();
198
    } else if(method == "CYCLOTRON-T" || method == "OPAL-CYCL") {
199 200 201 202 203
        setupCyclotronTracker();
    } else {
        throw OpalException("TrackRun::execute()",
                            "Method name \"" + method + "\" unknown.");
    }
204

205
    if(method == "THIN" || method == "THICK") {
206
        int turns = int(std::round(Attributes::getReal(itsAttr[TURNS])));
207

208 209 210 211
        // Track for the all but last turn.
        for(int turn = 1; turn < turns; ++turn) {
            itsTracker->execute();
        }
212

213
        // Track the last turn.
214
        itsTracker->execute();
215

216
    } else {
kraus's avatar
kraus committed
217
        itsTracker->execute();
218

219
        opal->setRestartRun(false);
220
    }
gsell's avatar
gsell committed
221

222
    opal->bunchIsAllocated();
223
    if(method == "PARALLEL-SLICE")
224
        opal->slbunchIsAllocated();
gsell's avatar
gsell committed
225

226 227
    delete itsTracker;
}
gsell's avatar
gsell committed
228

229
void TrackRun::setupSliceTracker() {
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 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
    OpalData::getInstance()->setInOPALEnvMode();
    bool isFollowupTrack = opal->hasSLBunchAllocated();

    if(!opal->hasSLBunchAllocated()) {
        *gmsg << "* ********************************************************************************** " << endl;
        *gmsg << "* Selected Tracking Method == PARALLEL-SLICE, NEW TRACK" << endl;
        *gmsg << "* ********************************************************************************** " << endl;
    } else if(isFollowupTrack) {
        *gmsg << "* ********************************************************************************** " << endl;
        *gmsg << "* Selected Tracking Method == PARALLEL-SLICE, FOLLOWUP TRACK" << endl;
        *gmsg << "* ********************************************************************************** " << endl;
    }

    Beam   *beam = Beam::find(Attributes::getString(itsAttr[BEAM]));
    Track::block->bunch->setBeamFrequency(beam->getFrequency() * 1e6);

    if(opal->inRestartRun()) {
        phaseSpaceSink_m = new H5PartWrapperForPS(opal->getInputBasename() + std::string(".h5"),
                                                  opal->getRestartStep(),
                                                  OpalData::getInstance()->getRestartFileName(),
                                                  H5_O_WRONLY);
    } else if (isFollowupTrack) {
        phaseSpaceSink_m = new H5PartWrapperForPS(opal->getInputBasename() + std::string(".h5"),
                                                  -1,
                                                  opal->getInputBasename() + std::string(".h5"),
                                                  H5_O_WRONLY);
    } else {
        phaseSpaceSink_m = new H5PartWrapperForPS(opal->getInputBasename() + std::string(".h5"),
                                                  H5_O_WRONLY);
    }

    std::vector<std::string> distr_str = Attributes::getStringArray(itsAttr[DISTRIBUTION]);
    const size_t numberOfDistributions = distr_str.size();
    if (numberOfDistributions == 0) {
        dist = Distribution::find(defaultDistribution);
    } else {
        dist = Distribution::find(distr_str.at(0));
        // dist->setNumberOfDistributions(numberOfDistributions);

        // if(numberOfDistributions > 1) {
        //     *gmsg << "Found more than one distribution: ";
        //     for(size_t i = 1; i < numberOfDistributions; ++ i) {
        //         Distribution *d = Distribution::find(distr_str.at(i));

        //         d->setNumberOfDistributions(numberOfDistributions);
        //         distrs_m.push_back(d);

        //         *gmsg << " " << distr_str.at(i);
        //     }
        //     *gmsg << endl;
        // }
    }

    fs = FieldSolver::find(Attributes::getString(itsAttr[FIELDSOLVER]));
    fs->initCartesianFields();

    double charge = 0.0;

    if(!opal->hasSLBunchAllocated()) {
        if(!opal->inRestartRun()) {

            dist->createOpalE(beam, distrs_m, Track::block->slbunch, 0.0, 0.0);
            opal->setGlobalPhaseShift(0.5 * dist->getTEmission());

        } else {
            /***
                reload slice distribution
            */

            dist->doRestartOpalE(Track::block->slbunch, beam->getNumberOfParticles(), opal->getRestartStep(), phaseSpaceSink_m);
        }
    } else {
        charge = 1.0;
    }

    Track::block->slbunch->setdT(Track::block->dT.front());
    // set the total charge
    charge = beam->getCharge() * beam->getCurrent() / (beam->getFrequency() * 1e6);
    Track::block->slbunch->setCharge(charge);
    // set coupling constant
    double coefE = 1.0 / (4 * pi * epsilon_0);
    Track::block->slbunch->setCouplingConstant(coefE);
    //Track::block->slbunch->calcBeamParameters();


frey_m's avatar
frey_m committed
315
    initDataSink();
316 317 318 319

    if (Track::block->bunch->getTotalNum() > 0) {
        double spos = Track::block->zstart;
        auto &zstop = Track::block->zstop;
320
        auto it = Track::block->dT.begin();
321 322 323 324

        unsigned int i = 0;
        while (i + 1 < zstop.size() && zstop[i + 1] < spos) {
            ++ i;
325
            ++ it;
326 327
        }

328
        Track::block->bunch->setdT(*it);
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
    } else {
        Track::block->zstart = 0.0;
    }

    if(!opal->hasBunchAllocated())
        *gmsg << *dist << endl;
    *gmsg << *beam << endl;
    *gmsg << *Track::block->slbunch  << endl;
    *gmsg << "Phase space dump frequency is set to " << Options::psDumpFreq
          << " Inputfile is " << opal->getInputFn() << endl;


    // findPhasesForMaxEnergy();

    itsTracker = new ParallelSliceTracker(*Track::block->use->fetchLine(),
                                          dynamic_cast<EnvelopeBunch &>(*Track::block->slbunch),
                                          *ds,
                                          Track::block->reference,
                                          false,
                                          false,
                                          Track::block->localTimeSteps,
                                          Track::block->zstart,
                                          Track::block->zstop,
                                          Track::block->dT);
353
}
354

355 356


357
void TrackRun::setupThickTracker()
358
{
359 360 361 362 363 364 365
    bool isFollowupTrack = opal->hasBunchAllocated();

    if(isFollowupTrack) {
        *gmsg << "* ********************************************************************************** " << endl;
        *gmsg << "* Selected Tracking Method == THICK, FOLLOWUP TRACK" << endl;
        *gmsg << "* ********************************************************************************** " << endl;
        Track::block->bunch->setLocalTrackStep(0);
366
    } else {
367 368 369
        *gmsg << "* ********************************************************************************** " << endl;
        *gmsg << "* Selected Tracking Method == THICK, NEW TRACK" << endl;
        *gmsg << "* ********************************************************************************** " << endl;
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
    }

    Beam *beam = Beam::find(Attributes::getString(itsAttr[BEAM]));
    if (Attributes::getString(itsAttr[BOUNDARYGEOMETRY]) != "NONE") {
        // Ask the dictionary if BoundaryGeometry is allocated.
        // If it is allocated use the allocated BoundaryGeometry
        if (!OpalData::getInstance()->hasGlobalGeometry()) {
            BoundaryGeometry *bg = BoundaryGeometry::find(Attributes::getString(itsAttr[BOUNDARYGEOMETRY]))->
                clone(getOpalName() + std::string("_geometry"));
            OpalData::getInstance()->setGlobalGeometry(bg);
        }
    }

    setupFieldsolver();

    if(opal->inRestartRun()) {
        phaseSpaceSink_m = new H5PartWrapperForPT(opal->getInputBasename() + std::string(".h5"),
                                                  opal->getRestartStep(),
                                                  OpalData::getInstance()->getRestartFileName(),
                                                  H5_O_WRONLY);
    } else if (isFollowupTrack) {
        phaseSpaceSink_m = new H5PartWrapperForPT(opal->getInputBasename() + std::string(".h5"),
                                                  -1,
                                                  opal->getInputBasename() + std::string(".h5"),
                                                  H5_O_WRONLY);
    } else {
        phaseSpaceSink_m = new H5PartWrapperForPT(opal->getInputBasename() + std::string(".h5"),
                                                  H5_O_WRONLY);
    }

    double charge = setDistributionParallelT(beam);

    Track::block->bunch->setdT(Track::block->dT.front());
    Track::block->bunch->dtScInit_m = Track::block->dtScInit;
    Track::block->bunch->deltaTau_m = Track::block->deltaTau;

    if (!isFollowupTrack && !opal->inRestartRun())
        Track::block->bunch->setT(Track::block->t0_m);
    if (Track::block->bunch->getIfBeamEmitting()) {
      Track::block->bunch->setChargeZeroPart(charge);
    } else {
      Track::block->bunch->setCharge(charge);
    }
    // set coupling constant
    double coefE = 1.0 / (4 * pi * epsilon_0);
    Track::block->bunch->setCouplingConstant(coefE);


    // statistical data are calculated (rms, eps etc.)
    Track::block->bunch->calcBeamParameters();

frey_m's avatar
frey_m committed
421
    initDataSink();
422

423
    if(!opal->hasBunchAllocated())
424 425 426
      *gmsg << *dist << endl;

    if (Track::block->bunch->getTotalNum() > 0) {
427
        double spos = /*Track::block->bunch->get_sPos() +*/ Track::block->zstart;
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
        auto &zstop = Track::block->zstop;
        auto &timeStep = Track::block->localTimeSteps;
        auto &dT = Track::block->dT;

        unsigned int i = 0;
        while (i + 1 < zstop.size() && zstop[i + 1] < spos) {
            ++ i;
        }

        zstop.erase(zstop.begin(), zstop.begin() + i);
        timeStep.erase(timeStep.begin(), timeStep.begin() + i);
        dT.erase(dT.begin(), dT.begin() + i);

        Track::block->bunch->setdT(dT.front());
    } else {
        Track::block->zstart = 0.0;
    }

    *gmsg << *beam << endl;
    *gmsg << *fs   << endl;
    *gmsg << level2
          << "Phase space dump frequency " << Options::psDumpFreq << " and "
          << "statistics dump frequency " << Options::statDumpFreq << " w.r.t. the time step." << endl;

    itsTracker = new ThickTracker(*Track::block->use->fetchLine(),
snuverink_j's avatar
snuverink_j committed
453
                                  Track::block->bunch, *beam, *ds, Track::block->reference,
454 455
                                  false, false, Track::block->localTimeSteps,
                                  Track::block->zstart, Track::block->zstop, Track::block->dT,
456
                                  Track::block->truncOrder);
457 458 459
}


460 461
void TrackRun::setupTTracker(){
    OpalData::getInstance()->setInOPALTMode();
462
    bool isFollowupTrack = opal->hasBunchAllocated();
463

464 465 466 467 468 469 470 471 472
    if(isFollowupTrack) {
        *gmsg << "* ********************************************************************************** " << endl;
        *gmsg << "* Selected Tracking Method == PARALLEL-T, FOLLOWUP TRACK" << endl;
        *gmsg << "* ********************************************************************************** " << endl;
        Track::block->bunch->setLocalTrackStep(0);
    } else {
        *gmsg << "* ********************************************************************************** " << endl;
        *gmsg << "* Selected Tracking Method == PARALLEL-T, NEW TRACK" << endl;
        *gmsg << "* ********************************************************************************** " << endl;
473
    }
474

475
    Beam *beam = Beam::find(Attributes::getString(itsAttr[BEAM]));
476 477
    Track::block->bunch->setBeamFrequency(beam->getFrequency() * 1e6);

478 479 480 481 482 483 484
    if (Attributes::getString(itsAttr[BOUNDARYGEOMETRY]) != "NONE") {
        // Ask the dictionary if BoundaryGeometry is allocated.
        // If it is allocated use the allocated BoundaryGeometry
        if (!OpalData::getInstance()->hasGlobalGeometry()) {
            BoundaryGeometry *bg = BoundaryGeometry::find(Attributes::getString(itsAttr[BOUNDARYGEOMETRY]))->
                clone(getOpalName() + std::string("_geometry"));
            OpalData::getInstance()->setGlobalGeometry(bg);
485
        }
486
    }
487

488
    setupFieldsolver();
489

490 491 492
    if(opal->inRestartRun()) {
        phaseSpaceSink_m = new H5PartWrapperForPT(opal->getInputBasename() + std::string(".h5"),
                                                  opal->getRestartStep(),
493 494
                                                  OpalData::getInstance()->getRestartFileName(),
                                                  H5_O_WRONLY);
495
    } else if (isFollowupTrack) {
496
        phaseSpaceSink_m = new H5PartWrapperForPT(opal->getInputBasename() + std::string(".h5"),
497
                                                  -1,
498
                                                  opal->getInputBasename() + std::string(".h5"),
499
                                                  H5_O_WRONLY);
500
    } else {
501
        phaseSpaceSink_m = new H5PartWrapperForPT(opal->getInputBasename() + std::string(".h5"),
502 503 504
                                                  H5_O_WRONLY);
    }

505
    double charge = setDistributionParallelT(beam);
506

507 508 509
    Track::block->bunch->setdT(Track::block->dT.front());
    Track::block->bunch->dtScInit_m = Track::block->dtScInit;
    Track::block->bunch->deltaTau_m = Track::block->deltaTau;
510

511
    if (!isFollowupTrack && !opal->inRestartRun())
512
        Track::block->bunch->setT(Track::block->t0_m);
513

514 515
    if (Track::block->bunch->getIfBeamEmitting()) {
        Track::block->bunch->setChargeZeroPart(charge);
516
    } else {
517
        Track::block->bunch->setCharge(charge);
518
    }
519 520 521
    // set coupling constant
    double coefE = 1.0 / (4 * pi * epsilon_0);
    Track::block->bunch->setCouplingConstant(coefE);
522

523 524
    // statistical data are calculated (rms, eps etc.)
    Track::block->bunch->calcBeamParameters();
gsell's avatar
gsell committed
525

frey_m's avatar
frey_m committed
526
    initDataSink();
gsell's avatar
gsell committed
527

528
    if(!opal->hasBunchAllocated()) {
529 530
        *gmsg << std::scientific;
        *gmsg << *dist << endl;
531
    }
gsell's avatar
gsell committed
532

533
    if (Track::block->bunch->getTotalNum() > 0) {
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
534
        double spos = Track::block->zstart;
535
        auto &zstop = Track::block->zstop;
536
        auto it = Track::block->dT.begin();
537 538

        unsigned int i = 0;
539
        while (i + 1 < zstop.size() && zstop[i + 1] < spos) {
540
            ++ i;
541
            ++ it;
542 543
        }

544
        Track::block->bunch->setdT(*it);
545 546
    } else {
        Track::block->zstart = 0.0;
547 548
    }

549 550
    *gmsg << *beam << endl;
    *gmsg << *fs   << endl;
gsell's avatar
gsell committed
551

552
    // findPhasesForMaxEnergy();
553

kraus's avatar
kraus committed
554 555
    *gmsg << level2
          << "Phase space dump frequency " << Options::psDumpFreq << " and "
556
          << "statistics dump frequency " << Options::statDumpFreq << " w.r.t. the time step." << endl;
Andreas Adelmann's avatar
Andreas Adelmann committed
557 558
#ifdef P3M_TEST

559
    Track::block->bunch->runTests();
Andreas Adelmann's avatar
Andreas Adelmann committed
560 561

#else
562
    itsTracker = new ParallelTTracker(*Track::block->use->fetchLine(),
563 564 565 566
                                      Track::block->bunch,
                                      *ds,
                                      Track::block->reference,
                                      false,
567
                                      Attributes::getBool(itsAttr[TRACKBACK]),
568 569 570 571
                                      Track::block->localTimeSteps,
                                      Track::block->zstart,
                                      Track::block->zstop,
                                      Track::block->dT);
572
#endif
573
}
gsell's avatar
gsell committed
574

575 576 577
void TrackRun::setupCyclotronTracker(){
    OpalData::getInstance()->setInOPALCyclMode();
    Beam *beam = Beam::find(Attributes::getString(itsAttr[BEAM]));
gsell's avatar
gsell committed
578

579
    if (Attributes::getString(itsAttr[BOUNDARYGEOMETRY]) != "NONE") {
580
        // Ask the dictionary if BoundaryGeometry is allocated.
581
        // If it is allocated use the allocated BoundaryGeometry
582
        if (!OpalData::getInstance()->hasGlobalGeometry()) {
583
            BoundaryGeometry *bg = BoundaryGeometry::find(Attributes::getString(itsAttr[BOUNDARYGEOMETRY]))->
584
                clone(getOpalName() + std::string("_geometry"));
585 586
            OpalData::getInstance()->setGlobalGeometry(bg);
        }
587
    }
adelmann's avatar
adelmann committed
588

589
    setupFieldsolver();
gsell's avatar
gsell committed
590

kraus's avatar
kraus committed
591
    Track::block->bunch->PType = ParticleType::REGULAR;
gsell's avatar
gsell committed
592

593 594 595 596 597 598
    std::vector<std::string> distr_str = Attributes::getStringArray(itsAttr[DISTRIBUTION]);
    if (distr_str.size() == 0) {
        dist = Distribution::find(defaultDistribution);
    } else {
        dist = Distribution::find(distr_str.at(0));
    }
gsell's avatar
gsell committed
599

600 601 602
    // set macromass and charge for simulation particles
    double macromass = 0.0;
    double macrocharge = 0.0;
gsell's avatar
gsell committed
603

604
    // multi-bunch parameters
605
    const int specifiedNumBunch = int(std::abs(std::round(Attributes::getReal(itsAttr[TURNS]))));
606 607 608 609
    const double mbPara         = Attributes::getReal(itsAttr[PARAMB]);
    const std::string mbMode    = Util::toUpper(Attributes::getString(itsAttr[MBMODE]));
    const double mbEta          = Attributes::getReal(itsAttr[MB_ETA]);
    const std::string mbBinning = Attributes::getString(itsAttr[MB_BINNING]);
ext-rogers_c's avatar
ext-rogers_c committed
610 611 612 613 614 615

    if(opal->inRestartRun()) {
        phaseSpaceSink_m = new H5PartWrapperForPC(opal->getInputBasename() + std::string(".h5"),
                                                  opal->getRestartStep(),
                                                  OpalData::getInstance()->getRestartFileName(),
                                                  H5_O_WRONLY);
616
    } else if (opal->hasBunchAllocated()) {
ext-rogers_c's avatar
ext-rogers_c committed
617 618 619 620 621 622 623
        phaseSpaceSink_m = new H5PartWrapperForPC(opal->getInputBasename() + std::string(".h5"),
                                                  -1,
                                                  opal->getInputBasename() + std::string(".h5"),
                                                  H5_O_WRONLY);
    } else {
        phaseSpaceSink_m = new H5PartWrapperForPC(opal->getInputBasename() + std::string(".h5"),
                                                  H5_O_WRONLY);
624 625
    }

626 627 628
    if(beam->getNumberOfParticles() < 3 || beam->getCurrent() == 0.0) {
        macrocharge = beam->getCharge() * q_e;
        macromass = beam->getMass();
frey_m's avatar
frey_m committed
629
        dist->createOpalCycl(Track::block->bunch,
630
                             beam->getNumberOfParticles(),
631
                             beam->getCurrent(),*Track::block->use->fetchLine());
gsell's avatar
gsell committed
632

633
    } else {
gsell's avatar
gsell committed
634

635
        /**
636
           getFrequency() gets RF frequency [MHz], NOT isochronous revolution frequency of particle!
637
           getCurrent() gets beamcurrent [A]
gsell's avatar
gsell committed
638

639 640
        */
        macrocharge = beam->getCurrent() / (beam->getFrequency() * 1.0e6); // [MHz]-->[Hz]
gsell's avatar
gsell committed
641

642 643
        if(!opal->hasBunchAllocated()) {
            if(!opal->inRestartRun()) {
gsell's avatar
gsell committed
644 645
                macrocharge /= beam->getNumberOfParticles();
                macromass = beam->getMass() * macrocharge / (beam->getCharge() * q_e);
frey_m's avatar
frey_m committed
646
                dist->createOpalCycl(Track::block->bunch,
647 648
                                     beam->getNumberOfParticles(),
                                     beam->getCurrent(),
649
                                     *Track::block->use->fetchLine());
650 651

            } else {
frey_m's avatar
frey_m committed
652
                dist->doRestartOpalCycl(Track::block->bunch,
653
                                        beam->getNumberOfParticles(),
654
                                        opal->getRestartStep(),
655 656
                                        specifiedNumBunch,
                                        phaseSpaceSink_m);
657 658
                macrocharge /= beam->getNumberOfParticles();
                macromass = beam->getMass() * macrocharge / (beam->getCharge() * q_e);
gsell's avatar
gsell committed
659 660
            }
        }
661 662 663
    }
    Track::block->bunch->setMass(macromass); // set the Mass per macro-particle, [GeV/c^2]
    Track::block->bunch->setCharge(macrocharge);  // set the charge per macro-particle, [C]
gsell's avatar
gsell committed
664

665 666
    *gmsg << "* Mass of simulation particle= " << macromass << " GeV/c^2" << endl;
    *gmsg << "* Charge of simulation particle= " << macrocharge << " [C]" << endl;
gsell's avatar
gsell committed
667

668 669
    Track::block->bunch->setdT(1.0 / (Track::block->stepsPerTurn * beam->getFrequency() * 1.0e6));
    Track::block->bunch->setStepsPerTurn(Track::block->stepsPerTurn);
gsell's avatar
gsell committed
670

671 672 673
    // set coupling constant
    double coefE = 1.0 / (4 * pi * epsilon_0);
    Track::block->bunch->setCouplingConstant(coefE);
gsell's avatar
gsell committed
674

675
    // statistical data are calculated (rms, eps etc.)
676
    Track::block->bunch->calcBeamParameters();
677

frey_m's avatar
frey_m committed
678
    initDataSink(specifiedNumBunch);
679

680
    if(!opal->hasBunchAllocated()) {
681
        *gmsg << "* ********************************************************************************** " << endl;
682
        *gmsg << "* Selected Tracking Method == CYCLOTRON-T, NEW TRACK" << endl;
683
        *gmsg << "* ********************************************************************************** " << endl;
684
    } else {
gsell's avatar
gsell committed
685
        *gmsg << "* ********************************************************************************** " << endl;
686
        *gmsg << "* Selected Tracking Method == CYCLOTRON-T, FOLLOWUP TRACK" << endl;
687 688 689 690 691 692 693 694
        *gmsg << "* ********************************************************************************** " << endl;
    }
    *gmsg << "* Number of neighbour bunches= " << specifiedNumBunch << endl;
    *gmsg << "* DT                         = " << Track::block->dT.front() << endl;
    *gmsg << "* MAXSTEPS                   = " << Track::block->localTimeSteps.front() << endl;
    *gmsg << "* Phase space dump frequency = " << Options::psDumpFreq << endl;
    *gmsg << "* Statistics dump frequency  = " << Options::statDumpFreq << " w.r.t. the time step." << endl;
    *gmsg << "* ********************************************************************************** " << endl;
695

696
    itsTracker = new ParallelCyclotronTracker(*Track::block->use->fetchLine(),
frey_m's avatar
frey_m committed
697
                                              Track::block->bunch, *ds, Track::block->reference,
698
                                              false, false, Track::block->localTimeSteps.front(),
699 700
                                              Track::block->timeIntegrator,
                                              specifiedNumBunch, mbEta, mbPara, mbMode, mbBinning);
gsell's avatar
gsell committed
701

702 703
    ParallelCyclotronTracker* cyclTracker = dynamic_cast<ParallelCyclotronTracker*>(itsTracker);

704
    if(opal->inRestartRun()) {
705

706
        H5PartWrapperForPC *h5pw = static_cast<H5PartWrapperForPC*>(phaseSpaceSink_m);
707
        cyclTracker->setBeGa(h5pw->getMeanMomentum());
708

709 710 711
        cyclTracker->setPr(h5pw->getReferencePr());
        cyclTracker->setPt(h5pw->getReferencePt());
        cyclTracker->setPz(h5pw->getReferencePz());
712

713 714 715
        cyclTracker->setR(h5pw->getReferenceR());
        cyclTracker->setTheta(h5pw->getReferenceT());
        cyclTracker->setZ(h5pw->getReferenceZ());
716

717
        // The following is for restarts in local frame
718 719 720
        cyclTracker->setPhi(h5pw->getAzimuth());
        cyclTracker->setPsi(h5pw->getElevation());
        cyclTracker->setPreviousH5Local(h5pw->getPreviousH5Local());
721 722 723 724

        if ( specifiedNumBunch > 1 ) {
            cyclTracker->setLastDumpedStep(opal->getRestartStep());
        }
725
    }
726

727
    // statistical data are calculated (rms, eps etc.)
728
    Track::block->bunch->calcBeamParameters();
729

730 731 732 733 734
    *gmsg << *dist << endl;
    *gmsg << *beam << endl;
    *gmsg << *fs   << endl;
    // *gmsg << *Track::block->bunch  << endl;
}
gsell's avatar
gsell committed
735

736 737
void TrackRun::setupFieldsolver() {
    fs = FieldSolver::find(Attributes::getString(itsAttr[FIELDSOLVER]));
738

739 740 741 742
    if (Util::toUpper(fs->getType()) != std::string("NONE")) {
        size_t numGridPoints = fs->getMX()*fs->getMY()*fs->getMT(); // total number of gridpoints
        Beam *beam = Beam::find(Attributes::getString(itsAttr[BEAM]));
        size_t numParticles = beam->getNumberOfParticles();
743

frey_m's avatar
frey_m committed
744
        if (!opal->inRestartRun() && numParticles < numGridPoints
745
            && Util::toUpper(fs->getType()) != std::string("SAAMG") // in SPIRAL/SAAMG we're meshing the whole domain -DW
frey_m's avatar
frey_m committed
746 747 748 749 750 751
#ifdef ENABLE_AMR
            && !Options::amr)
#else
            )
#endif
        {
752
            throw OpalException("TrackRun::setupFieldsolver()",
kraus's avatar
kraus committed
753 754 755
                                "The number of simulation particles (" + std::to_string(numParticles) + ") \n" +
                                "is smaller than the number of gridpoints (" + std::to_string(numGridPoints) + ").\n" +
                                "Please increase the number of particles or reduce the size of the mesh.\n");
frey_m's avatar
frey_m committed
756
        }
adelmann's avatar
adelmann committed
757 758 759 760 761

        OpalData::getInstance()->addProblemCharacteristicValue("MX", fs->getMX());
        OpalData::getInstance()->addProblemCharacteristicValue("MY", fs->getMY());
        OpalData::getInstance()->addProblemCharacteristicValue("MT", fs->getMT());

762
    }
763

764 765 766 767 768 769
    fs->initCartesianFields();
    Track::block->bunch->setSolver(fs);
    if (fs->hasPeriodicZ())
        Track::block->bunch->setBCForDCBeam();
    else
        Track::block->bunch->setBCAllOpen();
gsell's avatar
gsell committed
770
}
771

frey_m's avatar
frey_m committed
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788

void TrackRun::initDataSink(const int& numBunch) {
    if(!opal->inRestartRun()) {
        if(!opal->hasDataSinkAllocated()) {
            opal->setDataSink(new DataSink(phaseSpaceSink_m, false, numBunch));
        } else {
            ds = opal->getDataSink();
            ds->changeH5Wrapper(phaseSpaceSink_m);
        }
    } else {
        opal->setDataSink(new DataSink(phaseSpaceSink_m, true, numBunch));
    }

    ds = opal->getDataSink();
}


789
double TrackRun::setDistributionParallelT(Beam *beam) {
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
    /*
     * Distribution(s) can be set via a single distribution or a list
     * (array) of distributions. If an array is defined the first in the
     * list is treated as the primary distribution. All others are added to
     * it to create the full distribution.
     */
    std::vector<std::string> distributionArray
        = Attributes::getStringArray(itsAttr[DISTRIBUTION]);
    const size_t numberOfDistributions = distributionArray.size();

    if (numberOfDistributions == 0) {
        dist = Distribution::find(defaultDistribution);
    } else {
        dist = Distribution::find(distributionArray.at(0));
        dist->setNumberOfDistributions(numberOfDistributions);

        if (numberOfDistributions > 1) {
            *gmsg << endl
                  << "---------------------------------" << endl
                  << "Found more than one distribution:" << endl << endl;
            *gmsg << "Main Distribution" << endl
                  << "---------------------------------" << endl
                  << distributionArray.at(0) << endl << endl
                  << "Secondary Distribution(s)" << endl
                  << "---------------------------------" << endl;

            for (size_t i = 1; i < numberOfDistributions; ++ i) {
                Distribution *distribution = Distribution::find(distributionArray.at(i));
                distribution->setNumberOfDistributions(numberOfDistributions);
                distrs_m.push_back(distribution);

                *gmsg << distributionArray.at(i) << endl;
823
            }
824 825
            *gmsg << endl
                  << "---------------------------------" << endl << endl;
826
        }
827 828 829 830 831 832
    }

    /*
     * Initialize distributions.
     */
    size_t numberOfParticles = beam->getNumberOfParticles();
833 834
    if (!opal->hasBunchAllocated()) {
        if (!opal->inRestartRun()) {
835 836 837 838 839 840 841 842 843 844 845 846 847 848
            /*
             * Here we are not doing a restart run
             * and we do not have a bunch already allocated.
             */
            Track::block->bunch->setDistribution(dist,
                                                 distrs_m,
                                                 numberOfParticles);

            /*
             * If this is an injected beam (rather than an emitted beam), we
             * make sure it doesn't have any particles at z < 0.
             */

            opal->setGlobalPhaseShift(0.5 * dist->getTEmission() + dist->getEmissionTimeShift());
849 850 851 852
        } else {
            /*
             * Read in beam from restart file.
             */
frey_m's avatar
frey_m committed
853
            dist->doRestartOpalT(Track::block->bunch, numberOfParticles, opal->getRestartStep(), phaseSpaceSink_m);
854 855 856 857
        }
    }

    // Return charge per macroparticle.
snuverink_j's avatar
snuverink_j committed
858
    return beam->getCharge() * beam->getCurrent() / (beam->getFrequency()*1.0e6) / numberOfParticles;
859

860
}