ParallelCyclotronTracker.cpp 128 KB
Newer Older
gsell's avatar
gsell committed
1 2 3 4 5 6 7 8 9
// ------------------------------------------------------------------------
// $RCSfile: ParallelCyclotronTracker.cpp,v $
// ------------------------------------------------------------------------
// $Revision: 1.1 $initialLocalNum_m
// ------------------------------------------------------------------------
// Copyright: see Copyright.readme
// ------------------------------------------------------------------------
//
// Class: ParallelCyclotronTracker
ext-rogers_c's avatar
ext-rogers_c committed
10
//   The class for tracking particles with 3D space charge in Cyclotrons and FFAs
gsell's avatar
gsell committed
11 12 13 14
//
// ------------------------------------------------------------------------
//
// $Date: 2007/10/17 04:00:08 $
15
// $Author: adelmann, yang, winklehner $
gsell's avatar
gsell committed
16 17
//
// ------------------------------------------------------------------------
kraus's avatar
kraus committed
18 19

#include "Algorithms/ParallelCyclotronTracker.h"
20

gsell's avatar
gsell committed
21
#include <fstream>
22 23
#include <iostream>
#include <limits>
gsell's avatar
gsell committed
24
#include <vector>
25 26

#include "AbstractObjects/Element.h"
27
#include "AbstractObjects/OpalData.h"
gsell's avatar
gsell committed
28

29
#include "AbsBeamline/CCollimator.h"
gsell's avatar
gsell committed
30 31
#include "AbsBeamline/Corrector.h"
#include "AbsBeamline/Cyclotron.h"
32
#include "AbsBeamline/CyclotronValley.h"
adelmann's avatar
adelmann committed
33
#include "AbsBeamline/Degrader.h"
gsell's avatar
gsell committed
34 35 36 37
#include "AbsBeamline/Diagnostic.h"
#include "AbsBeamline/Drift.h"
#include "AbsBeamline/ElementBase.h"
#include "AbsBeamline/Lambertson.h"
38
#include "AbsBeamline/Offset.h"
gsell's avatar
gsell committed
39 40 41
#include "AbsBeamline/Marker.h"
#include "AbsBeamline/Monitor.h"
#include "AbsBeamline/Multipole.h"
ext-rogers_c's avatar
ext-rogers_c committed
42
#include "AbsBeamline/MultipoleT.h"
43 44 45 46
#include "AbsBeamline/MultipoleTBase.h"
#include "AbsBeamline/MultipoleTStraight.h"
#include "AbsBeamline/MultipoleTCurvedConstRadius.h"
#include "AbsBeamline/MultipoleTCurvedVarRadius.h"
47
#include "AbsBeamline/PluginElement.h"
gsell's avatar
gsell committed
48 49
#include "AbsBeamline/Probe.h"
#include "AbsBeamline/RBend.h"
50
#include "AbsBeamline/Ring.h"
gsell's avatar
gsell committed
51 52 53
#include "AbsBeamline/RFCavity.h"
#include "AbsBeamline/RFQuadrupole.h"
#include "AbsBeamline/SBend.h"
54
#include "AbsBeamline/SBend3D.h"
ext-rogers_c's avatar
ext-rogers_c committed
55
#include "AbsBeamline/ScalingFFAMagnet.h"
gsell's avatar
gsell committed
56 57 58 59
#include "AbsBeamline/Separator.h"
#include "AbsBeamline/Septum.h"
#include "AbsBeamline/Solenoid.h"
#include "AbsBeamline/Stripper.h"
60
#include "AbsBeamline/VariableRFCavity.h"
61
#include "AbsBeamline/VariableRFCavityFringeField.h"
62

63 64
#include "Algorithms/Ctunes.h"
#include "Algorithms/PolynomialTimeDependence.h"
gsell's avatar
gsell committed
65 66

#include "Beamlines/Beamline.h"
67
#include "Beamlines/FlaggedBeamline.h"
gsell's avatar
gsell committed
68

69
#include "Elements/OpalBeamline.h"
gsell's avatar
gsell committed
70 71 72 73

#include "Physics/Physics.h"

#include "Utilities/OpalException.h"
74
#include "Utilities/Options.h"
gsell's avatar
gsell committed
75

76
#include "BasicActions/DumpFields.h"
77
#include "BasicActions/DumpEMFields.h"
78

79
#include "Structure/H5PartWrapperForPC.h"
80
#include "Structure/BoundaryGeometry.h"
gsell's avatar
gsell committed
81

frey_m's avatar
frey_m committed
82 83
//FIXME Remove headers and dynamic_cast in readOneBunchFromFile
#include "Algorithms/PartBunch.h"
84
#ifdef ENABLE_AMR
frey_m's avatar
frey_m committed
85 86
    #include "Algorithms/AmrPartBunch.h"
#endif
frey_m's avatar
frey_m committed
87

gsell's avatar
gsell committed
88 89 90
using Physics::pi;
using Physics::q_e;

91

92
const double c_mmtns = Physics::c * 1.0e-6; // m/s --> mm/ns
93

94 95 96
Vector_t const ParallelCyclotronTracker::xaxis = Vector_t(1.0, 0.0, 0.0);
Vector_t const ParallelCyclotronTracker::yaxis = Vector_t(0.0, 1.0, 0.0);
Vector_t const ParallelCyclotronTracker::zaxis = Vector_t(0.0, 0.0, 1.0);
gsell's avatar
gsell committed
97 98 99 100 101 102 103 104 105 106 107 108

extern Inform *gmsg;

/**
 * Constructor ParallelCyclotronTracker
 *
 * @param beamline
 * @param reference
 * @param revBeam
 * @param revTrack
 */
ParallelCyclotronTracker::ParallelCyclotronTracker(const Beamline &beamline,
109
                                                   const PartData &reference,
frey_m's avatar
frey_m committed
110 111 112 113 114
                                                   bool revBeam, bool revTrack)
    : Tracker(beamline, reference, revBeam, revTrack)
    , itsDataSink(nullptr)
    , itsMBDump_m(new MultiBunchDump())
    , bgf_m(nullptr)
115
    , numBunch_m(1)
frey_m's avatar
frey_m committed
116 117 118 119 120 121 122 123 124 125 126
    , lastDumpedStep_m(0)
    , eta_m(0.01)
    , myNode_m(Ippl::myNode())
    , initialLocalNum_m(0)
    , initialTotalNum_m(0)
    , onebunch_m(OpalData::getInstance()->getInputBasename() + "-onebunch.h5")
    , opalRing_m(nullptr)
    , itsStepper_mp(nullptr)
    , mode_m(MODE::UNDEFINED)
    , stepper_m(stepper::INTEGRATOR::UNDEFINED)
{
gsell's avatar
gsell committed
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
    itsBeamline = dynamic_cast<Beamline *>(beamline.clone());
}

/**
 * Constructor ParallelCyclotronTracker
 *
 * @param beamline
 * @param bunch
 * @param ds
 * @param reference
 * @param revBeam
 * @param revTrack
 * @param maxSTEPS
 * @param timeIntegrator
 */
ParallelCyclotronTracker::ParallelCyclotronTracker(const Beamline &beamline,
frey_m's avatar
frey_m committed
143
                                                   PartBunchBase<double, 3> *bunch,
gsell's avatar
gsell committed
144 145 146
                                                   DataSink &ds,
                                                   const PartData &reference,
                                                   bool revBeam, bool revTrack,
frey_m's avatar
frey_m committed
147
                                                   int maxSTEPS, int timeIntegrator,
frey_m's avatar
frey_m committed
148
                                                   int numBunch)
frey_m's avatar
frey_m committed
149 150 151 152
    : Tracker(beamline, bunch, reference, revBeam, revTrack)
    , itsMBDump_m(new MultiBunchDump())
    , bgf_m(nullptr)
    , maxSteps_m(maxSTEPS)
153
    , numBunch_m(numBunch)
frey_m's avatar
frey_m committed
154 155 156 157 158 159 160 161 162
    , lastDumpedStep_m(0)
    , eta_m(0.01)
    , myNode_m(Ippl::myNode())
    , initialLocalNum_m(bunch->getLocalNum())
    , initialTotalNum_m(bunch->getTotalNum())
    , onebunch_m(OpalData::getInstance()->getInputBasename() + "-onebunch.h5")
    , opalRing_m(nullptr)
    , itsStepper_mp(nullptr)
{
gsell's avatar
gsell committed
163 164
    itsBeamline = dynamic_cast<Beamline *>(beamline.clone());
    itsDataSink = &ds;
frey_m's avatar
frey_m committed
165
    //  scaleFactor_m = itsBunch_m->getdT() * c;
gsell's avatar
gsell committed
166
    scaleFactor_m = 1;
167
    multiBunchMode_m = MB_MODE::NONE;
gsell's avatar
gsell committed
168 169 170 171 172

    IntegrationTimer_m = IpplTimings::getTimer("Integration");
    TransformTimer_m   = IpplTimings::getTimer("Frametransform");
    DumpTimer_m        = IpplTimings::getTimer("Dump");
    BinRepartTimer_m   = IpplTimings::getTimer("Binaryrepart");
173

174 175 176 177 178 179 180 181 182
    // FIXME Change track command
    if ( initialTotalNum_m == 1 ) {
        mode_m = MODE::SINGLE;
    } else if ( initialTotalNum_m == 2 ) {
        mode_m = MODE::SEO;
    } else if ( initialTotalNum_m > 2 ) {
        mode_m = MODE::BUNCH;
    } else
        mode_m = MODE::UNDEFINED;
183

184 185 186 187 188 189 190 191
    if ( timeIntegrator == 0 ) {
        stepper_m = stepper::INTEGRATOR::RK4;
    } else if ( timeIntegrator == 1) {
        stepper_m = stepper::INTEGRATOR::LF2;
    } else if ( timeIntegrator == 2) {
        stepper_m = stepper::INTEGRATOR::MTS;
    } else
        stepper_m = stepper::INTEGRATOR::UNDEFINED;
gsell's avatar
gsell committed
192 193 194 195 196 197 198
}

/**
 * Destructor ParallelCyclotronTracker
 *
 */
ParallelCyclotronTracker::~ParallelCyclotronTracker() {
199 200
    for(Component* component : myElements) {
        delete(component);
gsell's avatar
gsell committed
201
    }
202 203
    for(auto fd : FieldDimensions) {
        delete(fd);
gsell's avatar
gsell committed
204 205
    }
    delete itsBeamline;
206
    // delete opalRing_m;
gsell's avatar
gsell committed
207 208
}

209 210 211 212
/// set the working sub-mode for multi-bunch mode: "FORCE" or "AUTO"
void ParallelCyclotronTracker::setMultiBunchMode(const std::string& mbmode)
{
    if ( mbmode.compare("FORCE") == 0 ) {
213 214
        *gmsg << "FORCE mode: The multi bunches will be injected consecutively" << endl
              << "            after each revolution, until get \"TURNS\" bunches." << endl;
215 216
        multiBunchMode_m = MB_MODE::FORCE;
    } else if ( mbmode.compare("AUTO") == 0 ) {
217 218 219 220
        *gmsg << "AUTO mode: The multi bunches will be injected only when the" << endl
              << "           distance between two neighboring bunches is below" << endl
              << "           the limitation. The control parameter is set to "
              << CoeffDBunches_m << endl;
221 222 223 224 225 226 227 228
        multiBunchMode_m = MB_MODE::AUTO;
    } else if ( mbmode.compare("NONE") == 0 )
        multiBunchMode_m = MB_MODE::NONE;
    else
        throw OpalException("ParallelCyclotronTracker::setMultiBunchMode()",
                            "MBMODE name \"" + mbmode + "\" unknown.");
}

frey_m's avatar
frey_m committed
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
void ParallelCyclotronTracker::setMultiBunchBinning(std::string binning) {
    
    binning = Util::toUpper(binning);
    
    if ( binning.compare("BUNCH") == 0 ) {
        *gmsg << "Use 'BUNCH' injection for binnning." << endl;
        binningType_m = MB_BINNING::BUNCH;
    } else if ( binning.compare("GAMMA") == 0 ) {
        *gmsg << "Use 'GAMMA' for binning." << endl;
        binningType_m = MB_BINNING::GAMMA;
    } else {
        throw OpalException("ParallelCyclotronTracker::setMultiBunchBinning()",
                            "MB_BINNING name \"" + binning + "\" unknown.");
    }
}

245 246 247 248 249 250
/**
 *
 *
 * @param fn Base file name
 */
void ParallelCyclotronTracker::bgf_main_collision_test() {
251
    if(!bgf_m) return;
252

253
    Inform msg("bgf_main_collision_test ");
254

255 256 257
    /**
     *Here we check if a particles is outside the domain, flag it for deletion
     */
258

259
    Vector_t intecoords = 0.0;
260

261
    // This has to match the dT in the rk4 pusher
frey_m's avatar
frey_m committed
262
    double dtime = itsBunch_m->getdT() * getHarmonicNumber();
263

264
    int triId = 0;
frey_m's avatar
frey_m committed
265 266 267
    for(size_t i = 0; i < itsBunch_m->getLocalNum(); i++) {
        int res = bgf_m->partInside(itsBunch_m->R[i], itsBunch_m->P[i], dtime, itsBunch_m->PType[i], itsBunch_m->Q[i], intecoords, triId);
        //int res = bgf_m->partInside(itsBunch_m->R[i]*1.0e-3, itsBunch_m->P[i], dtime, itsBunch_m->PType[i], itsBunch_m->Q[i], intecoords, triId);
268
        if(res >= 0) {
frey_m's avatar
frey_m committed
269
            itsBunch_m->Bin[i] = -1;
270
        }
271
    }
272 273 274
}


gsell's avatar
gsell committed
275 276 277 278 279
/**
 *
 *
 * @param fn Base file name
 */
280
void ParallelCyclotronTracker::openFiles(std::string SfileName) {
gsell's avatar
gsell committed
281

282
    std::string  SfileName2 = SfileName + std::string("-Angle0.dat");
gsell's avatar
gsell committed
283
    outfTheta0_m.precision(8);
284
    outfTheta0_m.setf(std::ios::scientific, std::ios::floatfield);
gsell's avatar
gsell committed
285
    outfTheta0_m.open(SfileName2.c_str());
286 287 288
    outfTheta0_m << "#  r [mm]      beta_r*gamma       "
                 << "theta [mm]      beta_theta*gamma        "
                 << "z [mm]          beta_z*gamma" << std::endl;
gsell's avatar
gsell committed
289

290
    SfileName2 = SfileName + std::string("-Angle1.dat");
gsell's avatar
gsell committed
291
    outfTheta1_m.precision(8);
292
    outfTheta1_m.setf(std::ios::scientific, std::ios::floatfield);
gsell's avatar
gsell committed
293
    outfTheta1_m.open(SfileName2.c_str());
294 295 296
    outfTheta1_m << "#  r [mm]      beta_r*gamma       "
                 << "theta [mm]      beta_theta*gamma        "
                 << "z [mm]          beta_z*gamma"  << std::endl;
gsell's avatar
gsell committed
297

298
    SfileName2 = SfileName + std::string("-Angle2.dat");
gsell's avatar
gsell committed
299
    outfTheta2_m.precision(8);
300
    outfTheta2_m.setf(std::ios::scientific, std::ios::floatfield);
gsell's avatar
gsell committed
301
    outfTheta2_m.open(SfileName2.c_str());
302 303 304
    outfTheta2_m << "#  r [mm]      beta_r*gamma       "
                 << "theta [mm]      beta_theta*gamma        "
                 << "z [mm]          beta_z*gamma"  << std::endl;
gsell's avatar
gsell committed
305 306 307

    // for single Particle Mode, output after each turn, to define matched initial phase ellipse.

308
    SfileName2 = SfileName + std::string("-afterEachTurn.dat");
gsell's avatar
gsell committed
309 310

    outfThetaEachTurn_m.precision(8);
311
    outfThetaEachTurn_m.setf(std::ios::scientific, std::ios::floatfield);
gsell's avatar
gsell committed
312 313

    outfThetaEachTurn_m.open(SfileName2.c_str());
314 315 316
    outfTheta2_m << "#  r [mm]      beta_r*gamma       "
                 << "theta [mm]      beta_theta*gamma        "
                 << "z [mm]          beta_z*gamma"  << std::endl;
gsell's avatar
gsell committed
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
}

/**
 * Close all files related to
 * special output in the Cyclotron
 * mode.
 */
void ParallelCyclotronTracker::closeFiles() {

    outfTheta0_m.close();
    outfTheta1_m.close();
    outfTheta2_m.close();
    outfThetaEachTurn_m.close();
}

332
/**
333 334 335
 *
 * @param ring
 */
kraus's avatar
kraus committed
336
void ParallelCyclotronTracker::visitRing(const Ring &ring) {
Daniel Winklehner's avatar
Daniel Winklehner committed
337

338
    *gmsg << "* ----------------------------- Adding Ring ------------------------------ *" << endl;
Daniel Winklehner's avatar
Daniel Winklehner committed
339

snuverink_j's avatar
snuverink_j committed
340
    delete opalRing_m;
Daniel Winklehner's avatar
Daniel Winklehner committed
341

kraus's avatar
kraus committed
342
    opalRing_m = dynamic_cast<Ring*>(ring.clone());
Daniel Winklehner's avatar
Daniel Winklehner committed
343

344
    myElements.push_back(opalRing_m);
Daniel Winklehner's avatar
Daniel Winklehner committed
345

frey_m's avatar
frey_m committed
346
    opalRing_m->initialise(itsBunch_m);
347 348 349 350

    referenceR = opalRing_m->getBeamRInit();
    referencePr = opalRing_m->getBeamPRInit();
    referenceTheta = opalRing_m->getBeamPhiInit();
Daniel Winklehner's avatar
Daniel Winklehner committed
351

352
    if(referenceTheta <= -180.0 || referenceTheta > 180.0) {
kraus's avatar
kraus committed
353
        throw OpalException("Error in ParallelCyclotronTracker::visitRing",
354 355
                            "PHIINIT is out of [-180, 180)!");
    }
Daniel Winklehner's avatar
Daniel Winklehner committed
356 357

    referenceZ = 0.0;
358
    referencePz = 0.0;
Daniel Winklehner's avatar
Daniel Winklehner committed
359 360 361 362

    referencePtot = itsReference.getGamma() * itsReference.getBeta();
    referencePt = sqrt(referencePtot * referencePtot - referencePr * referencePr);

363 364
    if(referencePtot < 0.0)
        referencePt *= -1.0;
Daniel Winklehner's avatar
Daniel Winklehner committed
365

366 367
    sinRefTheta_m = sin(referenceTheta * Physics::deg2rad);
    cosRefTheta_m = cos(referenceTheta * Physics::deg2rad);
gsell's avatar
gsell committed
368

snuverink_j's avatar
snuverink_j committed
369
    double BcParameter[8] = {}; // zero initialise array
Daniel Winklehner's avatar
Daniel Winklehner committed
370

371
    buildupFieldList(BcParameter, ElementBase::RING, opalRing_m);
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387

    // Finally print some diagnostic
    *gmsg << "* Initial beam radius = " << referenceR << " [mm] " << endl;
    *gmsg << "* Initial gamma = " << itsReference.getGamma() << endl;
    *gmsg << "* Initial beta = " << itsReference.getBeta() << endl;
    *gmsg << "* Total reference momentum   = " << referencePtot * 1000.0
          << " [MCU]" << endl;
    *gmsg << "* Reference azimuthal momentum  = " << referencePt * 1000.0
          << " [MCU]" << endl;
    *gmsg << "* Reference radial momentum     = " << referencePr * 1000.0
          << " [MCU]" << endl;
    *gmsg << "* " << opalRing_m->getSymmetry() << " fold field symmetry "
          << endl;
    *gmsg << "* Harmonic number h= " << opalRing_m->getHarmonicNumber() << " "
          << endl;
}
gsell's avatar
gsell committed
388 389 390 391 392 393 394 395

/**
 *
 *
 * @param cycl
 */
void ParallelCyclotronTracker::visitCyclotron(const Cyclotron &cycl) {

396
    *gmsg << "* -------------------------- Adding Cyclotron ---------------------------- *" << endl;
gsell's avatar
gsell committed
397

398 399
    Cyclotron *elptr = dynamic_cast<Cyclotron *>(cycl.clone());
    myElements.push_back(elptr);
400

401
    // Is this a Spiral Inflector Simulation? If yes, we'll give the user some
402 403 404 405 406 407
    // useful information
    spiral_flag = elptr->getSpiralFlag();

    if(spiral_flag) {

        *gmsg << endl << "* This is a Spiral Inflector Simulation! This means the following:" << endl;
408
        *gmsg         << "* 1.) It is up to the user to provide appropriate geometry, electric and magnetic fields!" << endl;
409 410
        *gmsg         << "*     (Use BANDRF type cyclotron and use RFMAPFN to load both magnetic" << endl;
        *gmsg         << "*     and electric fields, setting SUPERPOSE to an array of TRUE values.)" << endl;
snuverink_j's avatar
snuverink_j committed
411
        *gmsg         << "* 2.) For high currents it is strongly recommended to use the SAAMG fieldsolver," << endl;
412 413
        *gmsg         << "*     FFT does not give the correct results (boundary conditions are missing)." << endl;
        *gmsg         << "* 3.) The whole geometry will be meshed and used for the fieldsolver." << endl;
414 415
        *gmsg         << "*     There will be no transformations of the bunch into a local frame und consequently," << endl;
        *gmsg         << "*     the problem will be treated non-relativistically!" << endl;
416 417 418 419 420 421 422
        *gmsg         << "*     (This is not an issue for spiral inflectors as they are typically < 100 keV/amu.)" << endl;
        *gmsg << endl << "* Note: For now, multi-bunch mode (MBM) needs to be de-activated for spiral inflector" << endl;
        *gmsg         << "* and space charge needs to be solved every time-step. numBunch_m and scSolveFreq are reset." << endl;
        numBunch_m = 1;

    }

423
    // Fresh run (no restart):
424
    if(!OpalData::getInstance()->inRestartRun()) {
425

426
        // Get reference values from cyclotron element
427
        // For now, these are still stored in mm. should be the only ones. -DW
428 429 430 431
        referenceR     = elptr->getRinit();
        referenceTheta = elptr->getPHIinit();
        referenceZ     = elptr->getZinit();
        referencePr    = elptr->getPRinit();
432 433
        referencePz    = elptr->getPZinit();

434
        if(referenceTheta <= -180.0 || referenceTheta > 180.0) {
435 436
            throw OpalException("Error in ParallelCyclotronTracker::visitCyclotron",
                                "PHIINIT is out of [-180, 180)!");
437 438 439 440 441
        }

        referencePtot =  itsReference.getGamma() * itsReference.getBeta();

        // Calculate reference azimuthal (tangential) momentum from total-, z- and radial momentum:
442
        float insqrt = referencePtot * referencePtot - \
443
            referencePr * referencePr - referencePz * referencePz;
444 445 446 447 448

        if(insqrt < 0) {

            if(insqrt > -1.0e-10) {

449
                referencePt = 0.0;
450 451 452

            } else {

453
                throw OpalException("Error in ParallelCyclotronTracker::visitCyclotron",
454
                                    "Pt imaginary!");
455 456 457 458 459 460 461
            }

        } else {

            referencePt = sqrt(insqrt);
        }

462
        if(referencePtot < 0.0)
Daniel Winklehner's avatar
Daniel Winklehner committed
463
            referencePt *= -1.0;
464 465
        // End calculate referencePt

466
        // Restart a run:
467 468
    } else {

469
        // If the user wants to save the restarted run in local frame,
470
        // make sure the previous h5 file was local too
471
      if (Options::psDumpFrame != Options::GLOBAL) {
winklehner_d's avatar
-DW  
winklehner_d committed
472
        if (!previousH5Local) {
473 474
                throw OpalException("Error in ParallelCyclotronTracker::visitCyclotron",
                                    "You are trying a local restart from a global h5 file!");
winklehner_d's avatar
-DW  
winklehner_d committed
475
        }
476 477
            // Else, if the user wants to save the restarted run in global frame,
            // make sure the previous h5 file was global too
winklehner_d's avatar
-DW  
winklehner_d committed
478 479
      } else {
        if (previousH5Local) {
480 481
                throw OpalException("Error in ParallelCyclotronTracker::visitCyclotron",
                                    "You are trying a global restart from a local h5 file!");
482
            }
483
        }
484

485
        // Adjust some of the reference variables from the h5 file
486 487
        referencePhi *= Physics::deg2rad;
        referencePsi *= Physics::deg2rad;
488
        referencePtot = bega;
489
        if(referenceTheta <= -180.0 || referenceTheta > 180.0) {
490
            throw OpalException("Error in ParallelCyclotronTracker::visitCyclotron",
491 492
                                "PHIINIT is out of [-180, 180)!");
        }
493 494
    }

495 496
    sinRefTheta_m = sin(referenceTheta * Physics::deg2rad);
    cosRefTheta_m = cos(referenceTheta * Physics::deg2rad);
497

498
    *gmsg << endl;
adelmann's avatar
adelmann committed
499
    *gmsg << "* Bunch global starting position:" << endl;
500 501
    *gmsg << "* RINIT = " << referenceR  << " [mm]" << endl;
    *gmsg << "* PHIINIT = " << referenceTheta << " [deg]" << endl;
502
    *gmsg << "* ZINIT = " << referenceZ << " [mm]" << endl;
503
    *gmsg << endl;
adelmann's avatar
adelmann committed
504
    *gmsg << "* Bunch global starting momenta:" << endl;
gsell's avatar
gsell committed
505 506
    *gmsg << "* Initial gamma = " << itsReference.getGamma() << endl;
    *gmsg << "* Initial beta = " << itsReference.getBeta() << endl;
507
    *gmsg << "* Reference total momentum (beta * gamma) = " << referencePtot * 1000.0 << " [MCU]" << endl;
508 509 510
    *gmsg << "* Reference azimuthal momentum (Pt) = " << referencePt * 1000.0 << " [MCU]" << endl;
    *gmsg << "* Reference radial momentum (Pr) = " << referencePr * 1000.0 << " [MCU]" << endl;
    *gmsg << "* Reference axial momentum (Pz) = " << referencePz * 1000.0 << " [MCU]" << endl;
511
    *gmsg << endl;
adelmann's avatar
adelmann committed
512

gsell's avatar
gsell committed
513
    double sym = elptr->getSymmetry();
snuverink_j's avatar
snuverink_j committed
514
    *gmsg << "* " << sym << "-fold field symmetry " << endl;
gsell's avatar
gsell committed
515

516 517 518
    // ckr: this just returned the default value as defined in Component.h
    // double rff = elptr->getRfFrequ();
    // *gmsg << "* Rf frequency= " << rff << " [MHz]" << endl;
gsell's avatar
gsell committed
519

520
    std::string fmfn = elptr->getFieldMapFN();
521
    *gmsg << "* Field map file name = " << fmfn << " " << endl;
gsell's avatar
gsell committed
522

523
    std::string type = elptr->getCyclotronType();
524
    *gmsg << "* Type of cyclotron = " << type << " " << endl;
525

526 527
    double rmin = elptr->getMinR();
    double rmax = elptr->getMaxR();
adelmann's avatar
adelmann committed
528
    *gmsg << "* Radial aperture = " << rmin << " ... " << rmax<<" [m] "<< endl;
529 530 531

    double zmin = elptr->getMinZ();
    double zmax = elptr->getMaxZ();
adelmann's avatar
adelmann committed
532
    *gmsg << "* Vertical aperture = " << zmin << " ... " << zmax<<" [m]"<< endl;
gsell's avatar
gsell committed
533 534

    double h = elptr->getCyclHarm();
535
    *gmsg << "* Number of trimcoils = " << elptr->getNumberOfTrimcoils() << endl;
536
    *gmsg << "* Harmonic number h = " << h << " " << endl;
537

gsell's avatar
gsell committed
538 539 540 541 542 543 544
    /**
     * To ease the initialise() function, set a integral parameter fieldflag internally.
     * Its value is  by the option "TYPE" of the element  "CYCLOTRON"
     * fieldflag = 1, readin PSI format measured field file (default)
     * fieldflag = 2, readin carbon cyclotron field file created by Jianjun Yang, TYPE=CARBONCYCL
     * fieldflag = 3, readin ANSYS format file for CYCIAE-100 created by Jianjun Yang, TYPE=CYCIAE
     * fieldflag = 4, readin AVFEQ format file for Riken cyclotrons
ext-rogers_c's avatar
ext-rogers_c committed
545
     * fieldflag = 5, readin FFA format file for MSU/FNAL FFA
gsell's avatar
gsell committed
546
     * fieldflag = 6, readin both median plane B field map and 3D E field map of RF cavity for compact cyclotron
547
     * fieldflag = 7, read in fields for Daniel's synchrocyclotron simulations
gsell's avatar
gsell committed
548
     */
549
    int fieldflag = elptr->getFieldFlag(type);
gsell's avatar
gsell committed
550

551
    // Read in cyclotron field maps (midplane + 3D fields if desired).
frey_m's avatar
frey_m committed
552
    elptr->initialise(itsBunch_m, fieldflag, elptr->getBScale());
gsell's avatar
gsell committed
553

snuverink_j's avatar
snuverink_j committed
554
    double BcParameter[8] = {};
555

556 557
    BcParameter[0] = 0.001 * elptr->getRmin();
    BcParameter[1] = 0.001 * elptr->getRmax();
gsell's avatar
gsell committed
558

559
    // Store inner radius and outer radius of cyclotron field map in the list
560
    buildupFieldList(BcParameter, ElementBase::CYCLOTRON, elptr);
gsell's avatar
gsell committed
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
}

/**
 * Not implemented and most probable never used
 *
 */
void ParallelCyclotronTracker::visitBeamBeam(const BeamBeam &) {
    *gmsg << "In BeamBeam tracker is missing " << endl;
}

/**
 *
 *
 * @param coll
 */
576
void ParallelCyclotronTracker::visitCCollimator(const CCollimator &coll) {
gsell's avatar
gsell committed
577

578
    *gmsg << "* --------- Collimator -----------------------------" << endl;
gsell's avatar
gsell committed
579

580
    CCollimator* elptr = dynamic_cast<CCollimator *>(coll.clone());
581
    myElements.push_back(elptr);
gsell's avatar
gsell committed
582

583
    double xstart = elptr->getXStart();
adelmann's avatar
adelmann committed
584
    *gmsg << "* Xstart= " << xstart << " [mm]" << endl;
gsell's avatar
gsell committed
585

586
    double xend = elptr->getXEnd();
adelmann's avatar
adelmann committed
587
    *gmsg << "* Xend= " << xend << " [mm]" << endl;
gsell's avatar
gsell committed
588

589
    double ystart = elptr->getYStart();
adelmann's avatar
adelmann committed
590
    *gmsg << "* Ystart= " << ystart << " [mm]" << endl;
gsell's avatar
gsell committed
591

592
    double yend = elptr->getYEnd();
593
    *gmsg << "* Yend= " << yend << " [mm]" << endl;
gsell's avatar
gsell committed
594

595
    double zstart = elptr->getZStart();
adelmann's avatar
adelmann committed
596
    *gmsg << "* Zstart= " << zstart << " [mm]" << endl;
597 598

    double zend = elptr->getZEnd();
599
    *gmsg << "* Zend= " << zend << " [mm]" << endl;
600

601
    double width = elptr->getWidth();
adelmann's avatar
adelmann committed
602
    *gmsg << "* Width= " << width << " [mm]" << endl;
gsell's avatar
gsell committed
603

frey_m's avatar
frey_m committed
604
    elptr->initialise(itsBunch_m);
gsell's avatar
gsell committed
605

snuverink_j's avatar
snuverink_j committed
606
    double BcParameter[8] = {};
607

608 609 610 611 612 613
    BcParameter[0] = 0.001 * xstart ;
    BcParameter[1] = 0.001 * xend;
    BcParameter[2] = 0.001 * ystart ;
    BcParameter[3] = 0.001 * yend;
    BcParameter[4] = 0.001 * width ;

614
    buildupFieldList(BcParameter, ElementBase::CCOLLIMATOR, elptr);
gsell's avatar
gsell committed
615 616 617 618 619 620 621 622 623 624 625 626
}

/**
 *
 *
 * @param corr
 */
void ParallelCyclotronTracker::visitCorrector(const Corrector &corr) {
    *gmsg << "In Corrector; L= " << corr.getElementLength() << endl;
    myElements.push_back(dynamic_cast<Corrector *>(corr.clone()));
}

adelmann's avatar
adelmann committed
627 628 629 630 631 632 633 634 635 636 637 638
/**
 *
 *
 * @param degrader
 */
void ParallelCyclotronTracker::visitDegrader(const Degrader &deg) {
    *gmsg << "In Degrader; L= " << deg.getElementLength() << endl;
    myElements.push_back(dynamic_cast<Degrader *>(deg.clone()));

}


gsell's avatar
gsell committed
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
/**
 *
 *
 * @param diag
 */
void ParallelCyclotronTracker::visitDiagnostic(const Diagnostic &diag) {
    *gmsg << "In Diagnostic; L= " << diag.getElementLength() << endl;
    myElements.push_back(dynamic_cast<Diagnostic *>(diag.clone()));
}

/**
 *
 *
 * @param drift
 */
void ParallelCyclotronTracker::visitDrift(const Drift &drift) {
    *gmsg << "In drift L= " << drift.getElementLength() << endl;
    myElements.push_back(dynamic_cast<Drift *>(drift.clone()));
}

659 660
/**
 *
661 662
 *
 *  @param
663 664 665 666 667
 */
void ParallelCyclotronTracker::visitFlexibleCollimator(const FlexibleCollimator &) {

}

gsell's avatar
gsell committed
668 669 670 671 672 673 674 675 676 677
/**
 *
 *
 * @param lamb
 */
void ParallelCyclotronTracker::visitLambertson(const Lambertson &lamb) {
    *gmsg << "In Lambertson; L= " << lamb.getElementLength() << endl;
    myElements.push_back(dynamic_cast<Lambertson *>(lamb.clone()));
}

678 679 680
void ParallelCyclotronTracker::visitOffset(const Offset & off) {
    if (opalRing_m == NULL)
        throw OpalException(
681 682
                            "ParallelCylcotronTracker::visitOffset",
                            "Attempt to place an offset when Ring not defined");
683 684
    Offset* offNonConst = const_cast<Offset*>(&off);
    offNonConst->updateGeometry(opalRing_m->getNextPosition(),
685
                                opalRing_m->getNextNormal());
686 687 688
    opalRing_m->appendElement(off);
}

gsell's avatar
gsell committed
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
/**
 *
 *
 * @param marker
 */
void ParallelCyclotronTracker::visitMarker(const Marker &marker) {
    //   *gmsg << "In Marker; L= " << marker.getElementLength() << endl;
    myElements.push_back(dynamic_cast<Marker *>(marker.clone()));
    // Do nothing.
}

/**
 *
 *
 * @param corr
 */
void ParallelCyclotronTracker::visitMonitor(const Monitor &corr) {
    //   *gmsg << "In Monitor; L= " << corr.getElementLength() << endl;
    myElements.push_back(dynamic_cast<Monitor *>(corr.clone()));
    //   applyDrift(flip_s * corr.getElementLength());
}

/**
 *
 *
 * @param mult
 */
void ParallelCyclotronTracker::visitMultipole(const Multipole &mult) {
    *gmsg << "In Multipole; L= " << mult.getElementLength() << " however the element is missing " << endl;
    myElements.push_back(dynamic_cast<Multipole *>(mult.clone()));
}

ext-rogers_c's avatar
ext-rogers_c committed
721 722 723 724 725 726 727
/**
 *
 *
 * @param multT
 */
void ParallelCyclotronTracker::visitMultipoleT(const MultipoleT &multT) {
    *gmsg << "Adding MultipoleT" << endl;
728
    if (opalRing_m != NULL) {
ext-rogers_c's avatar
ext-rogers_c committed
729
        opalRing_m->appendElement(multT);
730
    } else {
ext-rogers_c's avatar
ext-rogers_c committed
731 732
        throw OpalException("ParallelCyclotronTracker::visitMultipoleT",
                            "Need to define a RINGDEFINITION to use MultipoleT element");
733
    }
ext-rogers_c's avatar
ext-rogers_c committed
734 735 736
    myElements.push_back(dynamic_cast<MultipoleT *>(multT.clone()));
}

737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
/**
 *
 *
 * @param multTstraight
 */
void ParallelCyclotronTracker::visitMultipoleTStraight(const MultipoleTStraight &multTstraight) {
    *gmsg << "Adding MultipoleTStraight" << endl;
    if (opalRing_m != NULL) {
        opalRing_m->appendElement(multTstraight);
    } else {
        throw OpalException("ParallelCyclotronTracker::visitMultipoleTStraight",
                            "Need to define a RINGDEFINITION to use MultipoleTStraight element");
    }
    myElements.push_back(dynamic_cast<MultipoleTStraight *>(multTstraight.clone()));
}

/**
 *
 *
 * @param multTccurv
 */
void ParallelCyclotronTracker::visitMultipoleTCurvedConstRadius(const MultipoleTCurvedConstRadius &multTccurv) {
    *gmsg << "Adding MultipoleTCurvedConstRadius" << endl;
    if (opalRing_m != NULL) {
        opalRing_m->appendElement(multTccurv);
    } else {
        throw OpalException("ParallelCyclotronTracker::visitMultipoleTCurvedConstRadius",
                            "Need to define a RINGDEFINITION to use MultipoleTCurvedConstRadius element");
    }
    myElements.push_back(dynamic_cast<MultipoleTCurvedConstRadius *>(multTccurv.clone()));
}

/**
 *
 *
 * @param multTvcurv
 */
void ParallelCyclotronTracker::visitMultipoleTCurvedVarRadius(const MultipoleTCurvedVarRadius &multTvcurv) {
    *gmsg << "Adding MultipoleTCurvedVarRadius" << endl;
    if (opalRing_m != NULL) {
        opalRing_m->appendElement(multTvcurv);
    } else {
        throw OpalException("ParallelCyclotronTracker::visitMultipoleTCurvedVarRadius",
                            "Need to define a RINGDEFINITION to use MultipoleTCurvedVarRadius element");
    }
    myElements.push_back(dynamic_cast<MultipoleTCurvedVarRadius *>(multTvcurv.clone()));
}

gsell's avatar
gsell committed
785 786 787 788 789 790
/**
 *
 *
 * @param prob
 */
void ParallelCyclotronTracker::visitProbe(const Probe &prob) {
791
    *gmsg << "* -----------  Probe -------------------------------" << endl;
792 793
    Probe *elptr = dynamic_cast<Probe *>(prob.clone());
    myElements.push_back(elptr);
gsell's avatar
gsell committed
794

795
    double xstart = elptr->getXStart();
796
    *gmsg << "XStart= " << xstart << " [mm]" << endl;
gsell's avatar
gsell committed
797

798
    double xend = elptr->getXEnd();
799
    *gmsg << "XEnd= " << xend << " [mm]" << endl;
gsell's avatar
gsell committed
800

801
    double ystart = elptr->getYStart();
802
    *gmsg << "YStart= " << ystart << " [mm]" << endl;
gsell's avatar
gsell committed
803

804
    double yend = elptr->getYEnd();
805
    *gmsg << "YEnd= " << yend << " [mm]" << endl;
gsell's avatar
gsell committed
806 807

    // initialise, do nothing
frey_m's avatar
frey_m committed
808
    elptr->initialise(itsBunch_m);
gsell's avatar
gsell committed
809

snuverink_j's avatar
snuverink_j committed
810
    double BcParameter[8] = {};
811

812 813 814 815
    BcParameter[0] = 0.001 * xstart ;
    BcParameter[1] = 0.001 * xend;
    BcParameter[2] = 0.001 * ystart ;
    BcParameter[3] = 0.001 * yend;
816
    BcParameter[4] = 0.001 ; // width
gsell's avatar
gsell committed
817 818

    // store probe parameters in the list
819
    buildupFieldList(BcParameter, ElementBase::PROBE, elptr);
gsell's avatar
gsell committed
820 821 822 823 824 825 826 827 828 829 830 831
}

/**
 *
 *
 * @param bend
 */
void ParallelCyclotronTracker::visitRBend(const RBend &bend) {
    *gmsg << "In RBend; L= " << bend.getElementLength() << " however the element is missing " << endl;
    myElements.push_back(dynamic_cast<RBend *>(bend.clone()));
}

832 833 834 835 836 837
void ParallelCyclotronTracker::visitSBend3D(const SBend3D &bend) {
    *gmsg << "Adding SBend3D" << endl;
    if (opalRing_m != NULL)
        opalRing_m->appendElement(bend);
    else
        throw OpalException("ParallelCyclotronTracker::visitSBend3D",
838
                            "Need to define a RINGDEFINITION to use SBend3D element");
839 840
}

ext-rogers_c's avatar
ext-rogers_c committed
841 842
void ParallelCyclotronTracker::visitScalingFFAMagnet(const ScalingFFAMagnet &bend) {
    *gmsg << "Adding ScalingFFAMagnet" << endl;
ext-rogers_c's avatar
ext-rogers_c committed
843
    if (opalRing_m != NULL) {
844
        opalRing_m->appendElement(bend);
ext-rogers_c's avatar
ext-rogers_c committed
845
    } else {
ext-rogers_c's avatar
ext-rogers_c committed
846 847
        throw OpalException("ParallelCyclotronTracker::visitScalingFFAMagnet",
                            "Need to define a RINGDEFINITION to use ScalingFFAMagnet element");
ext-rogers_c's avatar
ext-rogers_c committed
848
    }
849 850
}

851 852 853 854 855 856
void ParallelCyclotronTracker::visitVariableRFCavity(const VariableRFCavity &cav) {
    *gmsg << "Adding Variable RF Cavity" << endl;
    if (opalRing_m != NULL)
        opalRing_m->appendElement(cav);
    else
        throw OpalException("ParallelCyclotronTracker::visitVariableRFCavity",
857
                            "Need to define a RINGDEFINITION to use VariableRFCavity element");
858 859 860 861 862 863 864 865 866 867
}

void ParallelCyclotronTracker::visitVariableRFCavityFringeField
                                  (const VariableRFCavityFringeField &cav) {
    *gmsg << "Adding Variable RF Cavity with Fringe Field" << endl;
    if (opalRing_m != NULL)
        opalRing_m->appendElement(cav);
    else
        throw OpalException("ParallelCyclotronTracker::visitVariableRFCavityFringeField",
                            "Need to define a RINGDEFINITION to use VariableRFCavity element");
868 869
}

gsell's avatar
gsell committed
870 871 872 873 874 875 876 877
/**
 *
 *
 * @param as
 */
void ParallelCyclotronTracker::visitRFCavity(const RFCavity &as) {

    *gmsg << "* --------- RFCavity ------------------------------" << endl;
878

879 880
    RFCavity *elptr = dynamic_cast<RFCavity *>(as.clone());
    myElements.push_back(elptr);
gsell's avatar
gsell committed
881 882 883 884 885 886 887

    if((elptr->getComponentType() != "SINGLEGAP") && (elptr->getComponentType() != "DOUBLEGAP")) {
        *gmsg << (elptr->getComponentType()) << endl;
        throw OpalException("ParallelCyclotronTracker::visitRFCavity",
                            "The ParallelCyclotronTracker can only play with cyclotron type RF system currently ...");
    }

888
    double rmin = elptr->getRmin();
gsell's avatar
gsell committed
889 890
    *gmsg << "* Minimal radius of cavity= " << rmin << " [mm]" << endl;

891
    double rmax = elptr->getRmax();
gsell's avatar
gsell committed
892 893
    *gmsg << "* Maximal radius of cavity= " << rmax << " [mm]" << endl;

894
    double rff = elptr->getCycFrequency();
gsell's avatar
gsell committed
895 896
    *gmsg << "* RF frequency (2*pi*f)= " << rff << " [rad/s]" << endl;

897
    std::string fmfn = elptr->getFieldMapFN();
gsell's avatar
gsell committed
898
    *gmsg << "* RF Field map file name= " << fmfn << endl;
899

900
    double angle = elptr->getAzimuth();
gsell's avatar
gsell committed
901 902
    *gmsg << "* Cavity azimuth position= " << angle << " [deg] " << endl;

903
    double gap = elptr->getGapWidth();
gsell's avatar
gsell committed
904 905
    *gmsg << "* Cavity gap width= " << gap << " [mm] " << endl;

906
    double pdis = elptr->getPerpenDistance();
gsell's avatar
gsell committed
907 908
    *gmsg << "* Cavity Shift distance= " << pdis << " [mm] " << endl;

909
    double phi0 = elptr->getPhi0();
gsell's avatar
gsell committed
910 911
    *gmsg << "* Initial RF phase (t=0)= " << phi0 << " [deg] " << endl;

912 913 914
    /*
      Setup time dependence and in case of no
      timedependence use a polynom with  a_0 = 1 and a_k = 0, k = 1,2,3.
915
    */
916

917 918 919 920
    std::shared_ptr<AbstractTimeDependence> freq_atd = nullptr;
    std::shared_ptr<AbstractTimeDependence> ampl_atd = nullptr;
    std::shared_ptr<AbstractTimeDependence> phase_atd = nullptr;

921
    dvector_t  unityVec;
922 923 924 925
    unityVec.push_back(1.);
    unityVec.push_back(0.);
    unityVec.push_back(0.);
    unityVec.push_back(0.);
926

927
    if (elptr->getFrequencyModelName() != "") {
928 929
        freq_atd = AbstractTimeDependence::getTimeDependence(elptr->getFrequencyModelName());
        *gmsg << "* Variable frequency RF Model name " << elptr->getFrequencyModelName() << endl;
930
    }
931 932
    else
        freq_atd = std::shared_ptr<AbstractTimeDependence>(new PolynomialTimeDependence(unityVec));
933 934

    if (elptr->getAmplitudeModelName() != "") {
935 936
        ampl_atd = AbstractTimeDependence::getTimeDependence(elptr->getAmplitudeModelName());
        *gmsg << "* Variable amplitude RF Model name " << elptr->getAmplitudeModelName() << endl;
937
    }