ParallelCyclotronTracker.cpp 226 KB
Newer Older
gsell's avatar
gsell committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// ------------------------------------------------------------------------
// $RCSfile: ParallelCyclotronTracker.cpp,v $
// ------------------------------------------------------------------------
// $Revision: 1.1 $initialLocalNum_m
// ------------------------------------------------------------------------
// Copyright: see Copyright.readme
// ------------------------------------------------------------------------
//
// Class: ParallelCyclotronTracker
//   The class for tracking particles with 3D space charge in Cyclotrons and FFAG's
//
// ------------------------------------------------------------------------
//
// $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/Ctunes.hpp>
kraus's avatar
kraus committed
20
#include "Algorithms/ParallelCyclotronTracker.h"
21 22
#include "Algorithms/PolynomialTimeDependence.h"
#include "Elements/OpalPolynomialTimeDependence.h"
gsell's avatar
gsell committed
23 24 25 26
#include <cfloat>
#include <iostream>
#include <fstream>
#include <vector>
27
#include "AbstractObjects/OpalData.h"
gsell's avatar
gsell committed
28 29 30 31

#include "AbsBeamline/Collimator.h"
#include "AbsBeamline/Corrector.h"
#include "AbsBeamline/Cyclotron.h"
adelmann's avatar
adelmann committed
32
#include "AbsBeamline/Degrader.h"
gsell's avatar
gsell committed
33 34 35 36
#include "AbsBeamline/Diagnostic.h"
#include "AbsBeamline/Drift.h"
#include "AbsBeamline/ElementBase.h"
#include "AbsBeamline/Lambertson.h"
37
#include "AbsBeamline/Offset.h"
gsell's avatar
gsell committed
38 39 40 41 42 43 44 45
#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/RFQuadrupole.h"
#include "AbsBeamline/SBend.h"
46
#include "AbsBeamline/SBend3D.h"
gsell's avatar
gsell committed
47 48 49 50 51
#include "AbsBeamline/Separator.h"
#include "AbsBeamline/Septum.h"
#include "AbsBeamline/Solenoid.h"
#include "AbsBeamline/CyclotronValley.h"
#include "AbsBeamline/Stripper.h"
52
#include "AbsBeamline/VariableRFCavity.h"
53

54 55
#include "AbstractObjects/Element.h"

56
#include "Elements/OpalBeamline.h"
kraus's avatar
kraus committed
57
#include "AbsBeamline/Ring.h"
gsell's avatar
gsell committed
58 59 60

#include "BeamlineGeometry/Euclid3D.h"
#include "BeamlineGeometry/PlanarArcGeometry.h"
Jianjun Yang's avatar
Jianjun Yang committed
61
#include "BeamlineGeometry/RBendGeometry.h"
gsell's avatar
gsell committed
62 63 64 65 66 67 68 69 70 71 72 73
#include "Beamlines/Beamline.h"

#include "Fields/BMultipoleField.h"
#include "FixedAlgebra/FTps.h"
#include "FixedAlgebra/FTpsMath.h"
#include "FixedAlgebra/FVps.h"

#include "Physics/Physics.h"

#include "Utilities/NumToStr.h"
#include "Utilities/OpalException.h"

74
#include "Structure/H5PartWrapperForPC.h"
75
#include "Structure/BoundaryGeometry.h"
76
#include "Utilities/Options.h"
gsell's avatar
gsell committed
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94

#include "Ctunes.h"
#include <cassert>

#include <hdf5.h>
#include "H5hut.h"

class Beamline;
class PartData;
using Physics::c;
using Physics::m_p; // GeV
using Physics::PMASS;
using Physics::PCHARGE;
using Physics::pi;
using Physics::q_e;

const double c_mmtns = c * 1.0e-6; // m/s --> mm/ns
const double mass_coeff = 1.0e18 * q_e / c / c; // from GeV/c^2 to basic unit: GV*C*s^2/m^2
95
const double PIOVER180 = pi / 180.0;
96

97 98 99
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
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118

#define PSdim 6

extern Inform *gmsg;

// typedef FVector<double, PSdim> Vector;

/**
 * Constructor ParallelCyclotronTracker
 *
 * @param beamline
 * @param reference
 * @param revBeam
 * @param revTrack
 */
ParallelCyclotronTracker::ParallelCyclotronTracker(const Beamline &beamline,
        const PartData &reference,
        bool revBeam, bool revTrack):
    Tracker(beamline, reference, revBeam, revTrack),
119
    eta_m(0.01),
gsell's avatar
gsell committed
120 121
    myNode_m(Ippl::myNode()),
    initialLocalNum_m(0),
122
    initialTotalNum_m(0),
123 124
    opalRing_m(NULL),
    lastDumpedStep_m(0) {
gsell's avatar
gsell committed
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
    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,
                                                   PartBunch &bunch,
                                                   DataSink &ds,
                                                   const PartData &reference,
                                                   bool revBeam, bool revTrack,
145
                                                   int maxSTEPS, int timeIntegrator):
gsell's avatar
gsell committed
146 147 148
    Tracker(beamline, reference, revBeam, revTrack),
    maxSteps_m(maxSTEPS),
    timeIntegrator_m(timeIntegrator),
149
    eta_m(0.01),
gsell's avatar
gsell committed
150 151
    myNode_m(Ippl::myNode()),
    initialLocalNum_m(bunch.getLocalNum()),
152
    initialTotalNum_m(bunch.getTotalNum()),
153
    opalRing_m(NULL),
154
    lastDumpedStep_m(0) {
gsell's avatar
gsell committed
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
    itsBeamline = dynamic_cast<Beamline *>(beamline.clone());
    itsBunch = &bunch;
    itsDataSink = &ds;
    //  scaleFactor_m = itsBunch->getdT() * c;
    scaleFactor_m = 1;
    multiBunchMode_m = 0;

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

/**
 * Destructor ParallelCyclotronTracker
 *
 */
ParallelCyclotronTracker::~ParallelCyclotronTracker() {
173
    for(std::list<Component *>::iterator compindex = myElements.begin(); compindex != myElements.end(); compindex++) {
gsell's avatar
gsell committed
174 175 176 177 178 179
        delete(*compindex);
    }
    for(beamline_list::iterator fdindex = FieldDimensions.begin(); fdindex != FieldDimensions.end(); fdindex++) {
        delete(*fdindex);
    }
    delete itsBeamline;
180 181 182
    if (opalRing_m != NULL) {
        // delete opalRing_m;
    }
gsell's avatar
gsell committed
183 184
}

185 186 187 188 189 190
/**
 * AAA
 *
 * @param none
 */
void ParallelCyclotronTracker::initializeBoundaryGeometry() {
191
  for(std::list<Component *>::iterator compindex = myElements.begin(); compindex != myElements.end(); compindex++) {
192
    bgf_m = dynamic_cast<ElementBase *>(*compindex)->getBoundaryGeometry();
193
    if(!bgf_m)
194 195 196 197
      continue;
    else
      break;
  }
adelmann's avatar
adelmann committed
198
  if (bgf_m) {
199
    itsDataSink->writeGeomToVtk(*bgf_m, std::string("data/testGeometry-00000.vtk"));
adelmann's avatar
adelmann committed
200 201 202
    OpalData::getInstance()->setGlobalGeometry(bgf_m);
    *gmsg << "* Boundary geometry initialized " << endl;
  }
203
}
204

205 206 207 208 209 210 211 212 213
/**
 *
 *
 * @param fn Base file name
 */
void ParallelCyclotronTracker::bgf_main_collision_test() {
  if(!bgf_m) return;

  Inform msg("bgf_main_collision_test ");
214 215

  /**
216 217 218
   *Here we check if a particles is outside the domain, flag it for deletion
   */

gsell's avatar
gsell committed
219
  Vector_t intecoords = 0.0;
220 221 222 223 224

  // This has to match the dT in the rk4 pusher! -DW
  //double dtime = 0.5 * itsBunch->getdT();  // Old
  double dtime = itsBunch->getdT() * getHarmonicNumber();  // New

225
  int triId = 0;
226 227
  size_t Nimpact = 0;
  for(size_t i = 0; i < itsBunch->getLocalNum(); i++) {
228
    int res = bgf_m->PartInside(itsBunch->R[i]*1.0e-3, itsBunch->P[i], dtime, itsBunch->PType[i], itsBunch->Q[i], intecoords, triId);
229
    if(res >= 0) {
230 231
      itsBunch->Bin[i] = -1;
      Nimpact++;
232
    }
233 234 235 236
  }
}


gsell's avatar
gsell committed
237 238 239 240 241
/**
 *
 *
 * @param fn Base file name
 */
242
void ParallelCyclotronTracker::openFiles(std::string SfileName) {
gsell's avatar
gsell committed
243

244
    std::string  SfileName2 = SfileName + std::string("-Angle0.dat");
gsell's avatar
gsell committed
245 246

    outfTheta0_m.precision(8);
247
    outfTheta0_m.setf(std::ios::scientific, std::ios::floatfield);
gsell's avatar
gsell committed
248
    outfTheta0_m.open(SfileName2.c_str());
249
    outfTheta0_m << "#  r [mm]      beta_r*gamma       theta [mm]      beta_theta*gamma        z [mm]          beta_z*gamma" << std::endl;
gsell's avatar
gsell committed
250

251
    SfileName2 = SfileName + std::string("-Angle1.dat");
gsell's avatar
gsell committed
252
    outfTheta1_m.precision(8);
253
    outfTheta1_m.setf(std::ios::scientific, std::ios::floatfield);
gsell's avatar
gsell committed
254
    outfTheta1_m.open(SfileName2.c_str());
255
    outfTheta1_m << "#  r [mm]      beta_r*gamma       theta [mm]      beta_theta*gamma        z [mm]          beta_z*gamma"  << std::endl;
gsell's avatar
gsell committed
256

257
    SfileName2 = SfileName + std::string("-Angle2.dat");
gsell's avatar
gsell committed
258
    outfTheta2_m.precision(8);
259
    outfTheta2_m.setf(std::ios::scientific, std::ios::floatfield);
gsell's avatar
gsell committed
260
    outfTheta2_m.open(SfileName2.c_str());
261
    outfTheta2_m << "#  r [mm]      beta_r*gamma       theta [mm]      beta_theta*gamma        z [mm]          beta_z*gamma"  << std::endl;
gsell's avatar
gsell committed
262 263 264

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

265
    SfileName2 = SfileName + std::string("-afterEachTurn.dat");
gsell's avatar
gsell committed
266 267

    outfThetaEachTurn_m.precision(8);
268
    outfThetaEachTurn_m.setf(std::ios::scientific, std::ios::floatfield);
gsell's avatar
gsell committed
269 270

    outfThetaEachTurn_m.open(SfileName2.c_str());
271
    outfTheta2_m << "#  r [mm]      beta_r*gamma       theta [mm]      beta_theta*gamma        z [mm]          beta_z*gamma"  << std::endl;
gsell's avatar
gsell committed
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
}

/**
 * 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();
}

287
/**
288 289 290
 *
 * @param ring
 */
kraus's avatar
kraus committed
291
void ParallelCyclotronTracker::visitRing(const Ring &ring) {
Daniel Winklehner's avatar
Daniel Winklehner committed
292

293
    *gmsg << "* ----------------------------- Adding Ring ------------------------------ *" << endl;
Daniel Winklehner's avatar
Daniel Winklehner committed
294 295

    if (opalRing_m != NULL)
296
        delete opalRing_m;
Daniel Winklehner's avatar
Daniel Winklehner committed
297

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

300
    myElements.push_back(opalRing_m);
Daniel Winklehner's avatar
Daniel Winklehner committed
301

302 303 304 305 306
    opalRing_m->initialise(itsBunch);

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

308
    if(referenceTheta <= -180.0 || referenceTheta > 180.0) {
kraus's avatar
kraus committed
309
        throw OpalException("Error in ParallelCyclotronTracker::visitRing",
310 311
                            "PHIINIT is out of [-180, 180)!");
    }
Daniel Winklehner's avatar
Daniel Winklehner committed
312 313

    referenceZ = 0.0;
314
    referencePz = 0.0;
Daniel Winklehner's avatar
Daniel Winklehner committed
315 316 317 318

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

319 320
    if(referencePtot < 0.0)
        referencePt *= -1.0;
Daniel Winklehner's avatar
Daniel Winklehner committed
321

322 323
    sinRefTheta_m = sin(referenceTheta * PIOVER180);
    cosRefTheta_m = cos(referenceTheta * PIOVER180);
gsell's avatar
gsell committed
324

325
    double BcParameter[8];
Daniel Winklehner's avatar
Daniel Winklehner committed
326

327
    for(int i = 0; i < 8; i++)
Daniel Winklehner's avatar
Daniel Winklehner committed
328 329
        BcParameter[i] = 0.0;

330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
    buildupFieldList(BcParameter, "OPALRING", opalRing_m);

    // 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
347 348 349 350 351 352 353 354

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

355
    *gmsg << "* -------------------------- Adding Cyclotron ---------------------------- *" << endl;
gsell's avatar
gsell committed
356

357 358
    Cyclotron *elptr = dynamic_cast<Cyclotron *>(cycl.clone());
    myElements.push_back(elptr);
359

360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
    // Is this a Spiral Inflector Simulation? If yes, we'll give the user some 
    // useful information
    spiral_flag = elptr->getSpiralFlag();

    if(spiral_flag) {

        *gmsg << endl << "* This is a Spiral Inflector Simulation! This means the following:" << endl;
        *gmsg         << "* 1.) It is up to the user to provide appropriate geometry, electric and magnetic fields!" << endl;        
        *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;
        *gmsg         << "* 2.) It is strongly recommended to use the SAAMG fieldsolver," << endl; 
        *gmsg         << "*     FFT does not give the correct results (boundaty conditions are missing)." << endl;
        *gmsg         << "* 3.) The whole geometry will be meshed and used for the fieldsolve." << endl;
        *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; 
        *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;

    }

382
    // Fresh run (no restart):
383
    if(!OpalData::getInstance()->inRestartRun()) {
384

385 386 387 388 389
        // Get reference values from cyclotron element
        referenceR     = elptr->getRinit();
        referenceTheta = elptr->getPHIinit();
        referenceZ     = elptr->getZinit();
        referencePr    = elptr->getPRinit();
390 391
        referencePz    = elptr->getPZinit();

392
        if(referenceTheta <= -180.0 || referenceTheta > 180.0) {
393 394
            throw OpalException("Error in ParallelCyclotronTracker::visitCyclotron",
                                "PHIINIT is out of [-180, 180)!");
395 396 397 398 399
        }

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

        // Calculate reference azimuthal (tangential) momentum from total-, z- and radial momentum:
400 401
        float insqrt = referencePtot * referencePtot - \
                       referencePr * referencePr - referencePz * referencePz;
402 403 404 405 406 407 408 409 410

        if(insqrt < 0) {

            if(insqrt > -1.0e-10) {

	        referencePt = 0.0;

            } else {

411
	        throw OpalException("Error in ParallelCyclotronTracker::visitCyclotron",
412
                                    "Pt imaginary!");
413 414 415 416 417 418 419
            }

        } else {

            referencePt = sqrt(insqrt);
        }

420
        if(referencePtot < 0.0)
Daniel Winklehner's avatar
Daniel Winklehner committed
421
            referencePt *= -1.0;
422 423 424 425 426
        // End calculate referencePt

    // Restart a run:
    } else {

427
        // If the user wants to save the restarted run in local frame,
428 429
        // make sure the previous h5 file was local too
        if (Options::psDumpLocalFrame) {
430

431
	    if (!previousH5Local) {
432

433 434
                throw OpalException("Error in ParallelCyclotronTracker::visitCyclotron",
                                    "You are trying a local restart from a global h5 file!");
435 436
	    }
	// Else, if the user wants to save the restarted run in global frame,
437 438
        // make sure the previous h5 file was global too
        } else {
439

440
	    if (previousH5Local) {
441

442 443
                throw OpalException("Error in ParallelCyclotronTracker::visitCyclotron",
                                    "You are trying a global restart from a local h5 file!");
444
            }
445
        }
446

447 448 449 450
        // Adjust some of the reference variables from the h5 file
        referencePhi *= PIOVER180;
        referencePsi *= PIOVER180;
        referencePtot = bega;
451 452 453

        if(referenceTheta <= -180.0 || referenceTheta > 180.0) {

454
            throw OpalException("Error in ParallelCyclotronTracker::visitCyclotron",
455 456
                                "PHIINIT is out of [-180, 180)!");
        }
457 458
    }

459
    sinRefTheta_m = sin(referenceTheta * PIOVER180);
460 461
    cosRefTheta_m = cos(referenceTheta * PIOVER180);

462
    *gmsg << endl;
adelmann's avatar
adelmann committed
463
    *gmsg << "* Bunch global starting position:" << endl;
464 465
    *gmsg << "* RINIT = " << referenceR  << " [mm]" << endl;
    *gmsg << "* PHIINIT = " << referenceTheta << " [deg]" << endl;
466
    *gmsg << "* ZINIT = " << referenceZ << " [mm]" << endl;
467
    *gmsg << endl;
adelmann's avatar
adelmann committed
468
    *gmsg << "* Bunch global starting momenta:" << endl;
gsell's avatar
gsell committed
469 470
    *gmsg << "* Initial gamma = " << itsReference.getGamma() << endl;
    *gmsg << "* Initial beta = " << itsReference.getBeta() << endl;
471
    *gmsg << "* Reference total momentum (beta * gamma) = " << referencePtot * 1000.0 << " [MCU]" << endl;
472 473 474
    *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;
475
    *gmsg << endl;
adelmann's avatar
adelmann committed
476

gsell's avatar
gsell committed
477
    double sym = elptr->getSymmetry();
478
    *gmsg << "* " << sym << "-fold field symmerty " << endl;
gsell's avatar
gsell committed
479

480 481 482
    // 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
483

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

487
    std::string type = elptr->getCyclotronType();
488
    *gmsg << "* Type of cyclotron = " << type << " " << endl;
489

490 491
    double rmin = elptr->getMinR();
    double rmax = elptr->getMaxR();
492
    *gmsg << "* Radial aperture = " << rmin << " ... " << rmax<<" [mm] "<< endl;
493 494 495

    double zmin = elptr->getMinZ();
    double zmax = elptr->getMaxZ();
496
    *gmsg << "* Vertical aperture = " << zmin << " ... " << zmax<<" [mm]"<< endl;
gsell's avatar
gsell committed
497

498
    /**
499
    bool Sflag = elptr->getSuperpose();
500
    std::string flagsuperposed;
501 502 503 504
    if (Sflag)
      flagsuperposed="yes";
    else
      flagsuperposed="no";
505
    *gmsg << "* Electric field maps are superposed? " << flagsuperposed << " " << endl;
506
    */
507

gsell's avatar
gsell committed
508
    double h = elptr->getCyclHarm();
509
    *gmsg << "* Number of trimcoils = " << elptr->getNumberOfTrimcoils() << endl;
510
    *gmsg << "* Harmonic number h = " << h << " " << endl;
511
    /**
adelmann's avatar
adelmann committed
512
    if (elptr->getSuperpose())
513
        *gmsg << "* Fields are superposed " << endl;
514
    */
adelmann's avatar
adelmann committed
515

gsell's avatar
gsell committed
516 517 518 519 520 521 522 523 524 525 526
    /**
     * 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
     * fieldflag = 5, readin FFAG format file for MSU/FNAL FFAG
     * fieldflag = 6, readin both median plane B field map and 3D E field map of RF cavity for compact cyclotron
     */
    int  fieldflag;
527
    if(type == std::string("CARBONCYCL")) {
gsell's avatar
gsell committed
528
        fieldflag = 2;
529
    } else if(type == std::string("CYCIAE")) {
gsell's avatar
gsell committed
530
        fieldflag = 3;
531
    } else if(type == std::string("AVFEQ")) {
gsell's avatar
gsell committed
532
        fieldflag = 4;
533
    } else if(type == std::string("FFAG")) {
gsell's avatar
gsell committed
534
        fieldflag = 5;
535
    } else if(type == std::string("BANDRF")) {
gsell's avatar
gsell committed
536
        fieldflag = 6;
537 538
    } else if(type == std::string("SYNCHROCYCLOTRON")) {
	fieldflag = 7;
539
    } else //(type == "RING")
gsell's avatar
gsell committed
540 541 542 543
        fieldflag = 1;

    // read field map on the  middle plane of cyclotron.
    // currently scalefactor is set to 1.0
544
    // TEMP changed 1.0 to getBScale() to test if we can scale the midplane field -DW
545
    elptr->initialise(itsBunch, fieldflag, elptr->getBScale());
gsell's avatar
gsell committed
546 547

    double BcParameter[8];
548

549
    for(int i = 0; i < 8; i++)
adelmann's avatar
adelmann committed
550
      BcParameter[i] = 0.0;
551

gsell's avatar
gsell committed
552 553 554
    BcParameter[0] = elptr->getRmin();
    BcParameter[1] = elptr->getRmax();

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

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

/**
 *
 *
 * @param coll
 */
void ParallelCyclotronTracker::visitCollimator(const Collimator &coll) {

574
    *gmsg << "* --------- Collimator -----------------------------" << endl;
gsell's avatar
gsell committed
575

576 577
    Collimator* elptr = dynamic_cast<Collimator *>(coll.clone());
    myElements.push_back(elptr);
gsell's avatar
gsell committed
578

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

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

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

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

591
    double zstart = elptr->getZStart();
adelmann's avatar
adelmann committed
592
    *gmsg << "* Zstart= " << zstart << " [mm]" << endl;
593 594

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

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

    elptr->initialise(itsBunch, 1.0);

    double BcParameter[8];
    for(int i = 0; i < 8; i++)
        BcParameter[i] = 0.0;
605
    std::string ElementType = "CCOLLIMATOR";
606 607 608 609
    BcParameter[0] = xstart ;
    BcParameter[1] = xend;
    BcParameter[2] = ystart ;
    BcParameter[3] = yend;
gsell's avatar
gsell committed
610 611 612 613 614 615 616 617 618 619 620 621 622 623
    BcParameter[4] = width ;
    buildupFieldList(BcParameter, ElementType, elptr);
}

/**
 *
 *
 * @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
624 625 626 627 628 629 630 631 632 633 634 635
/**
 *
 *
 * @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
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
/**
 *
 *
 * @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()));
}

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

666 667 668 669
void ParallelCyclotronTracker::visitOffset(const Offset & off) {
    if (opalRing_m == NULL)
        throw OpalException(
                        "ParallelCylcotronTracker::visitOffset",
kraus's avatar
kraus committed
670
                        "Attempt to place an offset when Ring not defined");
671 672 673 674 675 676
    Offset* offNonConst = const_cast<Offset*>(&off);
    offNonConst->updateGeometry(opalRing_m->getNextPosition(),
                       opalRing_m->getNextNormal());
    opalRing_m->appendElement(off);
}

gsell's avatar
gsell committed
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
/**
 *
 *
 * @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());
}

699

gsell's avatar
gsell committed
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
/**
 *
 *
 * @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()));
}

/**
 *
 *
 * @param prob
 */
void ParallelCyclotronTracker::visitProbe(const Probe &prob) {
716
    *gmsg << "* -----------  Probe -------------------------------" << endl;
717 718
    Probe *elptr = dynamic_cast<Probe *>(prob.clone());
    myElements.push_back(elptr);
gsell's avatar
gsell committed
719

720
    double xstart = elptr->getXstart();
721
    *gmsg << "XStart= " << xstart << " [mm]" << endl;
gsell's avatar
gsell committed
722

723
    double xend = elptr->getXend();
724
    *gmsg << "XEnd= " << xend << " [mm]" << endl;
gsell's avatar
gsell committed
725

726
    double ystart = elptr->getYstart();
727
    *gmsg << "YStart= " << ystart << " [mm]" << endl;
gsell's avatar
gsell committed
728

729
    double yend = elptr->getYend();
730
    *gmsg << "YEnd= " << yend << " [mm]" << endl;
gsell's avatar
gsell committed
731

732
    double width = elptr->getWidth();
733
    *gmsg << "Width= " << width << " [mm]" << endl;
gsell's avatar
gsell committed
734 735 736 737 738 739 740 741


    // initialise, do nothing
    elptr->initialise(itsBunch, 1.0);

    double BcParameter[8];
    for(int i = 0; i < 8; i++)
        BcParameter[i] = 0.0;
742
    std::string ElementType = "PROBE";
gsell's avatar
gsell committed
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
    BcParameter[0] = xstart ;
    BcParameter[1] = xend;
    BcParameter[2] = ystart ;
    BcParameter[3] = yend;
    BcParameter[4] = width ;

    // store probe parameters in the list
    buildupFieldList(BcParameter, ElementType, elptr);
}

/**
 *
 *
 * @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()));
}

763 764 765 766 767 768 769 770 771
void ParallelCyclotronTracker::visitSBend3D(const SBend3D &bend) {
    *gmsg << "Adding SBend3D" << endl;
    if (opalRing_m != NULL)
        opalRing_m->appendElement(bend);
    else
        throw OpalException("ParallelCyclotronTracker::visitSBend3D",
                      "Need to define a RINGDEFINITION to use SBend3D element");
}

772 773 774 775 776 777 778 779 780
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",
            "Need to define a RINGDEFINITION to use VariableRFCavity element");
}

gsell's avatar
gsell committed
781 782 783 784 785 786 787 788
/**
 *
 *
 * @param as
 */
void ParallelCyclotronTracker::visitRFCavity(const RFCavity &as) {

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

790 791
    RFCavity *elptr = dynamic_cast<RFCavity *>(as.clone());
    myElements.push_back(elptr);
gsell's avatar
gsell committed
792 793 794 795 796 797 798

    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 ...");
    }

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

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

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

808
    std::string fmfn = elptr->getFieldMapFN();
gsell's avatar
gsell committed
809
    *gmsg << "* RF Field map file name= " << fmfn << endl;
810
    double angle = elptr->getAzimuth();
gsell's avatar
gsell committed
811 812
    *gmsg << "* Cavity azimuth position= " << angle << " [deg] " << endl;

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

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

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

822 823 824 825 826 827

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

828 829 830 831
    std::shared_ptr<AbstractTimeDependence> freq_atd = nullptr;
    std::shared_ptr<AbstractTimeDependence> ampl_atd = nullptr;
    std::shared_ptr<AbstractTimeDependence> phase_atd = nullptr;

832 833 834 835 836 837
    std::vector<double>  unityVec;
    unityVec.push_back(1.);
    unityVec.push_back(0.);
    unityVec.push_back(0.);
    unityVec.push_back(0.);
    
838 839 840 841
    if (elptr->getFrequencyModelName() != "") {
      freq_atd = AbstractTimeDependence::getTimeDependence(elptr->getFrequencyModelName());
      *gmsg << "* Variable frequency RF Model name " << elptr->getFrequencyModelName() << endl;
    }
842 843
    else
        freq_atd = std::shared_ptr<AbstractTimeDependence>(new PolynomialTimeDependence(unityVec));
844 845 846 847 848

    if (elptr->getAmplitudeModelName() != "") {
      ampl_atd = AbstractTimeDependence::getTimeDependence(elptr->getAmplitudeModelName());
      *gmsg << "* Variable amplitude RF Model name " << elptr->getAmplitudeModelName() << endl;
    }
849 850
    else
        ampl_atd = std::shared_ptr<AbstractTimeDependence>(new PolynomialTimeDependence(unityVec));
851 852 853 854 855

    if (elptr->getPhaseModelName() != "") {
      phase_atd = AbstractTimeDependence::getTimeDependence(elptr->getPhaseModelName());
      *gmsg << "* Variable phase RF Model name " << elptr->getPhaseModelName() << endl;
    }
856 857
    else
        phase_atd = std::shared_ptr<AbstractTimeDependence>(new PolynomialTimeDependence(unityVec));
858

gsell's avatar
gsell committed
859
    // read cavity voltage profile data from file.
860 861 862
    elptr->initialise(itsBunch, 1.0, freq_atd, ampl_atd, phase_atd);

//    elptr->initialise(itsBunch, 1.0); 
gsell's avatar
gsell committed
863 864 865 866

    double BcParameter[8];
    for(int i = 0; i < 8; i++)
        BcParameter[i] = 0.0;
867
    std::string ElementType = "CAVITY";
gsell's avatar
gsell committed
868 869 870 871 872 873 874 875 876 877 878 879 880 881
    BcParameter[0] = rmin;
    BcParameter[1] = rmax;
    BcParameter[2] = pdis;
    BcParameter[3] = angle;

    buildupFieldList(BcParameter, ElementType, elptr);
}

/**
 *
 *
 * @param rfq
 */
void ParallelCyclotronTracker::visitRFQuadrupole(const RFQuadrupole &rfq) {
882
    *gmsg << "In RFQuadrupole; L = " << rfq.getElementLength() << " however the element is missing " << endl;
gsell's avatar
gsell committed
883 884 885 886 887 888 889 890 891
    myElements.push_back(dynamic_cast<RFQuadrupole *>(rfq.clone()));
}

/**
 *
 *
 * @param bend
 */
void ParallelCyclotronTracker::visitSBend(const SBend &bend) {
892
    *gmsg << "In SBend; L = " << bend.getElementLength() << " however the element is missing " << endl;
gsell's avatar
gsell committed
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
    myElements.push_back(dynamic_cast<SBend *>(bend.clone()));
}

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

/**
 *
 *
 * @param sept
 */
void ParallelCyclotronTracker::visitSeptum(const Septum &sept) {
912

913
    *gmsg << endl << "* -----------------------------  Septum ------------------------------- *" << endl;
gsell's avatar
gsell committed
914

915 916
    Septum *elptr = dynamic_cast<Septum *>(sept.clone());
    myElements.push_back(elptr);
gsell's avatar
gsell committed
917

918
    double xstart = elptr->getXstart();
919
    *gmsg << "XStart = " << xstart << " [mm]" << endl;
gsell's avatar
gsell committed
920

921
    double xend = elptr->getXend();
922
    *gmsg << "XEnd = " << xend << " [mm]" << endl;
gsell's avatar
gsell committed
923

924
    double ystart = elptr->getYstart();
925
    *gmsg << "YStart = " << ystart << " [mm]" << endl;
gsell's avatar
gsell committed
926

927
    double yend = elptr->getYend();
928
    *gmsg << "YEnd = " << yend << " [mm]" << endl;
gsell's avatar
gsell committed
929

930
    double width = elptr->getWidth();
931
    *gmsg << "Width = " << width << " [mm]" << endl;
gsell's avatar
gsell committed
932 933 934 935 936 937 938 939


    // initialise, do nothing
    elptr->initialise(itsBunch, 1.0);

    double BcParameter[8];
    for(int i = 0; i < 8; i++)
        BcParameter[i] = 0.0;
940
    std::string ElementType = "SEPTUM";
gsell's avatar
gsell committed
941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
    BcParameter[0] = xstart ;
    BcParameter[1] = xend;
    BcParameter[2] = ystart ;
    BcParameter[3] = yend;
    BcParameter[4] = width ;

    // store septum parameters in the list
    buildupFieldList(BcParameter, ElementType, elptr);
}

/**
 *
 *
 * @param solenoid
 */
void ParallelCyclotronTracker::visitSolenoid(const Solenoid &solenoid) {
    myElements.push_back(dynamic_cast<Solenoid *>(solenoid.clone()));
    Component *elptr = *(--myElements.end());
    if(!elptr->hasAttribute("ELEMEDGE")) {
        *gmsg << "Solenoid: no position of the element given!" << endl;
        return;
    }
}

/**
 *
 *
 * @param pplate
 */
void ParallelCyclotronTracker::visitParallelPlate(const ParallelPlate &pplate) {//do nothing

    //*gmsg << "ParallelPlate: not in use in ParallelCyclotronTracker!" << endl;

    //buildupFieldList(startField, endField, elptr);

}

/**
 *
 *
 * @param cv
 */
void ParallelCyclotronTracker::visitCyclotronValley(const CyclotronValley &cv) {
    // Do nothing here.
}
/**
 * not used
 *
 * @param angle
 * @param curve
 * @param field
 * @param scale
 */
void ParallelCyclotronTracker::applyEntranceFringe(double angle, double curve,
        const BMultipoleField &field, double scale) {

}

/**
 *
 *
 * @param stripper
 */

void ParallelCyclotronTracker::visitStripper(const Stripper &stripper) {

    *gmsg << "* ---------Stripper------------------------------" << endl;

1009 1010 1011 1012
    Stripper *elptr = dynamic_cast<Stripper *>(stripper.clone());
    myElements.push_back(elptr);

    double xstart = elptr->getXstart();
gsell's avatar
gsell committed
1013 1014
    *gmsg << "XStart= " << xstart << " [mm]" << endl;

1015
    double xend = elptr->getXend();
gsell's avatar
gsell committed
1016 1017
    *gmsg << "XEnd= " << xend << " [mm]" << endl;

1018
    double ystart = elptr->getYstart();
gsell's avatar
gsell committed
1019 1020
    *gmsg << "YStart= " << ystart << " [mm]" << endl;

1021
    double yend = elptr->getYend();
gsell's avatar
gsell committed
1022 1023
    *gmsg << "YEnd= " << yend << " [mm]" << endl;

1024
    double width = elptr->getWidth();
gsell's avatar
gsell committed
1025 1026
    *gmsg << "Width= " << width << " [mm]" << endl;

1027
    double opcharge = elptr->getOPCharge();
1028
    *gmsg << "Charge of outcoming particle = +e * " << opcharge << endl;
gsell's avatar
gsell committed
1029

1030
    double opmass = elptr->getOPMass();
1031
    *gmsg << "* Mass of the outcoming particle = " << opmass << " [GeV/c^2]" << endl;
gsell's avatar
gsell committed
1032 1033 1034 1035 1036 1037

    elptr->initialise(itsBunch, 1.0);

    double BcParameter[8];
    for(int i = 0; i < 8; i++)
        BcParameter[i] = 0.0;
1038
    std::string ElementType =