ParallelCyclotronTracker.cpp 223 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 18 19 20 21
//
// ------------------------------------------------------------------------
#include <cfloat>
#include <iostream>
#include <fstream>
#include <vector>
22
#include "AbstractObjects/OpalData.h"
gsell's avatar
gsell committed
23 24 25 26 27
#include "Algorithms/ParallelCyclotronTracker.h"

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

#include "Elements/OpalBeamline.h"
51
#include "Elements/OpalRing.h"
gsell's avatar
gsell committed
52 53 54

#include "BeamlineGeometry/Euclid3D.h"
#include "BeamlineGeometry/PlanarArcGeometry.h"
Jianjun Yang's avatar
Jianjun Yang committed
55
#include "BeamlineGeometry/RBendGeometry.h"
gsell's avatar
gsell committed
56 57 58 59 60 61 62 63 64 65 66 67
#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"

68
#include "Structure/BoundaryGeometry.h"
gsell's avatar
gsell committed
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87

#include "Ctunes.h"
#include "Ctunes.cc"
#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
88 89
const double PIOVER180 = pi / 180.0; 

90 91 92
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
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111

#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),
112
    eta_m(0.01),
gsell's avatar
gsell committed
113 114
    myNode_m(Ippl::myNode()),
    initialLocalNum_m(0),
115 116
    initialTotalNum_m(0),
    opalRing_m(NULL) {
gsell's avatar
gsell committed
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
    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,
                                                   int maxSTEPS, int timeIntegrator):
    Tracker(beamline, reference, revBeam, revTrack),
    maxSteps_m(maxSTEPS),
    timeIntegrator_m(timeIntegrator),
141
    eta_m(0.01),
gsell's avatar
gsell committed
142 143
    myNode_m(Ippl::myNode()),
    initialLocalNum_m(bunch.getLocalNum()),
144 145
    initialTotalNum_m(bunch.getTotalNum()),
    opalRing_m(NULL) {
gsell's avatar
gsell committed
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
    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() {
    for(list<Component *>::iterator compindex = myElements.begin(); compindex != myElements.end(); compindex++) {
        delete(*compindex);
    }
    for(beamline_list::iterator fdindex = FieldDimensions.begin(); fdindex != FieldDimensions.end(); fdindex++) {
        delete(*fdindex);
    }
    delete itsBeamline;
171 172 173
    if (opalRing_m != NULL) {
        // delete opalRing_m;
    }
gsell's avatar
gsell committed
174 175
}

176 177 178 179 180 181 182 183 184 185 186 187 188
/**
 * AAA
 *
 * @param none
 */
void ParallelCyclotronTracker::initializeBoundaryGeometry() {
  for(list<Component *>::iterator compindex = myElements.begin(); compindex != myElements.end(); compindex++) {
    bgf_m = dynamic_cast<ElementBase *>(*compindex)->getBoundaryGeometry();
    if(!bgf_m) 
      continue;
    else
      break;
  }
adelmann's avatar
adelmann committed
189 190 191 192 193
  if (bgf_m) {
    itsDataSink->writeGeomToVtk(*bgf_m, string("data/testGeometry-00000.vtk"));
    OpalData::getInstance()->setGlobalGeometry(bgf_m);
    *gmsg << "* Boundary geometry initialized " << endl;
  }
194
}
195

196 197 198 199 200 201 202 203 204 205
/**
 *
 *
 * @param fn Base file name
 */
void ParallelCyclotronTracker::bgf_main_collision_test() {
  if(!bgf_m) return;

  Inform msg("bgf_main_collision_test ");
  
206 207 208 209
  /**                                                                                                      
   *Here we check if a particles is outside the domain, flag it for deletion
   */

gsell's avatar
gsell committed
210
  Vector_t intecoords = 0.0;
211 212 213 214 215

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

216 217 218
  int triId = 0;     
  size_t Nimpact = 0;
  for(size_t i = 0; i < itsBunch->getLocalNum(); i++) {
219
    int res = bgf_m->PartInside(itsBunch->R[i]*1.0e-3, itsBunch->P[i], dtime, itsBunch->PType[i], itsBunch->Q[i], intecoords, triId);
220 221 222 223 224 225 226 227
    if(res >= 0) { 
      itsBunch->Bin[i] = -1;
      Nimpact++;
    }               
  }
}


gsell's avatar
gsell committed
228 229 230 231 232 233 234 235 236 237 238 239
/**
 *
 *
 * @param fn Base file name
 */
void ParallelCyclotronTracker::openFiles(string SfileName) {

    string  SfileName2 = SfileName + string("-Angle0.dat");

    outfTheta0_m.precision(8);
    outfTheta0_m.setf(ios::scientific, ios::floatfield);
    outfTheta0_m.open(SfileName2.c_str());
Jianjun Yang's avatar
Jianjun Yang committed
240
    outfTheta0_m << "#  r [mm]      beta_r*gamma       theta [mm]      beta_theta*gamma        z [mm]          beta_z*gamma" << endl;
gsell's avatar
gsell committed
241 242 243 244 245

    SfileName2 = SfileName + string("-Angle1.dat");
    outfTheta1_m.precision(8);
    outfTheta1_m.setf(ios::scientific, ios::floatfield);
    outfTheta1_m.open(SfileName2.c_str());
Jianjun Yang's avatar
Jianjun Yang committed
246
    outfTheta1_m << "#  r [mm]      beta_r*gamma       theta [mm]      beta_theta*gamma        z [mm]          beta_z*gamma"  << endl;
gsell's avatar
gsell committed
247 248 249 250 251

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

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

    SfileName2 = SfileName + string("-afterEachTurn.dat");

    outfThetaEachTurn_m.precision(8);
    outfThetaEachTurn_m.setf(ios::scientific, ios::floatfield);

    outfThetaEachTurn_m.open(SfileName2.c_str());
Jianjun Yang's avatar
Jianjun Yang committed
262
    outfTheta2_m << "#  r [mm]      beta_r*gamma       theta [mm]      beta_theta*gamma        z [mm]          beta_z*gamma"  << endl;
gsell's avatar
gsell committed
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
}

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

278 279 280 281 282
/** 
 *
 * @param ring
 */
void ParallelCyclotronTracker::visitOpalRing(const OpalRing &ring) {
Daniel Winklehner's avatar
Daniel Winklehner committed
283

284
    *gmsg << "Adding OpalRing" << endl;
Daniel Winklehner's avatar
Daniel Winklehner committed
285 286

    if (opalRing_m != NULL)
287
        delete opalRing_m;
Daniel Winklehner's avatar
Daniel Winklehner committed
288

289
    opalRing_m = dynamic_cast<OpalRing*>(ring.clone());
Daniel Winklehner's avatar
Daniel Winklehner committed
290

291
    myElements.push_back(opalRing_m);
Daniel Winklehner's avatar
Daniel Winklehner committed
292

293 294 295 296 297
    opalRing_m->initialise(itsBunch);

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

299 300 301 302
    if(referenceTheta <= -180.0 || referenceTheta > 180.0) {
        throw OpalException("Error in ParallelCyclotronTracker::visitOpalRing",
                            "PHIINIT is out of [-180, 180)!");
    }
Daniel Winklehner's avatar
Daniel Winklehner committed
303 304

    referenceZ = 0.0;
305
    referencePz = 0.0;
Daniel Winklehner's avatar
Daniel Winklehner committed
306 307 308 309

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

310 311
    if(referencePtot < 0.0)
        referencePt *= -1.0;
Daniel Winklehner's avatar
Daniel Winklehner committed
312

313 314
    sinRefTheta_m = sin(referenceTheta * PIOVER180);
    cosRefTheta_m = cos(referenceTheta * PIOVER180);
gsell's avatar
gsell committed
315

316
    double BcParameter[8];
Daniel Winklehner's avatar
Daniel Winklehner committed
317 318 319 320

    for(int i = 0; i < 8; i++) 
        BcParameter[i] = 0.0;

321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
    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
338 339 340 341 342 343 344 345 346 347

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

    *gmsg << "* --------- Cyclotron ------------------------------" << endl;

348 349
    Cyclotron *elptr = dynamic_cast<Cyclotron *>(cycl.clone());
    myElements.push_back(elptr);
350
     
351
    // Fresh run (no restart):
352
    if(!OpalData::getInstance()->inRestartRun()) {
353

354 355 356 357 358
        // Get reference values from cyclotron element
        referenceR     = elptr->getRinit();
        referenceTheta = elptr->getPHIinit();
        referenceZ     = elptr->getZinit();
        referencePr    = elptr->getPRinit();
359
        referencePz    = elptr->getPZinit(); 
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
         
        if(referenceTheta <= -180.0 || referenceTheta > 180.0) {
            throw OpalException("Error in ParallelCyclotronTracker::visitCyclotron", "PHIINIT is out of [-180, 180)!");
        }

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

        // Calculate reference azimuthal (tangential) momentum from total-, z- and radial momentum:
        float insqrt = referencePtot * referencePtot - referencePr * referencePr - referencePz * referencePz;

        if(insqrt < 0) {

            if(insqrt > -1.0e-10) {

	        referencePt = 0.0;

            } else {

	        throw OpalException("Error in ParallelCyclotronTracker::visitCyclotron", "Pt imaginary!");
            }

        } else {

            referencePt = sqrt(insqrt);
        }

Daniel Winklehner's avatar
Daniel Winklehner committed
386 387
        if(referencePtot < 0.0) 
            referencePt *= -1.0;
388 389 390 391 392 393 394 395 396 397 398 399 400
        // End calculate referencePt

    // Restart a run:
    } else {

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

            throw OpalException("Error in ParallelCyclotronTracker::visitCyclotron", "PHIINIT is out of [-180, 180)!");

        }
      
        referencePtot =  bega;
        // Note: Nothing else has to be set, b/c everything comes from the h5 file -DW
401 402
    }

403 404
    sinRefTheta_m = sin(referenceTheta * PIOVER180);
    cosRefTheta_m = cos(referenceTheta * PIOVER180);   
405
   
406
    *gmsg << endl;
adelmann's avatar
adelmann committed
407
    *gmsg << "* Bunch global starting position:" << endl;
408 409
    *gmsg << "* RINIT = " << referenceR  << " [mm]" << endl;
    *gmsg << "* PHIINIT = " << referenceTheta << " [deg]" << endl;
410
    *gmsg << "* ZINIT = " << referenceZ << " [mm]" << endl;
411
    *gmsg << endl;
adelmann's avatar
adelmann committed
412
    *gmsg << "* Bunch global starting momenta:" << endl;
gsell's avatar
gsell committed
413 414
    *gmsg << "* Initial gamma = " << itsReference.getGamma() << endl;
    *gmsg << "* Initial beta = " << itsReference.getBeta() << endl;
415
    *gmsg << "* Reference total momentum (beta * gamma) = " << referencePtot * 1000.0 << " [MCU]" << endl;
416 417 418
    *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;
419
    *gmsg << endl;
adelmann's avatar
adelmann committed
420

gsell's avatar
gsell committed
421
    double sym = elptr->getSymmetry();
422
    *gmsg << "* " << sym << "-fold field symmerty " << endl;
gsell's avatar
gsell committed
423

424 425 426
    // 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
427 428

    string fmfn = elptr->getFieldMapFN();
429
    *gmsg << "* Field map file name = " << fmfn << " " << endl;
gsell's avatar
gsell committed
430 431

    string type = elptr->getType();
432
    *gmsg << "* Type of cyclotron = " << type << " " << endl;
433 434 435
    
    double rmin = elptr->getMinR();
    double rmax = elptr->getMaxR();
436
    *gmsg << "* Radial aperture = " << rmin << " ... " << rmax<<" [mm] "<< endl;
437 438 439

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

442
    /**
443
    bool Sflag = elptr->getSuperpose();
444 445 446 447 448
    string flagsuperposed;
    if (Sflag)
      flagsuperposed="yes";
    else
      flagsuperposed="no";
449
    *gmsg << "* Electric field maps are superposed? " << flagsuperposed << " " << endl;
450
    */
451

gsell's avatar
gsell committed
452
    double h = elptr->getCyclHarm();
453
    *gmsg << "* Harmonic number h = " << h << " " << endl;
gsell's avatar
gsell committed
454

455
    /**
adelmann's avatar
adelmann committed
456
    if (elptr->getSuperpose())
457
        *gmsg << "* Fields are superposed " << endl;
458
    */
adelmann's avatar
adelmann committed
459

gsell's avatar
gsell committed
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
    /**
     * 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;
    if(type == string("CARBONCYCL")) {
        fieldflag = 2;
    } else if(type == string("CYCIAE")) {
        fieldflag = 3;
    } else if(type == string("AVFEQ")) {
        fieldflag = 4;
    } else if(type == string("FFAG")) {
        fieldflag = 5;
    } else if(type == string("BANDRF")) {
        fieldflag = 6;
481
    } else //(type == "RING")
gsell's avatar
gsell committed
482 483 484 485
        fieldflag = 1;

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

    double BcParameter[8];
490

adelmann's avatar
adelmann committed
491 492
    for(int i = 0; i < 8; i++) 
      BcParameter[i] = 0.0;
493

gsell's avatar
gsell committed
494 495 496
    BcParameter[0] = elptr->getRmin();
    BcParameter[1] = elptr->getRmax();

497 498
    // Store inner radius and outer radius of cyclotron field map in the list
    buildupFieldList(BcParameter, "CYCLOTRON", elptr);
gsell's avatar
gsell committed
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
}

/**
 * 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) {

516
    *gmsg << "* --------- Collimator -----------------------------" << endl;
gsell's avatar
gsell committed
517

518 519
    Collimator* elptr = dynamic_cast<Collimator *>(coll.clone());
    myElements.push_back(elptr);
gsell's avatar
gsell committed
520

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

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

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

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

533
    double zstart = elptr->getZStart();
adelmann's avatar
adelmann committed
534
    *gmsg << "* Zstart= " << zstart << " [mm]" << endl;
535 536

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

539
    double width = elptr->getWidth();
adelmann's avatar
adelmann committed
540
    *gmsg << "* Width= " << width << " [mm]" << endl;
gsell's avatar
gsell committed
541 542 543 544 545 546 547

    elptr->initialise(itsBunch, 1.0);

    double BcParameter[8];
    for(int i = 0; i < 8; i++)
        BcParameter[i] = 0.0;
    string ElementType = "CCOLLIMATOR";
548 549 550 551
    BcParameter[0] = xstart ;
    BcParameter[1] = xend;
    BcParameter[2] = ystart ;
    BcParameter[3] = yend;
gsell's avatar
gsell committed
552 553 554 555 556 557 558 559 560 561 562 563 564 565
    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
566 567 568 569 570 571 572 573 574 575 576 577
/**
 *
 *
 * @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
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
/**
 *
 *
 * @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()));
}

608 609 610 611 612 613 614 615 616 617 618
void ParallelCyclotronTracker::visitOffset(const Offset & off) {
    if (opalRing_m == NULL)
        throw OpalException(
                        "ParallelCylcotronTracker::visitOffset",
                        "Attempt to place an offset when OpalRing not defined");
    Offset* offNonConst = const_cast<Offset*>(&off);
    offNonConst->updateGeometry(opalRing_m->getNextPosition(),
                       opalRing_m->getNextNormal());
    opalRing_m->appendElement(off);
}

gsell's avatar
gsell committed
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
/**
 *
 *
 * @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());
}

641

gsell's avatar
gsell committed
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
/**
 *
 *
 * @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) {
658
    *gmsg << "* -----------  Probe -------------------------------" << endl;
659 660
    Probe *elptr = dynamic_cast<Probe *>(prob.clone());
    myElements.push_back(elptr);
gsell's avatar
gsell committed
661

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

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

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

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

674
    double width = elptr->getWidth();
675
    *gmsg << "Width= " << width << " [mm]" << endl;
gsell's avatar
gsell committed
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704


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

    double BcParameter[8];
    for(int i = 0; i < 8; i++)
        BcParameter[i] = 0.0;
    string ElementType = "PROBE";
    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()));
}

705 706 707 708 709 710 711 712 713
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");
}

714 715 716 717 718 719 720 721 722
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
723 724 725 726 727 728 729 730
/**
 *
 *
 * @param as
 */
void ParallelCyclotronTracker::visitRFCavity(const RFCavity &as) {

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

732 733
    RFCavity *elptr = dynamic_cast<RFCavity *>(as.clone());
    myElements.push_back(elptr);
gsell's avatar
gsell committed
734 735 736 737 738 739 740

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

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

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

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

750
    string fmfn = elptr->getFieldMapFN();
gsell's avatar
gsell committed
751
    *gmsg << "* RF Field map file name= " << fmfn << endl;
752
    double angle = elptr->getAzimuth();
gsell's avatar
gsell committed
753 754
    *gmsg << "* Cavity azimuth position= " << angle << " [deg] " << endl;

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

758
    double pdis = elptr->getPerpenDistance();
gsell's avatar
gsell committed
759 760 761
    *gmsg << "* Cavity Shift distance= " << pdis << " [mm] " << endl;


762
    double phi0 = elptr->getPhi0();
gsell's avatar
gsell committed
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
    *gmsg << "* Initial RF phase (t=0)= " << phi0 << " [deg] " << endl;

    // read cavity voltage profile data from file.
    elptr->initialise(itsBunch, 1.0);

    double BcParameter[8];
    for(int i = 0; i < 8; i++)
        BcParameter[i] = 0.0;
    string ElementType = "CAVITY";
    BcParameter[0] = rmin;
    BcParameter[1] = rmax;
    BcParameter[2] = pdis;
    BcParameter[3] = angle;

    buildupFieldList(BcParameter, ElementType, elptr);
}

/**
 *
 *
 * @param rfq
 */
void ParallelCyclotronTracker::visitRFQuadrupole(const RFQuadrupole &rfq) {
786
    *gmsg << "In RFQuadrupole; L = " << rfq.getElementLength() << " however the element is missing " << endl;
gsell's avatar
gsell committed
787 788 789 790 791 792 793 794 795
    myElements.push_back(dynamic_cast<RFQuadrupole *>(rfq.clone()));
}

/**
 *
 *
 * @param bend
 */
void ParallelCyclotronTracker::visitSBend(const SBend &bend) {
796
    *gmsg << "In SBend; L = " << bend.getElementLength() << " however the element is missing " << endl;
gsell's avatar
gsell committed
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815
    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) {
816

817
    *gmsg << endl << "* -----------------------------  Septum ------------------------------- *" << endl;
gsell's avatar
gsell committed
818

819 820
    Septum *elptr = dynamic_cast<Septum *>(sept.clone());
    myElements.push_back(elptr);
gsell's avatar
gsell committed
821

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

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

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

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

834
    double width = elptr->getWidth();
835
    *gmsg << "Width = " << width << " [mm]" << endl;
gsell's avatar
gsell committed
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912


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

    double BcParameter[8];
    for(int i = 0; i < 8; i++)
        BcParameter[i] = 0.0;
    string ElementType = "SEPTUM";
    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;

913 914 915 916
    Stripper *elptr = dynamic_cast<Stripper *>(stripper.clone());
    myElements.push_back(elptr);

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

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

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

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

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

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

934
    double opmass = elptr->getOPMass();
935
    *gmsg << "* Mass of the outcoming particle = " << opmass << " [GeV/c^2]" << endl;
gsell's avatar
gsell committed
936 937 938 939 940 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

    elptr->initialise(itsBunch, 1.0);

    double BcParameter[8];
    for(int i = 0; i < 8; i++)
        BcParameter[i] = 0.0;
    string ElementType = "STRIPPER";
    BcParameter[0] = xstart ;
    BcParameter[1] = xend;
    BcParameter[2] = ystart ;
    BcParameter[3] = yend;
    BcParameter[4] = width ;
    BcParameter[5] = opcharge;
    BcParameter[6] = opmass;

    buildupFieldList(BcParameter, ElementType, elptr);
}


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

}


/**
 *
 *
 * @param BcParameter
 * @param ElementType
 * @param elptr
 */
void ParallelCyclotronTracker::buildupFieldList(double BcParameter[], string ElementType, Component *elptr) {
    beamline_list::iterator sindex;

    type_pair *localpair = new type_pair();
    localpair->first = ElementType;

    for(int i = 0; i < 8; i++)
        *(((localpair->second).first) + i) = *(BcParameter + i);

    (localpair->second).second = elptr;

    // always put cyclotron as the first element in the list.
980
    if(ElementType == "OPALRING" || ElementType == "CYCLOTRON") { // CYCLOTRON is TEMP -DW
gsell's avatar
gsell committed
981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997
        sindex = FieldDimensions.begin();
    } else {
        sindex = FieldDimensions.end();
    }
    FieldDimensions.insert(sindex, localpair);

}

/**
 *
 *
 * @param bl
 */
void ParallelCyclotronTracker::visitBeamline(const Beamline &bl) {
    itsBeamline->iterate(*dynamic_cast<BeamlineVisitor *>(this), false);
}

Matthias Toggweiler's avatar
Matthias Toggweiler committed
998 999 1000 1001
void ParallelCyclotronTracker::checkNumPart(std::string s) {
    int nlp = itsBunch->getLocalNum();
    int minnlp = 0;
    int maxnlp = 111111;
gsell's avatar
gsell committed
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
    reduce(nlp, minnlp, OpMinAssign());
    reduce(nlp, maxnlp, OpMaxAssign());
    *gmsg << s << " min local particle number " << minnlp << " max local particle number: " << maxnlp << endl;
}

/**
 *
 *
 */
void ParallelCyclotronTracker::execute() {

    /*
      Initialize common variables and structures
      for the integrators
    */

    step_m = 0;
    restartStep0_m = 0;
Daniel Winklehner's avatar
Daniel Winklehner committed
1020 1021

    // Record how many bunches have already been injected. ONLY FOR MPM
gsell's avatar
gsell committed
1022 1023 1024 1025 1026 1027
    BunchCount_m = itsBunch->getNumBunch();

    // For the time being, we set bin number equal to bunch number. FixMe: not used
    BinCount_m = BunchCount_m;

    itsBeamline->accept(*this);
1028 1029
    if (opalRing_m != NULL)
        opalRing_m->lockRing();
gsell's avatar
gsell committed
1030

Daniel Winklehner's avatar
Daniel Winklehner committed
1031 1032
    // Display the selected elements
    *gmsg << "* -------------------------------------" << endl;
adelmann's avatar
Cleanup  
adelmann committed
1033
    *gmsg << "* The selected Beam line elements are :" << endl;
1034

gsell's avatar
gsell committed
1035
    for(beamline_list::iterator sindex = FieldDimensions.begin(); sindex != FieldDimensions.end(); sindex++)
1036 1037
        *gmsg << "* -> " <<  ((*sindex)->first) << endl;

Daniel Winklehner's avatar
Daniel Winklehner committed
1038
    *gmsg << "* -------------------------------------" << endl;
1039

Daniel Winklehner's avatar
Daniel Winklehner committed
1040 1041
    // Don't initializeBoundaryGeometry()
    // Get BoundaryGeometry that is already initialized
1042
    bgf_m = OpalData::getInstance()->getGlobalGeometry(); 
1043

Daniel Winklehner's avatar
Daniel Winklehner committed
1044
    // External field arrays for dumping
gsell's avatar
gsell committed
1045 1046
    for(int k = 0; k < 2; k++)
        FDext_m[k] = Vector_t(0.0, 0.0, 0.0);
Daniel Winklehner's avatar
Daniel Winklehner committed
1047

gsell's avatar
gsell committed
1048 1049 1050 1051 1052
    extE_m = Vector_t(0.0, 0.0, 0.0);
    extB_m = Vector_t(0.0, 0.0, 0.0);

    if(timeIntegrator_m == 0) {
        *gmsg << "* 4th order Runge-Kutta integrator" << endl;
1053 1054 1055
#ifdef GENERICTRACKER
        Tracker_Generic();
#else
gsell's avatar
gsell committed
1056
        Tracker_RK4();
1057
#endif
gsell's avatar
gsell committed
1058 1059
    } else if(timeIntegrator_m == 1) {
        *gmsg << "* 2nd order Leap-Frog integrator" << endl;
1060 1061 1062
#ifdef GENERICTRACKER
        Tracker_Generic();
#else
gsell's avatar
gsell committed
1063
        Tracker_LF();
1064
#endif
1065 1066 1067
    } else if(timeIntegrator_m == 2) {
        *gmsg << "* Multiple time stepping (MTS) integrator" << endl;
        Tracker_MTS();
gsell's avatar
gsell committed
1068 1069 1070 1071
    } else {
        *gmsg << "ERROR: Invalid name of TIMEINTEGRATOR in Track command" << endl;
        exit(1);
    }
1072
    *gmsg << "* ----------------------------------------------- *" << endl;
adelmann's avatar
Cleanup  
adelmann committed
1073
    *gmsg << "* Finalizing i.e. write data and close files :" << endl;
gsell's avatar
gsell committed
1074 1075 1076
    for(beamline_list::iterator sindex = FieldDimensions.begin(); sindex != FieldDimensions.end(); sindex++) {
        (((*sindex)->second).second)->finalise();
    }
1077
    *gmsg << "* ----------------------------------------------- *" << endl;
gsell's avatar
gsell committed
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
}

/**
   In general the two tracker have much code in common.
   This is a great source of errors.
   Need to avoid this

*/



/**
 *
 *
 */
void ParallelCyclotronTracker::Tracker_LF() {

    BorisPusher pusher;

    // time steps interval between bunches for multi-bunch simulation.
    const int stepsPerTurn = itsBunch->getStepsPerTurn();

1100
    const double harm = getHarmonicNumber();
gsell's avatar
gsell committed
1101 1102 1103 1104 1105 1106 1107 1108 1109

    // load time
    const double dt = itsBunch->getdT() * 1.0e9 * harm; //[s]-->[ns]

    // find the injection time interval
    if(numBunch_m > 1) {
        *gmsg << "Time interval between neighbour bunches is set to " << stepsPerTurn *dt << "[ns]" << endl;
    }

1110
    initTrackOrbitFile();
gsell's avatar
gsell committed
1111 1112 1113 1114

    int SteptoLastInj = itsBunch->getSteptoLastInj();

    // get data from h5 file for restart run
1115
    if(OpalData::getInstance()->inRestartRun()) {
1116
        restartStep0_m = itsBunch->getLocalTrackStep();
gsell's avatar
gsell committed
1117
        step_m = restartStep0_m;
1118
        if (numBunch_m > 1) itsBunch->resetPartBinID2(eta_m);
1119
        *gmsg << "* Restart at integration step " << restartStep0_m << endl;
gsell's avatar
gsell committed
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
    }

    if(OpalData::getInstance()->hasBunchAllocated() && Options::scan) {
        lastDumpedStep_m = 0;
        itsBunch->setT(0.0);
    }

    *gmsg << "* Beginning of this run is at t= " << itsBunch->getT() * 1e9 << " [ns]" << endl;
    *gmsg << "* The time step is set to dt= " << dt << " [ns]" << endl;

    // for single Particle Mode, output at zero degree.
    if(initialTotalNum_m == 1)
1132
        openFiles(OpalData::getInstance()->getInputBasename());
gsell's avatar
gsell committed
1133

1134
    double const initialReferenceTheta = referenceTheta * PIOVER180;
1135

1136
    initDistInGlobalFrame();
gsell's avatar
gsell committed
1137 1138 1139 1140 1141 1142

    //  read in some control parameters
    const int SinglePartDumpFreq = Options::sptDumpFreq;
    const int resetBinFreq = Options::rebinFreq;
    const int scSolveFreq = Options::scSolveFreq;
    const bool doDumpAfterEachTurn = Options::psDumpEachTurn;
1143
    const int boundpDestroyFreq = Options::boundpDestroyFreq;
gsell's avatar
gsell committed
1144 1145 1146 1147

    // prepare for dump after each turn
    double oldReferenceTheta = initialReferenceTheta;

adelmann's avatar
Cleanup  
adelmann committed
1148 1149
    *gmsg << "* Single particle trajectory dump frequency is set to " << SinglePartDumpFreq << endl;
    *gmsg << "* Repartition frequency is set to " << Options::repartFreq << endl;
gsell's avatar
gsell committed
1150 1151 1152 1153 1154 1155 1156 1157
    if(numBunch_m > 1)
        *gmsg << "particles energy bin ID reset frequency is set to " << resetBinFreq << endl;

    // if initialTotalNum_m = 2, trigger SEO mode
    // prepare for transverse tuning calculation
    vector<double> Ttime, Tdeltr, Tdeltz;
    // prepare for transverse tuning calculation
    vector<int> TturnNumber;
1158
    turnnumber_m = 1;
gsell's avatar
gsell committed
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170


    // flag to determine when to transit from single-bunch to multi-bunches mode
    bool flagTransition = false;
    // step point determining the next time point of check for transition
    int stepsNextCheck = step_m + itsBunch->getStepsPerTurn();

    const  double deltaTheta = pi / (stepsPerTurn);
    // record at which angle the space charge are solved
    double angleSpaceChargeSolve = 0.0;

    if(initialTotalNum_m == 1) {
1171
        *gmsg << endl;
gsell's avatar
gsell committed
1172 1173 1174 1175 1176 1177 1178 1179
        *gmsg << "* *---------------------------- SINGLE PARTICLE MODE------ ----------------------------*** " << endl;
        *gmsg << "* Instruction: when the total particle number equal to 1, single particle mode is triggered automatically," << endl
              << "* The initial distribution file must be specified which should contain only one line for the single particle " << endl
              << "* *------------NOTE: SINGLE PARTICLE MODE ONLY WORKS SERIALLY ON SINGLE NODE ------------------*** " << endl;
        if(Ippl::getNodes() != 1)
            throw OpalException("Error in ParallelCyclotronTracker::execute", "SINGLE PARTICLE MODE ONLY WORKS SERIALLY ON SINGLE NODE!");

    } else if(initialTotalNum_m == 2) {
1180
	*gmsg << endl;
gsell's avatar
gsell committed
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
        *gmsg << "* *------------------------ STATIC EQUILIBRIUM ORBIT MODE ----------------------------*** " << endl;
        *gmsg << "* Instruction: when the total particle number equal to 2, SEO mode is triggered automatically." << endl
              << "* This mode does NOT include any RF cavities. The initial distribution file must be specified" << endl
              << "* In the file the first line is for reference particle and the second line is for offcenter particle." << endl
              << "* The tunes are calculated by FFT routines based on these two particles. " << endl
              << "* *------------NOTE: SEO MODE ONLY WORKS SERIALLY ON SINGLE NODE ------------------*** " << endl;
        if(Ippl::getNodes() != 1)
            throw OpalException("Error in ParallelCyclotronTracker::execute", "SEO MODE ONLY WORKS SERIALLY ON SINGLE NODE!");
    }

1191
    // apply the plugin elements: probe, collimator, stripper, septum
1192 1193 1194
    // make sure that we apply elements even on first step
    applyPluginElements(dt);

gsell's avatar
gsell committed
1195 1196 1197
    // *****************II***************
    // main integration loop
    // *****************II***************
adelmann's avatar
Cleanup  
adelmann committed
1198
    *gmsg << "* ---------------------------- Start tracking ----------------------------" << endl;
gsell's avatar
gsell committed
1199 1200
    for(; step_m < maxSteps_m; step_m++) {
        bool dumpEachTurn = false;
1201 1202 1203
        if(step_m % SinglePartDumpFreq == 0) {
            singleParticleDump();
        }
gsell's avatar
gsell committed
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223