ParallelTTracker.h 23.9 KB
Newer Older
gsell's avatar
gsell committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#ifndef OPAL_ParallelTTracker_HH
#define OPAL_ParallelTTracker_HH

// ------------------------------------------------------------------------
// $RCSfile: ParallelTTracker.h,v $
// ------------------------------------------------------------------------
// $Revision: 1.1.2.1 $
// ------------------------------------------------------------------------
// Copyright: see Copyright.readme
// ------------------------------------------------------------------------
//
// Class: ParallelTTracker
//
// ------------------------------------------------------------------------
//
// $Date: 2004/11/12 20:10:11 $
// $Author: adelmann $
//
// ------------------------------------------------------------------------

#include "Algorithms/Tracker.h"
#include "Algorithms/PartPusher.h"
#include "Structure/DataSink.h"

25
#include "BasicActions/Option.h"
26
#include "Utilities/Options.h"
27 28
#include "Utilities/Options.h"

gsell's avatar
gsell committed
29
#include "Physics/Physics.h"
30 31 32
#ifdef HAVE_AMR_SOLVER
#include <Amr.H>
#endif
gsell's avatar
gsell committed
33

34 35 36 37
class BMultipoleField;
class PartBunch;
class AlignWrapper;
class BeamBeam;
38
#include "AbsBeamline/Collimator.h"
39
class Corrector;
adelmann's avatar
adelmann committed
40
class Degrader;
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
class Diagnostic;
class Drift;
class ElementBase;
class Lambertson;
class Marker;
class Monitor;
class Multipole;
class Probe;
class RBend;
class RFCavity;
class TravelingWave;
class RFQuadrupole;
class SBend;
class Separator;
class Septum;
class Solenoid;
class ParallelPlate;
class CyclotronValley;
gsell's avatar
gsell committed
59 60 61 62 63 64 65

#include "Beamlines/Beamline.h"
#include "Elements/OpalBeamline.h"
#include "Solvers/WakeFunction.hh"

#include <list>
#include <vector>
66
#include <queue>
gsell's avatar
gsell committed
67

68
class BorisPusher;
gsell's avatar
gsell committed
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110



// Class ParallelTTracker
// ------------------------------------------------------------------------
/// Track using a time integration scheme
// [p]
// Phase space coordinates numbering:
// [tab 3 b]
// [row]number [&]name          [&]unit  [/row]
// [row]0      [&]$x$           [&]metres [/row]
// [row]1      [&]$p_x/p_r$     [&]1      [/row]
// [row]2      [&]$y$           [&]metres [/row]
// [row]3      [&]$p_y/p_r$     [&]1      [/row]
// [row]4      [&]$v*delta_t$   [&]metres [/row]
// [row]5      [&]$delta_p/p_r$ [&]1      [/row]
// [/tab][p]
// Where $p_r$ is the constant reference momentum defining the reference
// frame velocity, $m$ is the rest mass of the particles, and $v$ is the
// instantaneous velocity of the particle.
// [p]
// Other units used:
// [tab 2 b]
// [row]quantity             [&]unit           [/row]
// [row]reference momentum   [&]electron-volts [/row]
// [row]velocity             [&]metres/second  [/row]
// [row]accelerating voltage [&]volts          [/row]
// [row]separator voltage    [&]volts          [/row]
// [row]frequencies          [&]hertz          [/row]
// [row]phase lags           [&]$2*pi$         [/row]
// [/tab][p]
// Approximations used:
// [ul]
// [li] blah
// [li] blah
// [li] blah
// [/ul]
//
// On going through an element, we use the following steps:
// To complete the map, we propagate the closed orbit and add that to the map.

typedef std::pair<double, Vector_t > PhaseEnT;
111
// typedef std::pair<std::string, double > MaxPhasesT;
gsell's avatar
gsell committed
112 113 114 115 116 117 118 119 120 121 122

class ParallelTTracker: public Tracker {

public:
    /// Constructor.
    //  The beam line to be tracked is "bl".
    //  The particle reference data are taken from "data".
    //  The particle bunch tracked is initially empty.
    //  If [b]revBeam[/b] is true, the beam runs from s = C to s = 0.
    //  If [b]revTrack[/b] is true, we track against the beam.
    explicit ParallelTTracker(const Beamline &bl, const PartData &data,
adelmann's avatar
adelmann committed
123
                              bool revBeam, bool revTrack, size_t N);
gsell's avatar
gsell committed
124 125 126 127 128 129 130 131

    /// Constructor.
    //  The beam line to be tracked is "bl".
    //  The particle reference data are taken from "data".
    //  The particle bunch tracked is taken from [b]bunch[/b].
    //  If [b]revBeam[/b] is true, the beam runs from s = C to s = 0.
    //  If [b]revTrack[/b] is true, we track against the beam.
    explicit ParallelTTracker(const Beamline &bl, PartBunch &bunch, DataSink &ds,
132 133 134
                              const PartData &data, bool revBeam, bool revTrack,
                              const std::vector<unsigned long long> &maxSTEPS, const std::vector<double> &zstop,
                              int timeIntegrator, const std::vector<double> &dt, size_t N);
gsell's avatar
gsell committed
135

136 137
    /// Constructor
    //  Amr pointer is taken
kraus's avatar
kraus committed
138
#ifdef HAVE_AMR_SOLVER
139
    explicit ParallelTTracker(const Beamline &bl, PartBunch &bunch, DataSink &ds,
140 141 142
                              const PartData &data, bool revBeam, bool revTrack,
                              const std::vector<unsigned long long> &maxSTEPS, const std::vector<double> &zstop,
                              int timeIntegrator, const std::vector<double> &dt, size_t N, Amr* amrptr_in);
143 144
#endif

gsell's avatar
gsell committed
145 146 147 148 149 150 151 152 153 154
    virtual ~ParallelTTracker();

    virtual void visitAlignWrapper(const AlignWrapper &);

    /// Apply the algorithm to a BeamBeam.
    virtual void visitBeamBeam(const BeamBeam &);

    /// Apply the algorithm to a collimator.
    virtual void visitCollimator(const Collimator &);

adelmann's avatar
adelmann committed
155

gsell's avatar
gsell committed
156 157 158
    /// Apply the algorithm to a Corrector.
    virtual void visitCorrector(const Corrector &);

adelmann's avatar
adelmann committed
159 160 161
    /// Apply the algorithm to a Degrader.
    virtual void visitDegrader(const Degrader &);

gsell's avatar
gsell committed
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
    /// Apply the algorithm to a Diagnostic.
    virtual void visitDiagnostic(const Diagnostic &);

    /// Apply the algorithm to a Drift.
    virtual void visitDrift(const Drift &);

    /// Apply the algorithm to a Lambertson.
    virtual void visitLambertson(const Lambertson &);

    /// Apply the algorithm to a Marker.
    virtual void visitMarker(const Marker &);

    /// Apply the algorithm to a Monitor.
    virtual void visitMonitor(const Monitor &);

    /// Apply the algorithm to a Multipole.
    virtual void visitMultipole(const Multipole &);

    /// Apply the algorithm to a Probe.
    virtual void visitProbe(const Probe &);

    /// Apply the algorithm to a RBend.
    virtual void visitRBend(const RBend &);

    /// Apply the algorithm to a RFCavity.
    virtual void visitRFCavity(const RFCavity &);

    /// Apply the algorithm to a RFCavity.
    virtual void visitTravelingWave(const TravelingWave &);

    /// Apply the algorithm to a RFQuadrupole.
    virtual void visitRFQuadrupole(const RFQuadrupole &);

    /// Apply the algorithm to a SBend.
    virtual void visitSBend(const SBend &);

    /// Apply the algorithm to a Separator.
    virtual void visitSeparator(const Separator &);

    /// Apply the algorithm to a Septum.
    virtual void visitSeptum(const Septum &);

    /// Apply the algorithm to a Solenoid.
    virtual void visitSolenoid(const Solenoid &);

    /// Apply the algorithm to a ParallelPlate.
    virtual void visitParallelPlate(const ParallelPlate &);

    /// Apply the algorithm to a CyclotronValley.
    virtual void visitCyclotronValley(const CyclotronValley &);


    //
    // Apply the emission considered schottky effect
    double schottkyLoop(double coeff);

    // Apply the correction to each particle for schottky effect
    void applySchottkyCorrection(PartBunch &itsBunch, int ne, double t, double rescale_coeff);


    /// Apply the algorithm to the top-level beamline.
    //  overwrite the execute-methode from DefaultVisitor
    virtual void execute();

    /// Apply the algorithm to a beam line.
    //  overwrite the execute-methode from DefaultVisitor
    virtual void visitBeamline(const Beamline &);

    /// set Multipacting flag
    inline void setMpacflg(bool mpacflg) {

        mpacflg_m = mpacflg;
    }

private:

    // Not implemented.
    ParallelTTracker();
    ParallelTTracker(const ParallelTTracker &);
    void operator=(const ParallelTTracker &);
242 243 244
#ifdef HAVE_AMR_SOLVER
    Amr* amrptr;
#endif
gsell's avatar
gsell committed
245

246 247 248 249 250
    /******************** STATE VARIABLES ***********************************/

    PartBunch        *itsBunch;
    DataSink         *itsDataSink_m;
    BoundaryGeometry *bgf_m;
gsell's avatar
gsell committed
251 252

    OpalBeamline itsOpalBeamline_m;
253 254
    LineDensity  lineDensity_m;

gsell's avatar
gsell committed
255 256 257 258 259 260

    Vector_t RefPartR_zxy_m;
    Vector_t RefPartP_zxy_m;
    Vector_t RefPartR_suv_m;
    Vector_t RefPartP_suv_m;

261

262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
#ifdef OPAL_DKS
  DKSBase dksbase;

  void *r_ptr;
  void *p_ptr;
  void *x_ptr;

  void *lastSec_ptr;
  void *orient_ptr;
  void *dt_ptr;

  int ierr;

  int stream1;
  int stream2;

  unsigned int numDeviceElements;
279 280 281 282 283

  void registerHostMemory();
  void unregisterHostMemory();
  void allocateDeviceMemory();
  void freeDeviceMemory();
284 285
#endif

286 287 288 289
    bool globalEOL_m;

    bool wakeStatus_m;

290
    /*--------- Added by Xiaoying Pang 04/22/2014 ---------------
kraus's avatar
kraus committed
291 292
     * This WakeFunction pointer is used to store a dipole's wake function and
     * to be used in the following drift if CSR calculation is requested in
293 294 295
     * the drift. */
    WakeFunction* wakeFunction_m;

296 297 298 299 300 301 302 303 304 305
    bool surfaceStatus_m;

    int secondaryFlg_m;

    /// multipacting flag
    bool mpacflg_m;

    bool nEmissionMode_m;

    /// where to stop
306
    std::queue<double> zStop_m;
307 308 309 310 311 312 313 314 315 316 317

    /// The scale factor for dimensionless variables (FIXME: move to PartBunch)
    double scaleFactor_m;

    // Vector of the scale factor for dimensionless variables (FIXME: move to PartBunch)
    Vector_t vscaleFactor_m;

    double recpGamma_m;

    double rescale_coeff_m;

318
    double dtCurrentTrack_m;
319
    std::queue<double> dtAllTracks_m;
320

Chuan Wang's avatar
Chuan Wang committed
321
    double surfaceEmissionStop_m;
322

adelmann's avatar
adelmann committed
323 324 325

    size_t specifiedNPart_m;

326 327 328 329 330 331 332 333 334 335 336 337 338
    // This variable controls the minimal number of steps of emission (using bins)
    // before we can merge the bins
    int minStepforReBin_m;

    // The space charge solver crashes if we use less than ~10 particles.
    // This variable controls the number of particles to be emitted before we use
    // the space charge solver.
    size_t minBinEmitted_m;

    // this variable controls the minimal number of steps until we repartition the particles
    int repartFreq_m;

    int lastVisited_m;
gsell's avatar
gsell committed
339 340 341 342

    /// The number of refinements of the search range of the phase
    int numRefs_m;

343 344 345 346 347
    /// ??
    int gunSubTimeSteps_m;

    unsigned int emissionSteps_m;

348
    /// The maximal number of steps the system is integrated per TRACK
349
    std::queue<unsigned long long> localTrackSteps_m;
gsell's avatar
gsell committed
350

351 352 353 354 355 356 357 358 359
    size_t maxNparts_m;
    size_t numberOfFieldEmittedParticles_m;

    // flag which indicates whether any particle is within the influence of bending element.
    // if this is the case we track the reference particle as if it were a real particle,
    // otherwise the reference particle is defined as the centroid particle of the bunch
    unsigned long bends_m;

    size_t numParticlesInSimulation_m;
360
    size_t totalParticlesInSimulation_m;
gsell's avatar
gsell committed
361 362 363

    Tenzor<double, 3> space_orientation_m;

364 365 366 367 368 369 370
    // Vector of the scale factor for dimensionless variables (FIXME: move to PartBunch)

    IpplTimings::TimerRef timeIntegrationTimer1_m;
    IpplTimings::TimerRef timeIntegrationTimer2_m;
    IpplTimings::TimerRef timeFieldEvaluation_m ;
    IpplTimings::TimerRef BinRepartTimer_m;
    IpplTimings::TimerRef WakeFieldTimer_m;
371
  
372 373
    IpplTimings::TimerRef timeIntegrationTimer1Push_m;
    IpplTimings::TimerRef timeIntegrationTimer2Push_m;
374

375 376 377 378
    // 1 --- LF-2 (Boris-Buneman)
    // 3 --- AMTS (Adaptive Boris-Buneman with multiple time stepping)
    int timeIntegrator_m;

kraus's avatar
kraus committed
379 380

    size_t Nimpact_m;
381
    double SeyNum_m;
382 383


384
    std::map<long, SurfacePhysicsHandler*> sphys_m;
385 386


387 388 389 390
    /********************** END VARIABLES ***********************************/

    int LastVisited;

gsell's avatar
gsell committed
391 392 393 394 395 396
    // Fringe fields for entrance and exit of magnetic elements.
    void applyEntranceFringe(double edge, double curve,
                             const BMultipoleField &field, double scale);
    void applyExitFringe(double edge, double curve,
                         const BMultipoleField &field, double scale);

397 398 399 400
    inline double getEnergyMeV(Vector_t p) {
        return (sqrt(dot(p, p) + 1.0) - 1.0) * itsBunch->getM() * 1e-6;
    }

gsell's avatar
gsell committed
401 402 403 404 405 406 407 408 409
    void kickParticles(const BorisPusher &pusher);
    void kickParticles(const BorisPusher &pusher, const int &flg);
    void updateReferenceParticle();

    void updateSpaceOrientation(const bool &move = false);
    Vector_t TransformTo(const Vector_t &vec, const Vector_t &ori) const;
    Vector_t TransformBack(const Vector_t &vec, const Vector_t &ori) const;

    void kickReferenceParticle(const Vector_t &externalE, const Vector_t &externalB);
410
    void writePhaseSpace(const long long step, const double &sposRef, bool psDump, bool statDump);
gsell's avatar
gsell committed
411

412
    /********** BEGIN AUTOPHSING STUFF **********/
413
    void updateRFElement(std::string elName, double maxPhi);
414 415 416 417
    void printRFPhases();
    void handleAutoPhasing();
    /************ END AUTOPHSING STUFF **********/

418 419
    void handleOverlappingMonitors();
    void prepareSections();
420 421 422

    double ptoEMeV(Vector_t p);

423
    void bgf_main_collision_test();
424 425 426 427
    void timeIntegration1(BorisPusher & pusher);
    void timeIntegration1_bgf(BorisPusher & pusher);
    void timeIntegration2(BorisPusher & pusher);
    void timeIntegration2_bgf(BorisPusher & pusher);
428
    void selectDT();
429
    void changeDT();
430 431 432 433 434 435
    void emitParticles(long long step);
    void computeExternalFields();
    void handleBends();
    void switchElements(double scaleMargin = 3.0);
    void computeSpaceChargeFields();
    void prepareOpalBeamlineSections();
436
    void dumpStats(long long step, bool psDump, bool statDump);
437 438 439
    void setOptionalVariables();
    bool hasEndOfLineReached();
    void doSchottyRenormalization();
440
    void setupSUV(bool updateReference = true);
441 442 443 444
    void handleRestartRun();
    void prepareEmission();
    void setTime();
    void initializeBoundaryGeometry();
445
    void doBinaryRepartition();
446
    void executeDefaultTracker();
447
#ifdef HAVE_AMR_SOLVER
448
    void executeAMRTracker();
449
#endif
450
    void executeAMTSTracker();
451
    void push(double h);
452
    void kick(double h, bool avoidGammaCalc = false);
453
    void computeExternalFields_AMTS();
454
    void borisExternalFields(double h, bool isFirstSubstep, bool isLastSubstep);
455 456 457
    double calcG(); // Time step chooser for adaptive variant
    Vector_t calcMeanR() const;
    Vector_t calcMeanP() const;
458
    double pSqr(Vector_t p1, Vector_t p2);
gsell's avatar
gsell committed
459 460
};

461 462
inline double ParallelTTracker::pSqr(Vector_t p1, Vector_t p2) {
  return p1[0]*p2[0] + p1[0]*p2[1] + p1[0]*p2[2] + p1[1]*p2[0] + p1[1]*p2[1] + p1[1]*p2[2] + p1[2]*p2[0] + p1[2]*p2[1] + p1[2]*p2[2];
463 464
}

gsell's avatar
gsell committed
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
inline double ParallelTTracker::ptoEMeV(Vector_t p) {
    return (sqrt(dot(p, p) + 1.0) - 1.0) * itsBunch->getM() * 1e-6;
}


inline void ParallelTTracker::visitBeamline(const Beamline &bl) {
    itsBeamline_m.iterate(*dynamic_cast<BeamlineVisitor *>(this), false);
}

inline void ParallelTTracker::visitAlignWrapper(const AlignWrapper &wrap) {
    itsOpalBeamline_m.visit(wrap, *this, itsBunch);
}

inline void ParallelTTracker::visitBeamBeam(const BeamBeam &bb) {
    itsOpalBeamline_m.visit(bb, *this, itsBunch);
}


inline void ParallelTTracker::visitCollimator(const Collimator &coll) {
    itsOpalBeamline_m.visit(coll, *this, itsBunch);
}


inline void ParallelTTracker::visitCorrector(const Corrector &corr) {
    itsOpalBeamline_m.visit(corr, *this, itsBunch);
}


adelmann's avatar
adelmann committed
493 494 495 496 497
inline void ParallelTTracker::visitDegrader(const Degrader &deg) {
    itsOpalBeamline_m.visit(deg, *this, itsBunch);
}


gsell's avatar
gsell committed
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 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 608 609 610 611 612 613 614 615 616
inline void ParallelTTracker::visitDiagnostic(const Diagnostic &diag) {
    itsOpalBeamline_m.visit(diag, *this, itsBunch);
}


inline void ParallelTTracker::visitDrift(const Drift &drift) {
    itsOpalBeamline_m.visit(drift, *this, itsBunch);
}


inline void ParallelTTracker::visitLambertson(const Lambertson &lamb) {
    itsOpalBeamline_m.visit(lamb, *this, itsBunch);
}


inline void ParallelTTracker::visitMarker(const Marker &marker) {
    itsOpalBeamline_m.visit(marker, *this, itsBunch);
}


inline void ParallelTTracker::visitMonitor(const Monitor &mon) {
    itsOpalBeamline_m.visit(mon, *this, itsBunch);
}


inline void ParallelTTracker::visitMultipole(const Multipole &mult) {
    itsOpalBeamline_m.visit(mult, *this, itsBunch);
}

inline void ParallelTTracker::visitProbe(const Probe &prob) {
    itsOpalBeamline_m.visit(prob, *this, itsBunch);
}


inline void ParallelTTracker::visitRBend(const RBend &bend) {
    itsOpalBeamline_m.visit(bend, *this, itsBunch);
}


inline void ParallelTTracker::visitRFCavity(const RFCavity &as) {
    itsOpalBeamline_m.visit(as, *this, itsBunch);
}

inline void ParallelTTracker::visitTravelingWave(const TravelingWave &as) {
    itsOpalBeamline_m.visit(as, *this, itsBunch);
}


inline void ParallelTTracker::visitRFQuadrupole(const RFQuadrupole &rfq) {
    itsOpalBeamline_m.visit(rfq, *this, itsBunch);
}

inline void ParallelTTracker::visitSBend(const SBend &bend) {
    itsOpalBeamline_m.visit(bend, *this, itsBunch);
}


inline void ParallelTTracker::visitSeparator(const Separator &sep) {
    itsOpalBeamline_m.visit(sep, *this, itsBunch);
}


inline void ParallelTTracker::visitSeptum(const Septum &sept) {
    itsOpalBeamline_m.visit(sept, *this, itsBunch);
}


inline void ParallelTTracker::visitSolenoid(const Solenoid &solenoid) {
    itsOpalBeamline_m.visit(solenoid, *this, itsBunch);
}


inline void ParallelTTracker::visitParallelPlate(const ParallelPlate &pplate) {
    itsOpalBeamline_m.visit(pplate, *this, itsBunch);
}

inline void ParallelTTracker::visitCyclotronValley(const CyclotronValley &cv) {
    itsOpalBeamline_m.visit(cv, *this, itsBunch);
}

inline void ParallelTTracker::kickParticles(const BorisPusher &pusher) {
    int localNum = itsBunch->getLocalNum();
    for(int i = 0; i < localNum; ++i)
        pusher.kick(itsBunch->R[i], itsBunch->P[i], itsBunch->Ef[i], itsBunch->Bf[i], itsBunch->dt[i]);
    itsBunch->calcBeamParameters();
}

// BoundaryGeometry version of kickParticles function
inline void ParallelTTracker::kickParticles(const BorisPusher &pusher, const int &flg) {
    int localNum = itsBunch->getLocalNum();
    for(int i = 0; i < localNum; ++i) {
        if(itsBunch->TriID[i] == 0) { //TriID[i] will be 0 if particles don't collide the boundary before kick;
            pusher.kick(itsBunch->R[i], itsBunch->P[i], itsBunch->Ef[i], itsBunch->Bf[i], itsBunch->dt[i]);
        }
    }
    itsBunch->calcBeamParameters();
}

inline void ParallelTTracker::updateReferenceParticle() {
    RefPartR_suv_m = itsBunch->get_rmean() * scaleFactor_m;
    RefPartP_suv_m = itsBunch->get_pmean();

    /* Update the position of the reference particle in ZXY-coordinates. The angle between the ZXY- and the SUV-coordinate
     *  system is determined by the momentum of the reference particle. We calculate the momentum of the reference
     *  particle by rotating the centroid momentum (= momentum of the reference particle in the SUV-coordinate system).
     *  Then we push the reference particle with this momentum for half a time step.
     */

    double gamma = sqrt(1.0 + dot(RefPartP_suv_m, RefPartP_suv_m));

    /* First update the momentum of the reference particle in zxy coordinate system, then update its position     */
    RefPartP_zxy_m = dot(space_orientation_m, RefPartP_suv_m);

    RefPartR_zxy_m += RefPartP_zxy_m * scaleFactor_m / (2. * gamma);
    RefPartR_suv_m += RefPartP_suv_m * scaleFactor_m / (2. * gamma);

}

inline void ParallelTTracker::updateSpaceOrientation(const bool &move) {
617 618 619 620 621 622 623 624
    /*
       Update the position of the reference particle in
       ZXY-coordinates. The angle between the ZXY- and the
       SUV-coordinate system is determined by the momentum of the
       reference particle. We calculate the momentum of the reference
       particle by rotating the centroid momentum (= momentum of the
       reference particle in the SUV-coordinate system). Then we push
       the reference particle with this momentum for half a time step.
gsell's avatar
gsell committed
625
     */
626 627 628 629
    itsBunch->calcBeamParameters();
    RefPartR_suv_m = itsBunch->get_rmean();
    RefPartP_suv_m = itsBunch->get_pmean();

gsell's avatar
gsell committed
630 631
    double AbsMomentum = sqrt(dot(RefPartP_suv_m, RefPartP_suv_m));
    double AbsMomentumProj = sqrt(RefPartP_suv_m(0) * RefPartP_suv_m(0) + RefPartP_suv_m(2) * RefPartP_suv_m(2));
kraus's avatar
kraus committed
632
    RefPartP_zxy_m *= AbsMomentum / sqrt(dot(RefPartP_zxy_m, RefPartP_zxy_m));
gsell's avatar
gsell committed
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656

    space_orientation_m(0, 0) = RefPartP_zxy_m(2) / AbsMomentumProj;
    space_orientation_m(0, 1) = -RefPartP_zxy_m(0) * RefPartP_zxy_m(1) / (AbsMomentum * AbsMomentumProj);
    space_orientation_m(0, 2) = RefPartP_zxy_m(0) / AbsMomentum;
    space_orientation_m(1, 0) = 0.;
    space_orientation_m(1, 1) = AbsMomentumProj / AbsMomentum;
    space_orientation_m(1, 2) = RefPartP_zxy_m(1) / AbsMomentum;
    space_orientation_m(2, 0) = -RefPartP_zxy_m(0) / AbsMomentumProj;
    space_orientation_m(2, 1) = -RefPartP_zxy_m(2) * RefPartP_zxy_m(1) / (AbsMomentum * AbsMomentumProj);
    space_orientation_m(2, 2) = RefPartP_zxy_m(2) / AbsMomentum;

    Vector_t EulerAngles;

    if(RefPartP_suv_m(2) < 1.0e-12) {
        EulerAngles = Vector_t(0.0);
    } else {
        EulerAngles = Vector_t(-atan(RefPartP_suv_m(0) / RefPartP_suv_m(2)),          \
                               -asin(RefPartP_suv_m(1) / AbsMomentum),    \
                               0.0);
    }

    // Rotate the local coordinate system of all sections which are online
    Vector_t smin(0.0), smax(0.0);
    itsBunch->get_bounds(smin, smax);
657
    itsOpalBeamline_m.updateOrientation(EulerAngles, RefPartR_suv_m, smin(2), smax(2));
gsell's avatar
gsell committed
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733

    itsBunch->rotateAbout(RefPartR_suv_m, RefPartP_suv_m);
    if(move)       // move the bunch such that the new centroid location is at (0,0,z)
        itsBunch->moveBy(Vector_t(-RefPartR_suv_m(0), -RefPartR_suv_m(1), 0.0));
}

inline Vector_t ParallelTTracker::TransformTo(const Vector_t &vec, const Vector_t &ori) const {

    // Rotate to the the element's local coordinate system.
    //
    // 1) Rotate about the z axis by angle negative ori(2).
    // 2) Rotate about the y axis by angle negative ori(0).
    // 3) Rotate about the x axis by angle ori(1).

    const double sina = sin(ori(0));
    const double cosa = cos(ori(0));
    const double sinb = sin(ori(1));
    const double cosb = cos(ori(1));
    const double sinc = sin(ori(2));
    const double cosc = cos(ori(2));

    Vector_t temp(0.0, 0.0, 0.0);

    temp(0) = (cosa * cosc) * vec(0) + (cosa * sinc) * vec(1) - sina *        vec(2);
    temp(1) = (-cosb * sinc - sina * sinb * cosc) * vec(0) + (cosb * cosc - sina * sinb * sinc) * vec(1) - cosa * sinb * vec(2);
    temp(2) = (-sinb * sinc + sina * cosb * cosc) * vec(0) + (sinb * cosc + sina * cosb * sinc) * vec(1) + cosa * cosb * vec(2);

    return temp;
}

inline Vector_t ParallelTTracker::TransformBack(const Vector_t &vec, const Vector_t &ori) const {

    // Rotate out of the element's local coordinate system.
    //
    // 1) Rotate about the x axis by angle negative ori(1).
    // 2) Rotate about the y axis by angle ori(0).
    // 3) Rotate about the z axis by angle ori(3).

    const double sina = sin(ori(0));
    const double cosa = cos(ori(0));
    const double sinb = sin(ori(1));
    const double cosb = cos(ori(1));
    const double sinc = sin(ori(2));
    const double cosc = cos(ori(2));

    Vector_t temp(0.0, 0.0, 0.0);

    temp(0) =  cosa * cosc * vec(0) + (-sina * sinb * cosc - cosb * sinc) * vec(1) + (sina * cosb * cosc - sinb * sinc) * vec(2);
    temp(1) =  cosa * sinc * vec(0) + (-sina * sinb * sinc + cosb * cosc) * vec(1) + (sina * cosb * sinc + sinb * cosc) * vec(2);
    temp(2) = -sina        * vec(0) + (-cosa * sinb) * vec(1) + (cosa * cosb) * vec(2);

    return temp;
}

inline void ParallelTTracker::kickReferenceParticle(const Vector_t &externalE, const Vector_t &externalB) {
    using Physics::c;

    // track reference particle
    Vector_t um = RefPartP_suv_m + 0.5 * itsReference.getQ() * itsBunch->getdT() / itsReference.getM() * c * externalE;
    double gamma = sqrt(1.0 + dot(um, um));

    double tmp = 0.5 * itsReference.getQ() * c * c * itsBunch->getdT() / (itsReference.getM() * gamma);
    Vector_t a = tmp * externalB;

    Vector_t s = um + tmp * cross(um, externalB);

    tmp = 1.0 + dot(a, a);

    um(0) = ((1.0 + a(0) * a(0))    * s(0) + (a(0) * a(1) + a(2)) * s(1) + (a(0) * a(2) - a(1)) * s(2)) / tmp;
    um(1) = ((a(0) * a(1) - a(2)) * s(0) + (1.0 + a(1) * a(1)) * s(1) + (a(1) * a(2) + a(0)) * s(2)) / tmp;
    um(2) = ((a(0) * a(2) + a(1)) * s(0) + (a(1) * a(2) - a(0)) * s(1) + (1.0 + a(2) * a(2)) * s(2)) / tmp;

    RefPartP_suv_m = um + 0.5 * itsReference.getQ()  * itsBunch->getdT() / itsReference.getM() * c * externalE;

}

734
#endif // OPAL_ParallelTTracker_HH