OPAL (Object Oriented Parallel Accelerator Library) 2024.2
OPAL
ParallelCyclotronTracker.cpp
Go to the documentation of this file.
1//
2// Class ParallelCyclotronTracker
3// Tracker for OPAL-Cycl
4//
5// Copyright (c) 2007 - 2014, Jianjun Yang, Andreas Adelmann and Matthias Toggweiler,
6// Paul Scherrer Institut, Villigen PSI, Switzerland
7// Copyright (c) 2014, Daniel Winklehner, MIT, Cambridge, MA, USA
8// Copyright (c) 2012 - 2023, Paul Scherrer Institut, Villigen PSI, Switzerland
9// All rights reserved
10//
11// Implemented as part of the PhD thesis
12// "Beam dynamics in high intensity cyclotrons including neighboring bunch effects"
13// and the paper
14// "Beam dynamics in high intensity cyclotrons including neighboring bunch effects:
15// Model, implementation, and application"
16// (https://journals.aps.org/prab/pdf/10.1103/PhysRevSTAB.13.064201)
17//
18// This file is part of OPAL.
19//
20// OPAL is free software: you can redistribute it and/or modify
21// it under the terms of the GNU General Public License as published by
22// the Free Software Foundation, either version 3 of the License, or
23// (at your option) any later version.
24//
25// You should have received a copy of the GNU General Public License
26// along with OPAL. If not, see <https://www.gnu.org/licenses/>.
27//
29
34#include "AbsBeamline/Drift.h"
35#include "AbsBeamline/Marker.h"
36#include "AbsBeamline/Monitor.h"
40#include "AbsBeamline/Offset.h"
43#include "AbsBeamline/Probe.h"
44#include "AbsBeamline/RBend.h"
46#include "AbsBeamline/Ring.h"
47#include "AbsBeamline/SBend.h"
48#include "AbsBeamline/SBend3D.h"
50#include "AbsBeamline/Septum.h"
53#include "AbsBeamline/Vacuum.h"
57
59
60#include "Algorithms/Ctunes.h"
62
65
66#include "Beamlines/Beamline.h"
68
70
71#include "Physics/Physics.h"
72#include "Physics/Units.h"
73
75#include "Structure/DataSink.h"
77
79#include "Utilities/Options.h"
80
81#include <algorithm>
82#include <cmath>
83#include <filesystem>
84#include <limits>
85#include <numeric>
86
90
91extern Inform *gmsg;
92extern Inform *gmsgALL;
93
94
109 DataSink& ds,
110 const PartData& reference,
111 bool revBeam, bool revTrack,
112 int maxSTEPS,
113 Steppers::TimeIntegrator timeintegrator,
114 const int& numBunch,
115 const double& mbEta,
116 const double& mbPara,
117 const std::string& mbMode,
118 const std::string& mbBinning)
119 : Tracker(beamline, bunch, reference, revBeam, revTrack)
120 , bgf_m(nullptr)
121 , cycl_m(nullptr)
122 , maxSteps_m(maxSTEPS)
123 , lastDumpedStep_m(0)
124 , pathLength_m(0.0)
125 , myNode_m(Ippl::myNode())
126 , initialLocalNum_m(bunch->getLocalNum())
127 , initialTotalNum_m(bunch->getTotalNum())
128 , opalRing_m(nullptr)
129 , itsStepper_mp(nullptr)
130 , mode_m(TrackingMode::UNDEFINED)
131 , stepper_m(timeintegrator)
132 , rotation_m(3,3)
133{
134 itsBeamline = dynamic_cast<Beamline*>(beamline.clone());
135 itsDataSink = &ds;
136
137 if ( numBunch > 1 ) {
138 // The core-fitted mesh exists for the single-bunch solve only. Deciding here, and
139 // not at the first solve with more than one bunch, keeps a run from switching
140 // between the two meshes after the second injection.
141 if (bunch->getMeshFit().type == MeshFitType::CORE) {
142 throw OpalException("ParallelCyclotronTracker::ParallelCyclotronTracker()",
143 "FIELDSOLVER, MESHFIT=\"CORE\" is not available in "
144 "multi-bunch mode (TURNS > 1 in RUN).");
145 }
146 mbHandler_m = std::unique_ptr<MultiBunchHandler>(
147 new MultiBunchHandler(bunch, numBunch, mbEta,
148 mbPara, mbMode, mbBinning)
149 );
150 }
151
153 TransformTimer_m = IpplTimings::getTimer("Frametransform");
155 BinRepartTimer_m = IpplTimings::getTimer("Binaryrepart");
156 PluginElemTimer_m = IpplTimings::getTimer("PluginElements");
157 DelParticleTimer_m = IpplTimings::getTimer("DeleteParticles");
158
160}
161
167 for (Component* component : myElements) {
168 delete(component);
169 }
170 for (auto fd : FieldDimensions) {
171 delete(fd);
172 }
173 delete itsBeamline;
174 // delete opalRing_m;
175}
176
177
179 if (!bgf_m) return;
180
181 Inform msg("bgf_main_collision_test ");
182
187 Vector_t intecoords = 0.0;
188
189 // This has to match the dT in the rk4 pusher
190 double dtime = itsBunch_m->getdT() * getHarmonicNumber();
191
192 int triId = 0;
193 for (size_t i = 0; i < itsBunch_m->getLocalNum(); i++) {
194 // already lost (Bin < 0) and recorded, waiting for deleteParticle()
195 if (itsBunch_m->Bin[i] < 0) continue;
196
197 int res = bgf_m->partInside(itsBunch_m->R[i], itsBunch_m->P[i],
198 dtime, intecoords, triId);
199 if (res >= 0) {
200 // OpalParticle takes the rest mass in MeV. M[i] is the macro-particle mass in
201 // GeV, except for particles made by a Stripper (STOP=FALSE) or by beam
202 // stripping, whose M[i] is their own mass in GeV.
203 const double mass = (itsBunch_m->POrigin[i] == ParticleOrigin::REGULAR) ?
205 lossDs_m->addParticle(OpalParticle(itsBunch_m->ID[i],
206 itsBunch_m->R[i], itsBunch_m->P[i],
207 itsBunch_m->getT(),
208 itsBunch_m->Q[i], mass),
209 std::make_pair(turnnumber_m, itsBunch_m->bunchNum[i]));
210 itsBunch_m->Bin[i] = -1;
211 *gmsgALL << level4 << "* Particle " << itsBunch_m->ID[i]
212 << " lost on boundary geometry" << endl;
213 }
214 }
215}
216
217// only used for dumping into stat file
218void ParallelCyclotronTracker::dumpAngle(const double& theta,
219 double& prevAzimuth,
220 double& azimuth,
221 const short& bunchNr) {
222 if ( prevAzimuth < 0.0 ) { // only at first occurrence
223 double plus = 0.0;
224 if ( OpalData::getInstance()->inRestartRun() ) {
225 plus = 360.0 * (turnnumber_m - bunchNr);
226 }
227 azimuth = theta + plus;
228 } else {
229 double dtheta = theta - prevAzimuth;
230 if ( dtheta < 0 ) {
231 dtheta += 360.0;
232 }
233 if ( dtheta > 180 ) { // rotating clockwise, reduce angle
234 dtheta -= 360;
235 }
236 azimuth += dtheta;
237 }
238 prevAzimuth = theta;
239}
240
241
243 return Units::m2mm * std::sqrt(meanR(0) * meanR(0) + meanR(1) * meanR(1));
244}
245
246
248 const double& dt)
249{
250 // the last element in dotP is the dot-product over all particles
251 std::vector<double> dotP(dl.size());
253
254 for (unsigned int i = 0; i < itsBunch_m->getLocalNum(); ++i) {
255 dotP[itsBunch_m->bunchNum[i]] += dot(itsBunch_m->P[i], itsBunch_m->P[i]);
256 }
257
258 allreduce(dotP.data(), dotP.size(), std::plus<double>());
259
260 // dot-product over all particles; without multi-bunches dotP has a single
261 // entry, which already holds the sum over all particles
262 const size_t numBunchEntries = std::max(dotP.size() - 1, size_t(1));
263 double sum = std::accumulate(dotP.begin(), dotP.begin() + numBunchEntries, 0.0);
264 dotP.back() = sum / double(itsBunch_m->getTotalNum());
265
266 // bunch specific --> multi-bunches only
267 for (short b = 0; b < (short)dotP.size() - 1; ++b) {
268 dotP[b] /= double(itsBunch_m->getTotalNumPerBunch(b));
269 }
270
271 } else {
272 // here we are in DumpFrame::GLOBAL (or REFERENCE) mode: s is the path length of the
273 // reference particle, ID 0. Local index 0 is an arbitrary particle that differs between
274 // ranks and changes with every migration, so ID 0 is looked up collectively and every
275 // rank accumulates the same s (stat file 's', H5 'SPOS'). Once ID 0 is lost, s goes on
276 // with the bunch mean of |P|^2, as in BUNCH_MEAN mode.
277 double buf[2] = {0.0, 0.0};
278 for (size_t i = 0; i < itsBunch_m->getLocalNum(); ++i) {
279 if (itsBunch_m->ID[i] == 0) {
280 buf[0] = dot(itsBunch_m->P[i], itsBunch_m->P[i]);
281 buf[1] = 1.0;
282 break;
283 }
284 }
285
286 allreduce(buf, 2, std::plus<double>());
287
288 if (buf[1] == 1.0) {
289 dotP[0] = buf[0];
290 } else {
291 double sum = 0.0;
292 for (size_t i = 0; i < itsBunch_m->getLocalNum(); ++i) {
293 sum += dot(itsBunch_m->P[i], itsBunch_m->P[i]);
294 }
295
296 allreduce(sum, 1, std::plus<double>());
297
298 const size_t totalNum = itsBunch_m->getTotalNum();
299 dotP[0] = (totalNum > 0) ? sum / double(totalNum) : 0.0;
300 }
301 }
302
303 for (size_t i = 0; i < dotP.size(); ++i) {
304 double const gamma = std::sqrt(1.0 + dotP[i]);
305 double const beta = std::sqrt(dotP[i]) / gamma;
306 dl[i] = Physics::c * dt * beta;
307 }
308}
309
310
316void ParallelCyclotronTracker::openFiles(size_t numFiles, std::string SfileName) {
317
318 for (unsigned int i=0; i<numFiles; i++) {
319 std::string SfileName2 = SfileName;
320 if (i<=2) {
321 SfileName2 += std::string("-Angle" + std::to_string(int(i)) + ".dat");
322 }
323 else {
324 // for single Particle Mode, output after each turn, to define matched initial phase ellipse.
325 SfileName2 += std::string("-afterEachTurn.dat");
326 }
327
328 outfTheta_m.emplace_back(new std::ofstream(SfileName2.c_str()));
329 outfTheta_m.back()->precision(8);
330 outfTheta_m.back()->setf(std::ios::scientific, std::ios::floatfield);
331 // r and z are written as they are tracked, in metres
332 *outfTheta_m.back() << "# r [m] beta_r*gamma "
333 << "theta [deg] beta_theta*gamma "
334 << "z [m] beta_z*gamma" << std::endl;
335 }
336}
337
344 for (auto & file : outfTheta_m) {
345 file->close();
346 }
347}
348
349
356 *gmsg << "* ----------------------------- Cyclotron -------------------------------- *" << endl;
357
358 cycl_m = dynamic_cast<Cyclotron*>(cycl.clone());
359 myElements.push_back(cycl_m);
360
361 // Is this a Spiral Inflector Simulation? If yes, we'll give the user some
362 // useful information
364 if (spiral_flag) {
365 *gmsg << endl << "* This is a Spiral Inflector Simulation! This means the following:" << endl;
366 *gmsg << "* 1.) It is up to the user to provide appropriate geometry, electric and magnetic fields!" << endl;
367 *gmsg << "* (Use BANDRF type cyclotron and use RFMAPFN to load both magnetic" << endl;
368 *gmsg << "* and electric fields, setting SUPERPOSE to an array of TRUE values.)" << endl;
369 *gmsg << "* 2.) For high currents it is strongly recommended to use the SAAMG fieldsolver," << endl;
370 *gmsg << "* FFT does not give the correct results (boundary conditions are missing)." << endl;
371 *gmsg << "* 3.) The whole geometry will be meshed and used for the fieldsolver." << endl;
372 *gmsg << "* There will be no transformations of the bunch into a local frame und consequently," << endl;
373 *gmsg << "* the problem will be treated non-relativistically!" << endl;
374 *gmsg << "* (This is not an issue for spiral inflectors as they are typically < 100 keV/amu.)" << endl;
375 *gmsg << endl << "* Note: For now, multi-bunch mode (MBM) needs to be de-activated for spiral inflector" << endl;
376 *gmsg << "* and space charge needs to be solved every time-step. numBunch_m and scSolveFreq are reset." << endl;
377 if (isMultiBunch()) {
378 mbHandler_m = nullptr;
379 }
380 }
381
382 // Fresh run (no restart):
384
385 // Get reference values from cyclotron element
392
393 // Calculate reference azimuthal (tangential) momentum from total-, z- and radial momentum:
394 float insqrt = referencePtot * referencePtot - \
396
397 if (insqrt < 0) {
398 if (insqrt > -1.0e-10) {
399 referencePt = 0.0;
400 } else {
401 throw OpalException("Error in ParallelCyclotronTracker::visitCyclotron",
402 "Pt imaginary");
403 }
404 } else {
405 referencePt = std::sqrt(insqrt);
406 }
407
408 if (referencePtot < 0.0) {
409 referencePt *= -1.0;
410 }
411 // End calculate referencePt
412
413 // Restart a run:
414 } else {
415
416 // If the user wants to save the restarted run in local frame,
417 // make sure the previous h5 file was local too
419 if (!previousH5Local) {
420 throw OpalException("Error in ParallelCyclotronTracker::visitCyclotron",
421 "You are trying a local restart from a global h5 file");
422 }
423 // Else, if the user wants to save the restarted run in global frame,
424 // make sure the previous h5 file was global too
425 } else {
426 if (previousH5Local) {
427 throw OpalException("Error in ParallelCyclotronTracker::visitCyclotron",
428 "You are trying a global restart from a local h5 file");
429 }
430 }
431
432 // Adjust some of the reference variables from the h5 file
439 }
440
442
443 sinRefTheta_m = std::sin(referenceTheta);
444 cosRefTheta_m = std::cos(referenceTheta);
445
446 *gmsg << endl;
447 *gmsg << "* Bunch global starting position:" << endl;
448 *gmsg << "* RINIT = " << referenceR << " [m]" << endl;
449 *gmsg << "* PHIINIT = " << referenceTheta * Units::rad2deg << " [deg]" << endl;
450 *gmsg << "* ZINIT = " << referenceZ << " [m]" << endl;
451 *gmsg << endl;
452 *gmsg << "* Bunch global starting momenta:" << endl;
453 *gmsg << "* Initial gamma = " << itsReference.getGamma() << endl;
454 *gmsg << "* Initial beta = " << itsReference.getBeta() << endl;
455 *gmsg << "* Reference total momentum = " << referencePtot << " [beta gamma]" << endl;
456 *gmsg << "* Reference azimuthal momentum (Pt) = " << referencePt << " [beta gamma]" << endl;
457 *gmsg << "* Reference radial momentum (Pr) = " << referencePr << " [beta gamma]" << endl;
458 *gmsg << "* Reference axial momentum (Pz) = " << referencePz << " [beta gamma]" << endl;
459 *gmsg << endl;
460
461 double sym = cycl_m->getSymmetry();
462 *gmsg << "* " << sym << "-fold field symmetry " << endl;
463
464 // ckr: this just returned the default value as defined in Component.h
465 // double rff = cycl_m->getRfFrequ(0);
466 // *gmsg << "* Rf frequency= " << rff << " [MHz]" << endl;
467
468 std::string fmfn = cycl_m->getFieldMapFN();
469 *gmsg << "* Field map file = '" << fmfn << "'" << endl;
470
471 std::string type = cycl_m->getCyclotronType();
472 *gmsg << "* Type of cyclotron = " << type << " " << endl;
473
474 double rmin = cycl_m->getMinR();
475 double rmax = cycl_m->getMaxR();
476 *gmsg << "* Radial aperture = " << rmin << " ... " << rmax << " [m]" << endl;
477
478 double zmin = cycl_m->getMinZ();
479 double zmax = cycl_m->getMaxZ();
480 *gmsg << "* Vertical aperture = " << zmin << " ... " << zmax << " [m]" << endl;
481
482 double h = cycl_m->getCyclHarm();
483 *gmsg << "* Number of trimcoils = " << cycl_m->getNumberOfTrimcoils() << endl;
484 *gmsg << "* Harmonic number h = " << h << endl;
485
486 std::vector<double> rffrequ = cycl_m->getRfFrequ();
487 *gmsg << "* RF frequency = " << Util::doubleVectorToString(rffrequ) << " [MHz]" << endl;
488
490 std::vector<double> rfphi = cycl_m->getRfPhi();
491 for (size_t i = 0; i < rfphi.size(); ++i) {
492 rfphi[i] = rfphi[i] * Units::rad2deg;
493 }
494 *gmsg << "* RF inital phase = " << Util::doubleVectorToString(rfphi) << " [deg]" << endl;
495
496 std::vector<double> escale = cycl_m->getEScale();
497 *gmsg << "* E-field scale factor = " << Util::doubleVectorToString(escale) << endl;
498
499 std::vector<bool> superpose = cycl_m->getSuperpose();
500 *gmsg << "* Superpose electric field maps -> " << Util::boolVectorToUpperString(superpose) << endl;
501 }
502
503 // Read in cyclotron field maps
505
506 double BcParameter[8] = {};
507 BcParameter[0] = cycl_m->getRmin();
508 BcParameter[1] = cycl_m->getRmax();
509
510 // Store inner radius and outer radius of cyclotron field map in the list
512}
513
520 *gmsg << "* ----------------------------- Collimator ------------------------------- *" << endl;
521
522 CCollimator* elptr = dynamic_cast<CCollimator*>(coll.clone());
523 myElements.push_back(elptr);
524
525 *gmsg << "* Name = " << elptr->getName() << endl;
526
527 double xstart = elptr->getXStart();
528 *gmsg << "* XStart = " << xstart << " [m]" << endl;
529
530 double xend = elptr->getXEnd();
531 *gmsg << "* XEnd = " << xend << " [m]" << endl;
532
533 double ystart = elptr->getYStart();
534 *gmsg << "* YStart = " << ystart << " [m]" << endl;
535
536 double yend = elptr->getYEnd();
537 *gmsg << "* YEnd = " << yend << " [m]" << endl;
538
539 double zstart = elptr->getZStart();
540 *gmsg << "* ZStart = " << zstart << " [m]" << endl;
541
542 double zend = elptr->getZEnd();
543 *gmsg << "* ZEnd = " << zend << " [m]" << endl;
544
545 double width = elptr->getWidth();
546 *gmsg << "* Width = " << width << " [m]" << endl;
547
548 elptr->initialise(itsBunch_m);
549
550 double BcParameter[8] = {};
551
552 BcParameter[0] = xstart;
553 BcParameter[1] = xend;
554 BcParameter[2] = ystart;
555 BcParameter[3] = yend;
556 BcParameter[4] = width;
557
558 buildupFieldList(BcParameter, ElementType::CCOLLIMATOR, elptr);
559}
560
567 *gmsg << "In Corrector; L= " << corr.getElementLength() << endl;
568 myElements.push_back(dynamic_cast<Corrector*>(corr.clone()));
569}
570
577 *gmsg << "In Degrader; L= " << deg.getElementLength() << endl;
578 myElements.push_back(dynamic_cast<Degrader*>(deg.clone()));
579
580}
581
588 *gmsg << "In drift L= " << drift.getElementLength() << endl;
589 myElements.push_back(dynamic_cast<Drift*>(drift.clone()));
590}
591
600
607 if (opalRing_m == nullptr)
608 throw OpalException(
609 "ParallelCylcotronTracker::visitOffset",
610 "Attempt to place an offset when Ring not defined");
612}
613
620 // *gmsg << "In Marker; L= " << marker.getElementLength() << endl;
621 myElements.push_back(dynamic_cast<Marker*>(marker.clone()));
622 // Do nothing.
623}
624
631 // *gmsg << "In Monitor; L= " << corr.getElementLength() << endl;
632 myElements.push_back(dynamic_cast<Monitor*>(corr.clone()));
633 // applyDrift(flip_s * corr.getElementLength());
634}
635
642 *gmsg << "In Multipole; L= " << mult.getElementLength() << " however the element is missing " << endl;
643 myElements.push_back(dynamic_cast<Multipole*>(mult.clone()));
644}
645
652 *gmsg << "Adding MultipoleT" << endl;
653 if (opalRing_m != nullptr) {
655 } else {
656 throw OpalException("ParallelCyclotronTracker::visitMultipoleT",
657 "Need to define a RINGDEFINITION to use MultipoleT element");
658 }
659 myElements.push_back(dynamic_cast<MultipoleT*>(multT.clone()));
660}
661
668 if (opalRing_m == nullptr) {
669 throw OpalException("ParallelCylcotronTracker::visitOutputPlane",
670 "Attempt to place an OutputPlane when Ring not defined");
671 }
672
673 OutputPlane* elptr = dynamic_cast<OutputPlane*>(plane.clone());
675 myElements.push_back(elptr);
676 elptr->initialise(itsBunch_m);
677
678 double BcParameter[8] = {};
679
680 Vector_t centre = elptr->getCentre();
681 Vector_t norm = elptr->getNormal();
682 double width = elptr->getHorizontalExtent();
683 BcParameter[0] = centre[0]-width*norm[1];
684 BcParameter[1] = centre[0]+width*norm[1];
685 BcParameter[2] = centre[1]-width*norm[0];
686 BcParameter[3] = centre[1]+width*norm[0];
687 BcParameter[4] = Units::mm2m; // thickness, not used
688 buildupFieldList(BcParameter, ElementType::OUTPUTPLANE, elptr);
689}
690
691
698 *gmsg << "* ----------------------------- Probe ------------------------------------ *" << endl;
699
700 Probe* elptr = dynamic_cast<Probe*>(prob.clone());
701 myElements.push_back(elptr);
702
703 *gmsg << "* Name = " << elptr->getName() << endl;
704
705 double xstart = elptr->getXStart();
706 *gmsg << "* XStart = " << xstart << " [m]" << endl;
707
708 double xend = elptr->getXEnd();
709 *gmsg << "* XEnd = " << xend << " [m]" << endl;
710
711 double ystart = elptr->getYStart();
712 *gmsg << "* YStart = " << ystart << " [m]" << endl;
713
714 double yend = elptr->getYEnd();
715 *gmsg << "* YEnd = " << yend << " [m]" << endl;
716
717 // initialise, do nothing
718 elptr->initialise(itsBunch_m);
719
720 double BcParameter[8] = {};
721
722 BcParameter[0] = xstart;
723 BcParameter[1] = xend;
724 BcParameter[2] = ystart;
725 BcParameter[3] = yend;
726 BcParameter[4] = 1 ; // width
727
728 buildupFieldList(BcParameter, ElementType::PROBE, elptr);
729}
730
737 *gmsg << "In RBend; L= " << bend.getElementLength() << " however the element is missing " << endl;
738 myElements.push_back(dynamic_cast<RBend*>(bend.clone()));
739}
740
747 *gmsg << "* ----------------------------- RFCavity --------------------------------- * " << endl;
748
749 RFCavity* elptr = dynamic_cast<RFCavity*>(as.clone());
750 myElements.push_back(elptr);
751
752 if ( elptr->getCavityType() != CavityType::SGSW ) {
753 throw OpalException("ParallelCyclotronTracker::visitRFCavity",
754 "\"" + elptr->getCavityTypeString() + "\" is not valid \"TYPE\" for RFCavity.\n"
755 "The ParallelCyclotronTracker can only play with cyclotron type RF system currently...");
756 }
757
758 *gmsg << "* Name = " << elptr->getName() << endl;
759
760 std::string fmfn = elptr->getFieldMapFN();
761 *gmsg << "* RF Field map file = '" << fmfn << "'" << endl;
762
763 double rmin = elptr->getRmin();
764 *gmsg << "* Minimal radius of cavity = " << rmin << " [m]" << endl;
765
766 double rmax = elptr->getRmax();
767 *gmsg << "* Maximal radius of cavity = " << rmax << " [m]" << endl;
768
769 double rff = elptr->getCycFrequency();
770 *gmsg << "* RF frequency (2*pi*f) = " << rff << " [rad/s]" << endl;
771
772 double angle = elptr->getAzimuth();
773 *gmsg << "* Cavity azimuth position = " << angle * Units::rad2deg << " [deg] " << endl;
774
775 double gap = elptr->getGapWidth();
776 *gmsg << "* Cavity gap width = " << gap << " [m] " << endl;
777
778 double pdis = elptr->getPerpenDistance();
779 *gmsg << "* Cavity Shift distance = " << pdis << " [m] " << endl;
780
781 double phi0 = elptr->getPhi0();
782 *gmsg << "* Initial RF phase (t=0) = " << phi0 * Units::rad2deg << " [deg] " << endl;
783
784 /*
785 Setup time dependence and in case of no
786 timedependence use a polynom with a_0 = 1 and a_k = 0, k = 1,2,3.
787 */
788
789 std::shared_ptr<AbstractTimeDependence> freq_atd = nullptr;
790 std::shared_ptr<AbstractTimeDependence> ampl_atd = nullptr;
791 std::shared_ptr<AbstractTimeDependence> phase_atd = nullptr;
792
793 dvector_t unityVec;
794 unityVec.push_back(1.);
795 unityVec.push_back(0.);
796 unityVec.push_back(0.);
797 unityVec.push_back(0.);
798
799 std::string frequencyModelName = elptr->getFrequencyModelName();
800 std::string amplitudeModelName = elptr->getAmplitudeModelName();
801 std::string phaseModelName = elptr->getPhaseModelName();
802
803 if (!frequencyModelName.empty()) {
804 freq_atd = AbstractTimeDependence::getTimeDependence(frequencyModelName);
805 *gmsg << "* Variable frequency RF Model name " << frequencyModelName << endl;
806 } else {
807 freq_atd = std::shared_ptr<AbstractTimeDependence>(new PolynomialTimeDependence(unityVec));
808 }
809
810 if (!amplitudeModelName.empty()) {
811 ampl_atd = AbstractTimeDependence::getTimeDependence(amplitudeModelName);
812 *gmsg << "* Variable amplitude RF Model name " << amplitudeModelName << endl;
813 } else {
814 ampl_atd = std::shared_ptr<AbstractTimeDependence>(new PolynomialTimeDependence(unityVec));
815 }
816
817 if (!phaseModelName.empty()) {
818 phase_atd = AbstractTimeDependence::getTimeDependence(phaseModelName);
819 *gmsg << "* Variable phase RF Model name " << phaseModelName << endl;
820 } else {
821 phase_atd = std::shared_ptr<AbstractTimeDependence>(new PolynomialTimeDependence(unityVec));
822 }
823 // read cavity voltage profile data from file.
824 elptr->initialise(itsBunch_m, freq_atd, ampl_atd, phase_atd);
825
826 double BcParameter[8] = {};
827
828 BcParameter[0] = rmin;
829 BcParameter[1] = rmax;
830 BcParameter[2] = pdis;
831 BcParameter[3] = angle;
832
833 buildupFieldList(BcParameter, ElementType::RFCAVITY, elptr);
834}
835
841 *gmsg << "* ----------------------------- Ring ------------------------------------- *" << endl;
842
843 delete opalRing_m;
844
845 opalRing_m = dynamic_cast<Ring*>(ring.clone());
846
847 myElements.push_back(opalRing_m);
848
850
855
857 throw OpalException("Error in ParallelCyclotronTracker::visitRing",
858 "BEAM_PHIINIT is out of [-180, 180)");
859 }
860
861 referenceZ = 0.0;
862 referencePz = 0.0;
863
866
867 if (referencePtot < 0.0)
868 referencePt *= -1.0;
869
870 sinRefTheta_m = std::sin(referenceTheta);
871 cosRefTheta_m = std::cos(referenceTheta);
872
873 double BcParameter[8] = {}; // zero initialise array
874
876
877 // Finally print some diagnostic
878 *gmsg << "* Initial beam radius = " << referenceR << " [m] " << endl;
879 *gmsg << "* Initial gamma = " << itsReference.getGamma() << endl;
880 *gmsg << "* Initial beta = " << itsReference.getBeta() << endl;
881 *gmsg << "* Total reference momentum = " << referencePtot << " [beta gamma]" << endl;
882 *gmsg << "* Reference azimuthal momentum = " << referencePt << " [beta gamma]" << endl;
883 *gmsg << "* Reference radial momentum = " << referencePr << " [beta gamma]" << endl;
884 *gmsg << "* " << opalRing_m->getSymmetry() << " fold field symmetry " << endl;
885 *gmsg << "* Harmonic number h = " << opalRing_m->getHarmonicNumber() << " " << endl;
886}
887
894 *gmsg << "In SBend; L = " << bend.getElementLength() << " however the element is missing " << endl;
895 myElements.push_back(dynamic_cast<SBend*>(bend.clone()));
896}
897
899 *gmsg << "Adding SBend3D" << endl;
900 if (opalRing_m != nullptr)
902 else
903 throw OpalException("ParallelCyclotronTracker::visitSBend3D",
904 "Need to define a RINGDEFINITION to use SBend3D element");
905}
906
908 *gmsg << "Adding ScalingFFAMagnet" << endl;
909 if (opalRing_m != nullptr) {
910 ScalingFFAMagnet* newBend = bend.clone(); // setup the end field, if required
911 newBend->setupEndField();
912 opalRing_m->appendElement(*newBend);
913 } else {
914 throw OpalException("ParallelCyclotronTracker::visitScalingFFAMagnet",
915 "Need to define a RINGDEFINITION to use ScalingFFAMagnet element");
916 }
917}
918
925 *gmsg << "* ----------------------------- Septum ----------------------------------- *" << endl;
926
927 Septum* elptr = dynamic_cast<Septum*>(sept.clone());
928 myElements.push_back(elptr);
929
930 *gmsg << "* Name = " << elptr->getName() << endl;
931
932 double xstart = elptr->getXStart();
933 *gmsg << "* XStart = " << xstart << " [m]" << endl;
934
935 double xend = elptr->getXEnd();
936 *gmsg << "* XEnd = " << xend << " [m]" << endl;
937
938 double ystart = elptr->getYStart();
939 *gmsg << "* YStart = " << ystart << " [m]" << endl;
940
941 double yend = elptr->getYEnd();
942 *gmsg << "* YEnd = " << yend << " [m]" << endl;
943
944 double width = elptr->getWidth();
945 *gmsg << "* Width = " << width << " [m]" << endl;
946
947 // initialise, do nothing
948 elptr->initialise(itsBunch_m);
949
950 double BcParameter[8] = {};
951
952 BcParameter[0] = xstart;
953 BcParameter[1] = xend;
954 BcParameter[2] = ystart;
955 BcParameter[3] = yend;
956 BcParameter[4] = width;
957
958 buildupFieldList(BcParameter, ElementType::SEPTUM, elptr);
959}
960
967 myElements.push_back(dynamic_cast<Solenoid*>(solenoid.clone()));
968 Component* elptr = *(--myElements.end());
969 if (!elptr->hasAttribute("ELEMEDGE")) {
970 *gmsg << "Solenoid: no position of the element given" << endl;
971 return;
972 }
973}
974
981 *gmsg << "* ----------------------------- Stripper --------------------------------- *" << endl;
982
983 Stripper* elptr = dynamic_cast<Stripper*>(stripper.clone());
984 myElements.push_back(elptr);
985
986 *gmsg << "* Name = " << elptr->getName() << endl;
987
988 double xstart = elptr->getXStart();
989 *gmsg << "* XStart = " << xstart << " [m]" << endl;
990
991 double xend = elptr->getXEnd();
992 *gmsg << "* XEnd = " << xend << " [m]" << endl;
993
994 double ystart = elptr->getYStart();
995 *gmsg << "* YStart = " << ystart << " [m]" << endl;
996
997 double yend = elptr->getYEnd();
998 *gmsg << "* YEnd = " << yend << " [m]" << endl;
999
1000 double opcharge = elptr->getOPCharge();
1001 *gmsg << "* Charge of outcoming particle = +e * " << opcharge << endl;
1002
1003 double opmass = elptr->getOPMass();
1004 *gmsg << "* Mass of the outcoming particle = " << opmass << " [GeV/c^2]" << endl;
1005
1006 bool stop = elptr->getStop();
1007 *gmsg << std::boolalpha
1008 << "* Particles stripped will be deleted after interaction -> "
1009 << stop << endl;
1010
1011 elptr->initialise(itsBunch_m);
1012
1013 double BcParameter[8] = {};
1014
1015 BcParameter[0] = xstart;
1016 BcParameter[1] = xend;
1017 BcParameter[2] = ystart;
1018 BcParameter[3] = yend;
1019 BcParameter[4] = 1; // width
1020 BcParameter[5] = opcharge;
1021 BcParameter[6] = opmass;
1022
1023 buildupFieldList(BcParameter, ElementType::STRIPPER, elptr);
1024}
1025
1032 *gmsg << "* ----------------------------- Vacuum ----------------------------------- *" << endl;
1033
1034 Vacuum* elptr = dynamic_cast<Vacuum*>(vac.clone());
1035 myElements.push_back(elptr);
1036
1037 double BcParameter[8] = {};
1038
1039 std::string gas = elptr->getResidualGasName();
1040 *gmsg << "* Residual gas = " << gas << endl;
1041
1042 double pressure = elptr->getPressure();
1043 if ( std::filesystem::exists(elptr->getPressureMapFN()) ) {
1044 std::string pmfn = elptr->getPressureMapFN();
1045 *gmsg << "* Pressure field map file = '" << pmfn << "'" << endl;
1046 *gmsg << "* Default pressure = " << pressure << " [mbar]" << endl;
1047 } else {
1048 *gmsg << "* Pressure = " << pressure << " [mbar]" << endl;
1049 }
1050 double pscale = elptr->getPScale();
1051
1052 double temperature = elptr->getTemperature();
1053 *gmsg << "* Temperature = " << temperature << " [K]" << endl;
1054
1055 bool stop = elptr->getStop();
1056 *gmsg << std::boolalpha
1057 << "* Particles stripped will be deleted after interaction -> "
1058 << stop << endl;
1059
1060 elptr->initialise(itsBunch_m);
1061
1062 BcParameter[0] = pressure;
1063 BcParameter[1] = pscale;
1064 BcParameter[2] = temperature;
1065
1066 buildupFieldList(BcParameter, ElementType::VACUUM, elptr);
1067}
1068
1075 *gmsg << "Adding Variable RF Cavity" << endl;
1076 if (opalRing_m != nullptr)
1078 else
1079 throw OpalException("ParallelCyclotronTracker::visitVariableRFCavity",
1080 "Need to define a RINGDEFINITION to use VariableRFCavity element");
1081}
1082
1089 (const VariableRFCavityFringeField& cav) {
1090 *gmsg << "Adding Variable RF Cavity with Fringe Field" << endl;
1091 if (opalRing_m != nullptr)
1093 else
1094 throw OpalException("ParallelCyclotronTracker::visitVariableRFCavityFringeField",
1095 "Need to define a RINGDEFINITION to use VariableRFCavity element");
1096}
1097
1104 *gmsg << "Adding Vertical FFA Magnet" << endl;
1105 if (opalRing_m != nullptr)
1107 else
1108 throw OpalException("ParallelCyclotronTracker::visitVerticalFFAMagnet",
1109 "Need to define a RINGDEFINITION to use VerticalFFAMagnet element");
1110}
1111
1112
1120void ParallelCyclotronTracker::buildupFieldList(double BcParameter[], ElementType elementType, Component *elptr) {
1121 beamline_list::iterator sindex;
1122
1123 type_pair *localpair = new type_pair();
1124 localpair->first = elementType;
1125
1126 for (int i = 0; i < 8; i++)
1127 *(((localpair->second).first) + i) = *(BcParameter + i);
1128
1129 (localpair->second).second = elptr;
1130
1131 if (elementType == ElementType::RFCAVITY) {
1133 }
1134
1135 // always put cyclotron as the first element in the list.
1136 if (elementType == ElementType::RING || elementType == ElementType::CYCLOTRON) {
1137 sindex = FieldDimensions.begin();
1138 } else {
1139 sindex = FieldDimensions.end();
1140 }
1141 FieldDimensions.insert(sindex, localpair);
1142}
1143
1150 const FlaggedBeamline* fbl = static_cast<const FlaggedBeamline*>(&bl);
1151 fbl->iterate(*this, false);//*dynamic_cast<BeamlineVisitor *>(this), false);
1152}
1153
1155 int nlp = itsBunch_m->getLocalNum();
1156 int minnlp = 0;
1157 int maxnlp = 111111;
1158 reduce(nlp, minnlp, OpMinAssign());
1159 reduce(nlp, maxnlp, OpMaxAssign());
1160 *gmsg << s << "min local particle number: "<< minnlp << endl;
1161 *gmsg << "* max local particle number: " << maxnlp << endl;
1162}
1163
1164
1166 /*
1167 Initialize common variables and structures
1168 for the integrators
1169 */
1170 if (OpalData::getInstance()->inRestartRun()) {
1172 }
1173
1174 step_m = 0;
1175 restartStep0_m = 0;
1176 turnnumber_m = 1;
1177 azimuth_m = -1.0;
1178 prevAzimuth_m = -1.0;
1179 refLostWarned_m = false;
1180
1181 // Record how many bunches have already been injected. ONLY FOR MPM
1182 if (isMultiBunch())
1183 mbHandler_m->setNumBunch(itsBunch_m->getNumBunch());
1184
1185 itsBeamline->accept(*this);
1186 if (opalRing_m != nullptr)
1188
1189 // Display the selected elements
1190 *gmsg << "* ------------------------------------------------------------------------ *" << endl;
1191 *gmsg << "* The selected Beam line elements are :" << endl;
1192 for (auto fd : FieldDimensions) {
1193 ElementType type = fd->first;
1194 *gmsg << "* -> " << ElementBase::getTypeString(type) << endl;
1195 if (type == ElementType::RFCAVITY) {
1196 RFCavity* cav = static_cast<RFCavity*>((fd->second).second);
1197 CavityCrossData ccd = {cav, cav->getSinAzimuth(), cav->getCosAzimuth(), cav->getPerpenDistance()};
1198 cavCrossDatas_m.push_back(ccd);
1199 } else if ( type == ElementType::CCOLLIMATOR ||
1200 type == ElementType::OUTPUTPLANE ||
1201 type == ElementType::PROBE ||
1202 type == ElementType::SEPTUM ||
1203 type == ElementType::STRIPPER) {
1204 PluginElement* element = static_cast<PluginElement*>((fd->second).second);
1205 pluginElements_m.push_back(element);
1206 }
1207 }
1208 *gmsg << "* ------------------------------------------------------------------------ *" << endl << endl;
1209
1210 // Get BoundaryGeometry that is already initialized
1212 if (bgf_m)
1213 lossDs_m = std::unique_ptr<LossDataSink>(new LossDataSink(bgf_m->getOpalName(),!Options::asciidump));
1214
1215 // External field arrays for dumping
1216 for (int k = 0; k < 6; k++) {
1217 FDext_m[k] = Vector_t({0.0, 0.0, 0.0});
1218 }
1219 extE_m = Vector_t({0.0, 0.0, 0.0});
1220 extB_m = Vector_t({0.0, 0.0, 0.0});
1221 DumpFields::writeFields((((*FieldDimensions.begin())->second).second));
1222 DumpEMFields::writeFields((((*FieldDimensions.begin())->second).second));
1223
1225 this,
1226 std::placeholders::_1,
1227 std::placeholders::_2,
1228 std::placeholders::_3,
1229 std::placeholders::_4);
1230
1231 switch ( stepper_m ) {
1233 *gmsg << "* 2nd order Leap-Frog integrator" << endl;
1234 itsStepper_mp.reset(new LF2<function_t>(func));
1235 break;
1236 }
1238 *gmsg << "* Multiple time stepping (MTS) integrator" << endl;
1239 break;
1240 }
1242 default: {
1243 *gmsg << "* 4th order Runge-Kutta integrator" << endl;
1244 itsStepper_mp.reset(new RK4<function_t>(func));
1245 break;
1246 }
1247 }
1248
1250 MtsTracker();
1251 } else {
1253 }
1254
1255 *gmsg << "* ------------------------------------------------------------------------ *" << endl;
1256 *gmsg << "* Finalizing i.e. write data and close files :" << endl;
1257 for (auto fd : FieldDimensions) {
1258 ((fd->second).second)->finalise();
1259 }
1260 if (bgf_m && lossDs_m) {
1261 lossDs_m->save();
1262 }
1263 *gmsg << "* ------------------------------------------------------------------------ *" << endl;
1264}
1265
1266
1268 /*
1269 * variable unit meaning
1270 * ------------------------------------------------
1271 * t [s] time
1272 * dt [s] time step
1273 * oldReferenceTheta [rad] azimuth angle
1274 * itsBunch_m->R [m] particle position
1275 *
1276 */
1277
1278 double t = 0, dt = 0, oldReferenceTheta = 0;
1279 std::tie(t, dt, oldReferenceTheta) = initializeTracking_m();
1280
1281 int const numSubsteps = std::max(Options::mtsSubsteps, 1);
1282 *gmsg << "* MTS: Number of substeps per step is " << numSubsteps << endl;
1283
1284 double const dt_inner = dt / double(numSubsteps);
1285 *gmsg << "* MTS: The inner time step is therefore " << dt_inner * Units::s2ns << " [ns]" << endl;
1286
1287// int SteptoLastInj = itsBunch_m->getSteptoLastInj();
1288
1289 bool flagTransition = false; // flag to determine when to transit from single-bunch to multi-bunches mode
1290
1291 *gmsg << "* ---------------------- Start tracking ---------------------------------- *" << endl;
1292
1293 if (itsBunch_m->hasFieldSolver()) {
1295 }
1296
1297 for (; (step_m < maxSteps_m) && (itsBunch_m->getTotalNum()>0); step_m++) {
1298
1299 bool finishedTurn = false;
1300
1301 // the turn that the plugin elements get in this step, for the cyclotron's loss records
1303
1304 if (step_m % Options::sptDumpFreq == 0) {
1306 }
1307
1309
1310 // First half kick from space charge force
1311 if (itsBunch_m->hasFieldSolver()) {
1312 kick(0.5 * dt);
1313 }
1314
1315 // Substeps for external field integration
1316 for (int n = 0; n < numSubsteps; ++n) {
1317 borisExternalFields(dt_inner);
1318 }
1319 // bunch injection
1320 // TODO: Where is correct location for this piece of code? Beginning/end of step? Before field solve?
1321 injectBunch(flagTransition);
1322
1323 if ( itsBunch_m->hasFieldSolver() ) {
1325 } else {
1326 // if field solver is not available , only update bunch, to transfer particles between nodes if needed,
1327 // reset parameters such as LocalNum, initialTotalNum_m.
1328 // INFOMSG("No space charge Effects are included"<<endl;);
1329 if ((step_m % Options::repartFreq * 100) == 0) { //TODO: why * 100?
1330 Vector_t const meanP = calcMeanP();
1331 double const phi = calculateAngle(meanP(0), meanP(1)) - 0.5 * Physics::pi;
1332 Vector_t const meanR = calcMeanR();
1333 globalToLocal(itsBunch_m->R, phi, meanR);
1335 repartition();
1336 localToGlobal(itsBunch_m->R, phi, meanR);
1337 }
1338 }
1339
1340 // Second half kick from space charge force
1341 if (itsBunch_m->hasFieldSolver()) {
1342 kick(0.5 * dt);
1343 }
1344 // recalculate bingamma and reset the BinID for each particles according to its current gamma
1345 if (isMultiBunch() && (step_m % Options::rebinFreq == 0)) {
1346 mbHandler_m->updateParticleBins(itsBunch_m);
1347 }
1348
1349 // dump some data after one push in single particle tracking
1350 if ( mode_m == TrackingMode::SINGLE ) {
1351 unsigned int i = 0;
1352
1353 double temp_meanTheta = calculateAngle2(itsBunch_m->R[i](0),
1354 itsBunch_m->R[i](1)); // [-pi, pi]
1355
1357 temp_meanTheta, finishedTurn);
1358
1360 oldReferenceTheta, temp_meanTheta);
1361
1362 oldReferenceTheta = temp_meanTheta;
1363 } else if ( mode_m == TrackingMode::BUNCH ) {
1364 // both for single bunch and multi-bunch
1365 // avoid dump at the first step
1366 // finishedTurn has not been changed in first push
1367 if ( isTurnDone() ) {
1368 ++turnnumber_m;
1369 finishedTurn = true;
1370
1371 *gmsg << endl;
1372 *gmsg << "*** Finished turn " << turnnumber_m - 1
1373 << ", Total number of live particles: "
1374 << itsBunch_m->getTotalNum() << endl;
1376 }
1377
1378 // Recalculate bingamma and reset the BinID for each particles according to its current gamma
1379 if (isMultiBunch() && (step_m % Options::rebinFreq == 0)) {
1380 mbHandler_m->updateParticleBins(itsBunch_m);
1381 }
1382 }
1383
1384 // printing + updating bunch parameters + updating t
1385 update_m(t, dt, finishedTurn);
1386 }
1387
1388 // Some post-integration stuff
1389 *gmsg << endl;
1390 *gmsg << "* ---------------------- DONE TRACKING PARTICLES ------------------------- *" << endl;
1391
1392 //FIXME
1393 dvector_t Ttime = dvector_t();
1394 dvector_t Tdeltr = dvector_t();
1395 dvector_t Tdeltz = dvector_t();
1396 ivector_t TturnNumber = ivector_t();
1397
1398 finalizeTracking_m(Ttime, Tdeltr, Tdeltz, TturnNumber);
1399}
1400
1401
1403 /*
1404 * variable unit meaning
1405 * ------------------------------------------------
1406 * t [s] time
1407 * dt [s] time step
1408 * oldReferenceTheta [rad] azimuth angle
1409 * itsBunch_m->R [m] particle position
1410 *
1411 */
1412 // Generic Tracker that has three modes defined by timeIntegrator_m:
1413 // 0 --- RK-4 (default)
1414 // 1 --- LF-2
1415 // (2 --- MTS ... not yet implemented in generic tracker)
1416 // mbHandler_m->getNumBunch() determines the number of bunches in multibunch mode (MBM, 1 for OFF)
1417 // Total number of particles determines single particle mode (SPM, 1 particle) or
1418 // Static Equilibrium Orbit Mode (SEO, 2 particles)
1419
1420 double t = 0, dt = 0, oldReferenceTheta = 0;
1421 std::tie(t, dt, oldReferenceTheta) = initializeTracking_m();
1422
1423 // If initialTotalNum_m = 2, trigger SEO mode and prepare for transverse tuning calculation
1424 // Where is the IF here? -DW
1425 dvector_t Ttime, Tdeltr, Tdeltz;
1426 ivector_t TturnNumber;
1427
1428 // Apply the plugin elements: probe, collimator, stripper, septum once before first step
1429 bool flagNeedUpdate = applyPluginElements(dt);
1430
1431 // Destroy particles if they are marked as Bin = -1 in the plugin elements
1432 // or out of global aperture
1433 deleteParticle(flagNeedUpdate);
1434
1435 /********************************
1436 * Main integration loop *
1437 ********************************/
1438 *gmsg << endl;
1439 *gmsg << "* ---------------------- Start tracking ---------------------------------- *" << endl;
1440
1441 for (; (step_m < maxSteps_m) && (itsBunch_m->getTotalNum()>0); step_m++) {
1442
1443 bool finishedTurn = false;
1444
1445 // the turn that the plugin elements get in this step, for the cyclotron's loss records
1447
1448 switch (mode_m) {
1449 case TrackingMode::SEO: {
1450 // initialTotalNum_m == 2
1451 seoMode_m(t, dt, finishedTurn, Ttime, Tdeltr, Tdeltz, TturnNumber);
1452 break;
1453 }
1454 case TrackingMode::SINGLE: {
1455 // initialTotalNum_m == 1
1456 singleMode_m(t, dt, finishedTurn, oldReferenceTheta);
1457 break;
1458 }
1459 case TrackingMode::BUNCH: {
1460 // initialTotalNum_m > 2
1461 // Start Tracking for number of particles > 2 (i.e. not single and not SEO mode)
1462 bunchMode_m(t, dt, finishedTurn);
1463 break;
1464 }
1466 default:
1467 throw OpalException("ParallelCyclotronTracker::GenericTracker()",
1468 "No such tracking mode.");
1469 }
1470 }
1471 // Update bunch and some parameters and output some info
1472 update_m(t, dt, finishedTurn);
1473
1474 } // end for: the integration is DONE after maxSteps_m steps or if all particles are lost!
1475
1476 // Some post-integration stuff
1477 *gmsg << endl;
1478 *gmsg << "* ---------------------- DONE TRACKING PARTICLES ------------------------- *" << endl;
1479
1480 finalizeTracking_m(Ttime, Tdeltr, Tdeltz, TturnNumber);
1481}
1482
1483bool ParallelCyclotronTracker::getFieldsAtPoint(const double& t, const size_t& Pindex, Vector_t& Efield, Vector_t& Bfield) {
1484
1485 bool outOfBound = this->computeExternalFields_m(Pindex, t, Efield, Bfield);
1486
1487 // For runs without space charge effects, override this step to save time
1488 if (itsBunch_m->hasFieldSolver()) {
1489
1490 // Don't do for reference particle
1491 if (itsBunch_m->ID[Pindex] != 0) {
1492
1493 // add external Field and self space charge field
1494 Efield += itsBunch_m->Ef[Pindex];
1495 Bfield += itsBunch_m->Bf[Pindex];
1496 }
1497 }
1498
1499 return outOfBound;
1500}
1501
1502
1514 RFCavity* rfcavity, double& Dold) {
1515 bool flag = false;
1516 double sinx = rfcavity->getSinAzimuth();
1517 double cosx = rfcavity->getCosAzimuth();
1518
1519 double PerpenDistance = rfcavity->getPerpenDistance();
1520 double distNew = (Rnew[0] * sinx - Rnew[1] * cosx) - PerpenDistance;
1521 double distOld = (Rold[0] * sinx - Rold[1] * cosx) - PerpenDistance;
1522 if (distOld > 0.0 && distNew <= 0.0) flag = true;
1523 // This parameter is used correct cavity phase
1524 Dold = distOld;
1525 return flag;
1526}
1527
1528bool ParallelCyclotronTracker::RFkick(RFCavity* rfcavity, const double t, const double dt, const int Pindex) {
1529
1530 double radius = std::sqrt(std::pow(itsBunch_m->R[Pindex](0), 2.0) + std::pow(itsBunch_m->R[Pindex](1), 2.0)
1531 - std::pow(rfcavity->getPerpenDistance() , 2.0));
1532 double rmin = rfcavity->getRmin();
1533 double rmax = rfcavity->getRmax();
1534 double nomalRadius = (radius - rmin) / (rmax - rmin);
1535 double tempP[3];
1536 if (nomalRadius <= 1.0 && nomalRadius >= 0.0) {
1537
1538 for (int j = 0; j < 3; j++)
1539 tempP[j] = itsBunch_m->P[Pindex](j); //[px,py,pz] units: dimensionless
1540
1541 // here evaluate voltage and conduct momenta kicking;
1542 rfcavity->getMomentaKick(nomalRadius, tempP, t, dt, itsBunch_m->ID[Pindex], itsBunch_m->getM(), itsBunch_m->getQ()); // t : ns
1543
1544 for (int j = 0; j < 3; j++)
1545 itsBunch_m->P[Pindex](j) = tempP[j];
1546 return true;
1547 }
1548 return false;
1549}
1550
1551
1552struct adder {
1553 adder() : sum(0) {}
1554 double sum;
1555 void operator()(double x) { sum += x; }
1556};
1557
1571 int lastTurn, double& /*nur*/, double& /*nuz*/) {
1572 TUNE_class *tune;
1573
1574 int Ndat = t.size();
1575
1576 /*
1577 remove mean
1578 */
1579 double rsum = for_each(r.begin(), r.end(), adder()).sum;
1580
1581 for (int i = 0; i < Ndat; i++)
1582 r[i] -= rsum;
1583
1584 double zsum = for_each(z.begin(), z.end(), adder()).sum;
1585
1586 for (int i = 0; i < Ndat; i++)
1587 z[i] -= zsum;
1588 double ti = *(t.begin());
1589 double tf = t[t.size()-1];
1590 double T = (tf - ti);
1591
1592 t.clear();
1593 for (int i = 0; i < Ndat; i++) {
1594 t.push_back(i);
1595 }
1596
1597 T = t[Ndat-1];
1598
1599 *gmsg << endl;
1600 *gmsg << "* ************************************* nuR ******************************************* *" << endl;
1601 *gmsg << endl << "* ===> " << Ndat << " data points Ti=" << ti << " Tf= " << tf << " -> T= " << T << endl;
1602
1603 int nhis_lomb = 10;
1604 int stat = 0;
1605 // book tune class
1606 tune = new TUNE_class();
1607 stat = tune->lombAnalysis(t, r, nhis_lomb, T / lastTurn);
1608 if (stat != 0)
1609 *gmsg << "* TUNE: Lomb analysis failed" << endl;
1610 *gmsg << "* ************************************************************************************* *" << endl;
1611
1612 delete tune;
1613 tune = nullptr;
1614 // FIXME: FixMe: need to come from the inputfile
1615 nhis_lomb = 100;
1616
1617 if (zsum != 0.0) {
1618
1619 *gmsg << endl;
1620 *gmsg << "* ************************************* nuZ ******************************************* *" << endl;
1621 *gmsg << endl << "* ===> " << Ndat << " data points Ti=" << ti << " Tf= " << tf << " -> T= " << T << endl;
1622
1623 // book tune class
1624 tune = new TUNE_class();
1625 stat = tune->lombAnalysis(t, z, nhis_lomb, T / lastTurn);
1626 if (stat != 0)
1627 *gmsg << "* TUNE: Lomb analysis failed" << endl;
1628 *gmsg << "* ************************************************************************************* *" << endl;
1629
1630 delete tune;
1631 tune = nullptr;
1632 }
1633 return true;
1634}
1635
1636
1638 if (opalRing_m != nullptr)
1639 return opalRing_m->getHarmonicNumber();
1640 Cyclotron* elcycl = dynamic_cast<Cyclotron*>(((*FieldDimensions.begin())->second).second);
1641 if (elcycl != nullptr)
1642 return elcycl->getCyclHarm();
1643 throw OpalException("ParallelCyclotronTracker::getHarmonicNumber()",
1644 std::string("The first item in the FieldDimensions list does not ")
1645 +std::string("seem to be a Ring or a Cyclotron element"));
1646}
1647
1648
1650 Vector_t meanR({0.0, 0.0, 0.0});
1651
1652 for (unsigned int i = 0; i < itsBunch_m->getLocalNum(); ++i) {
1653 // take all particles if bunchNr <= -1
1654 if ( bunchNr > -1 && itsBunch_m->bunchNum[i] != bunchNr)
1655 continue;
1656
1657 for (int d = 0; d < 3; ++d) {
1658 meanR(d) += itsBunch_m->R[i](d);
1659 }
1660 }
1661
1662 reduce(meanR, meanR, OpAddAssign());
1663
1664 size_t n = itsBunch_m->getTotalNum();
1665
1666 if ( bunchNr > -1 )
1667 n = itsBunch_m->getTotalNumPerBunch(bunchNr);
1668
1669 return meanR / Vector_t(n);
1670}
1671
1673 Vector_t meanP({0.0, 0.0, 0.0});
1674
1675 for (unsigned int i = 0; i < itsBunch_m->getLocalNum(); ++i) {
1676 for (int d = 0; d < 3; ++d) {
1677 meanP(d) += itsBunch_m->P[i](d);
1678 }
1679 }
1680
1681 reduce(meanP, meanP, OpAddAssign());
1682 return meanP / Vector_t(itsBunch_m->getTotalNum());
1683}
1684
1693
1695 double phi, Vector_t const translationToGlobal) {
1697 particleVectors -= translationToGlobal;
1698
1699 rotation_m(0,0) = std::cos(phi);
1700 rotation_m(0,1) = std::sin(phi);
1701 rotation_m(0,2) = 0;
1702 rotation_m(1,0) = -std::sin(phi);
1703 rotation_m(1,1) = std::cos(phi);
1704 rotation_m(1,2) = 0;
1705 rotation_m(2,0) = 0;
1706 rotation_m(2,1) = 0;
1707 rotation_m(2,2) = 1;
1708
1709 for (unsigned int i = 0; i < itsBunch_m->getLocalNum(); ++i) {
1710 particleVectors[i] = prod_boost_vector(rotation_m, particleVectors[i]);
1711 }
1713}
1714
1716 double phi, Vector_t const translationToGlobal) {
1718
1719 rotation_m(0,0) = std::cos(phi);
1720 rotation_m(0,1) = -std::sin(phi);
1721 rotation_m(0,2) = 0;
1722 rotation_m(1,0) = std::sin(phi);
1723 rotation_m(1,1) = std::cos(phi);
1724 rotation_m(1,2) = 0;
1725 rotation_m(2,0) = 0;
1726 rotation_m(2,1) = 0;
1727 rotation_m(2,2) = 1;
1728
1729 for (unsigned int i = 0; i < itsBunch_m->getLocalNum(); ++i) {
1730 particleVectors[i] = prod_boost_vector(rotation_m, particleVectors[i]);
1731 }
1732
1733 particleVectors += translationToGlobal;
1735}
1736
1737
1739 Quaternion_t const quaternion,
1740 Vector_t const meanR) {
1742
1743 // Translation from global to local
1744 particleVectors -= meanR;
1745
1746 // Rotation to align P_mean with x-axis
1747 rotateWithQuaternion(particleVectors, quaternion);
1749}
1750
1752 Quaternion_t const quaternion,
1753 Vector_t const meanR) {
1755 // Reverse the quaternion by multiplying the axis components (x,y,z) with -1
1756 Quaternion_t reverseQuaternion = quaternion * -1.0;
1757 reverseQuaternion(0) *= -1.0;
1758
1759 // Rotation back to original P_mean direction
1760 rotateWithQuaternion(particleVectors, reverseQuaternion);
1761
1762 // Translation from local to global
1763 particleVectors += meanR;
1765}
1766
1768 double const phi,
1769 double const psi,
1770 Vector_t const meanR) {
1771
1773 //double const tolerance = 1.0e-4; // TODO What is a good angle threshold? -DW
1774
1775 // Translation from global to local
1776 particleVectors -= meanR;
1777
1778 // Rotation to align P_mean with x-axis
1779 rotateAroundZ(particleVectors, phi);
1780
1781 // If theta is large enough (i.e. there is significant momentum in z direction)
1782 // rotate around x-axis next
1783 //if (fabs(psi) > tolerance)
1784 rotateAroundX(particleVectors, psi);
1786}
1787
1789 double const phi,
1790 double const psi,
1791 Vector_t const meanR) {
1792
1794 //double const tolerance = 1.0e-4; // TODO What is a good angle threshold? -DW
1795
1796 // Translation from global to local
1797 myVector -= meanR;
1798
1799 // Rotation to align P_mean with x-axis
1800 rotateAroundZ(myVector, phi);
1801
1802 // If theta is large enough (i.e. there is significant momentum in z direction)
1803 // rotate around x-axis next
1804 //if (fabs(psi) > tolerance)
1805 rotateAroundX(myVector, psi);
1807}
1808
1810 double const phi,
1811 double const psi,
1812 Vector_t const meanR) {
1813
1815 //double const tolerance = 1.0e-4; // TODO What is a good angle threshold? -DW
1816
1817 // If theta is large enough (i.e. there is significant momentum in z direction)
1818 // rotate back around x-axis next
1819 //if (fabs(psi) > tolerance)
1820 rotateAroundX(particleVectors, -psi);
1821
1822 // Rotation to align P_mean with x-axis
1823 rotateAroundZ(particleVectors, -phi);
1824
1825 // Translation from local to global
1826 particleVectors += meanR;
1828}
1829
1831 double const phi,
1832 double const psi,
1833 Vector_t const meanR) {
1834
1836 //double const tolerance = 1.0e-4; // TODO What is a good angle threshold? -DW
1837
1838 // If theta is large enough (i.e. there is significant momentum in z direction)
1839 // rotate back around x-axis next
1840 //if (fabs(psi) > tolerance)
1841 rotateAroundX(myVector, -psi);
1842
1843 // Rotation to align P_mean with x-axis
1844 rotateAroundZ(myVector, -phi);
1845
1846 // Translation from local to global
1847 myVector += meanR;
1849}
1850
1852
1853 Vector_t const quaternionVectorComponent = Vector_t({quaternion(1), quaternion(2), quaternion(3)});
1854 double const quaternionScalarComponent = quaternion(0);
1855
1856 for (unsigned int i = 0; i < itsBunch_m->getLocalNum(); ++i) {
1857
1858 particleVectors[i] = 2.0f * dot(quaternionVectorComponent, particleVectors[i]) * quaternionVectorComponent +
1859 (quaternionScalarComponent * quaternionScalarComponent -
1860 dot(quaternionVectorComponent, quaternionVectorComponent)) * particleVectors[i] + 2.0f *
1861 quaternionScalarComponent * cross(quaternionVectorComponent, particleVectors[i]);
1862 }
1863}
1864
1866
1867 double tolerance = 1.0e-10;
1868 double length2 = dot(quaternion, quaternion);
1869
1870 if (std::abs(length2) > tolerance && std::abs(length2 - 1.0f) > tolerance) {
1871
1872 double length = std::sqrt(length2);
1873 quaternion /= length;
1874 }
1875}
1876
1878
1879 double tolerance = 1.0e-10;
1880 double length2 = dot(vector, vector);
1881
1882 if (std::abs(length2) > tolerance && std::abs(length2 - 1.0f) > tolerance) {
1883
1884 double length = std::sqrt(length2);
1885 vector /= length;
1886 }
1887}
1888
1889inline void ParallelCyclotronTracker::rotateAroundZ(ParticleAttrib<Vector_t>& particleVectors, double const phi) {
1890 // Clockwise rotation of particles 'particleVectors' by 'phi' around Z axis
1891
1892 rotation_m(0,0) = std::cos(phi);
1893 rotation_m(0,1) = std::sin(phi);
1894 rotation_m(0,2) = 0;
1895 rotation_m(1,0) = -std::sin(phi);
1896 rotation_m(1,1) = std::cos(phi);
1897 rotation_m(1,2) = 0;
1898 rotation_m(2,0) = 0;
1899 rotation_m(2,1) = 0;
1900 rotation_m(2,2) = 1;
1901
1902 for (unsigned int i = 0; i < itsBunch_m->getLocalNum(); ++i) {
1903 particleVectors[i] = prod_boost_vector(rotation_m, particleVectors[i]);
1904 }
1905}
1906
1907inline void ParallelCyclotronTracker::rotateAroundZ(Vector_t& myVector, double const phi) {
1908 // Clockwise rotation of single vector 'myVector' by 'phi' around Z axis
1909
1910 rotation_m(0,0) = std::cos(phi);
1911 rotation_m(0,1) = std::sin(phi);
1912 rotation_m(0,2) = 0;
1913 rotation_m(1,0) = -std::sin(phi);
1914 rotation_m(1,1) = std::cos(phi);
1915 rotation_m(1,2) = 0;
1916 rotation_m(2,0) = 0;
1917 rotation_m(2,1) = 0;
1918 rotation_m(2,2) = 1;
1919
1920 myVector = prod_boost_vector(rotation_m, myVector);
1921}
1922
1923inline void ParallelCyclotronTracker::rotateAroundX(ParticleAttrib<Vector_t>& particleVectors, double const psi) {
1924 // Clockwise rotation of particles 'particleVectors' by 'psi' around X axis
1925
1926 rotation_m(0,0) = 1;
1927 rotation_m(0,1) = 0;
1928 rotation_m(0,2) = 0;
1929 rotation_m(1,0) = 0;
1930 rotation_m(1,1) = std::cos(psi);
1931 rotation_m(1,2) = std::sin(psi);
1932 rotation_m(2,0) = 0;
1933 rotation_m(2,1) = -std::sin(psi);
1934 rotation_m(2,2) = std::cos(psi);
1935
1936 for (unsigned int i = 0; i < itsBunch_m->getLocalNum(); ++i) {
1937 particleVectors[i] = prod_boost_vector(rotation_m, particleVectors[i]);
1938 }
1939}
1940
1941inline void ParallelCyclotronTracker::rotateAroundX(Vector_t& myVector, double const psi) {
1942 // Clockwise rotation of single vector 'myVector' by 'psi' around X axis
1943
1944 rotation_m(0,0) = 1;
1945 rotation_m(0,1) = 0;
1946 rotation_m(0,2) = 0;
1947 rotation_m(1,0) = 0;
1948 rotation_m(1,1) = std::cos(psi);
1949 rotation_m(1,2) = std::sin(psi);
1950 rotation_m(2,0) = 0;
1951 rotation_m(2,1) = -std::sin(psi);
1952 rotation_m(2,2) = std::cos(psi);
1953
1954 myVector = prod_boost_vector(rotation_m, myVector);
1955}
1956
1958 // four vector (w,x,y,z) of the quaternion of P_mean with the positive x-axis
1959
1960 normalizeVector(u);
1961 normalizeVector(v);
1962
1963 double k_cos_theta = dot(u, v);
1964 double k = std::sqrt(dot(u, u) * dot(v, v));
1965 double tolerance1 = 1.0e-5;
1966 double tolerance2 = 1.0e-8;
1967 Vector_t resultVectorComponent;
1968
1969 if (std::abs(k_cos_theta / k + 1.0) < tolerance1) {
1970 // u and v are almost exactly antiparallel so we need to do
1971 // 180 degree rotation around any vector orthogonal to u
1972
1973 resultVectorComponent = cross(u, xaxis);
1974
1975 // If by chance u is parallel to xaxis, use zaxis instead
1976 if (dot(resultVectorComponent, resultVectorComponent) < tolerance2) {
1977 resultVectorComponent = cross(u, zaxis);
1978 }
1979
1980 double halfAngle = 0.5 * Physics::pi;
1981 double sinHalfAngle = std::sin(halfAngle);
1982
1983 resultVectorComponent *= sinHalfAngle;
1984
1985 k = 0.0;
1986 k_cos_theta = std::cos(halfAngle);
1987
1988 } else {
1989 resultVectorComponent = cross(u, v);
1990 }
1991
1992 quaternion(0) = k_cos_theta + k;
1993 quaternion(1) = resultVectorComponent(0);
1994 quaternion(2) = resultVectorComponent(1);
1995 quaternion(3) = resultVectorComponent(2);
1996
1997 normalizeQuaternion(quaternion);
1998}
1999
2000
2002
2004
2005 bool flagNeedUpdate = false;
2006 for (unsigned int i = 0; i < itsBunch_m->getLocalNum(); ++i) {
2007
2008 Vector_t const oldR = itsBunch_m->R[i];
2009 double const gamma = Util::getGamma(itsBunch_m->P[i]);
2010 double const c_gamma = Physics::c / gamma;
2011 Vector_t const v = itsBunch_m->P[i] * c_gamma;
2012
2013 itsBunch_m->R[i] += h * v;
2014
2015 for (const auto & ccd : cavCrossDatas_m) {
2016 double const distNew = (itsBunch_m->R[i][0] * ccd.sinAzimuth - itsBunch_m->R[i][1] * ccd.cosAzimuth) - ccd.perpenDistance;
2017 bool tagCrossing = false;
2018 double distOld;
2019 if (distNew <= 0.0) {
2020 distOld = (oldR[0] * ccd.sinAzimuth - oldR[1] * ccd.cosAzimuth) - ccd.perpenDistance;
2021 if (distOld > 0.0) tagCrossing = true;
2022 }
2023 if (tagCrossing) {
2024 double const dt1 = distOld / euclidean_norm(v);
2025 double const dt2 = h - dt1;
2026
2027 // Re-track particle from the old position to cavity gap point
2028 itsBunch_m->R[i] = oldR + dt1 * v;
2029
2030 // Momentum kick
2031 RFkick(ccd.cavity, itsBunch_m->getT(), dt1, i);
2032
2033 itsBunch_m->R[i] += dt2 * itsBunch_m->P[i] * c_gamma;
2034 }
2035 }
2036 flagNeedUpdate |= (itsBunch_m->Bin[i] < 0);
2037 }
2038
2040 return flagNeedUpdate;
2041}
2042
2043
2046
2047 bool flagNeedUpdate = false;
2048 BorisPusher pusher;
2049 double const q = itsBunch_m->Q[0] / Physics::q_e; // For now all particles have the same charge
2050 double const M = itsBunch_m->M[0] * Units::GeV2eV; // For now all particles have the same rest energy
2051
2052 for (unsigned int i = 0; i < itsBunch_m->getLocalNum(); ++i) {
2053
2054 pusher.kick(itsBunch_m->R[i], itsBunch_m->P[i],
2055 itsBunch_m->Ef[i], itsBunch_m->Bf[i],
2056 h, M, q);
2057 flagNeedUpdate |= (itsBunch_m->Bin[i] < 0);
2058 }
2060 return flagNeedUpdate;
2061}
2062
2063
2065
2066 // push particles for first half step
2067 bool flagNeedUpdate = push(0.5 * h);
2068
2069 // Evaluate external fields
2071 for (unsigned int i = 0; i < itsBunch_m->getLocalNum(); ++i) {
2072
2073 itsBunch_m->Ef[i] = Vector_t({0.0, 0.0, 0.0});
2074 itsBunch_m->Bf[i] = Vector_t({0.0, 0.0, 0.0});
2075
2077 itsBunch_m->Ef[i], itsBunch_m->Bf[i]);
2078 }
2080
2081 // Kick particles for full step
2082 flagNeedUpdate |= kick(h);
2083
2084 // push particles for second half step
2085 flagNeedUpdate |= push(0.5 * h);
2086
2087 // apply the plugin elements: probe, collimator, stripper, septum
2088 flagNeedUpdate |= applyPluginElements(h);
2089 // destroy particles if they are marked as Bin=-1 in the plugin elements or out of global aperture
2090 deleteParticle(flagNeedUpdate);
2091}
2092
2093
2096
2097 for (beamline_list::iterator sindex = ++(FieldDimensions.begin()); sindex != FieldDimensions.end(); ++sindex) {
2098 if (((*sindex)->first) == ElementType::VACUUM) {
2099 Vacuum* vac = static_cast<Vacuum*>(((*sindex)->second).second);
2101 }
2102 }
2103
2104 bool flag = false;
2105 for (PluginElement* element : pluginElements_m) {
2106 bool tmp = element->check(itsBunch_m,
2108 itsBunch_m->getT(),
2109 dt);
2110 flag |= tmp;
2111
2112 if ( tmp ) {
2114 *gmsg << "* Total number of particles after PluginElement= "
2115 << itsBunch_m->getTotalNum() << endl;
2116 }
2117 }
2118
2120 return flag;
2121}
2122
2125 // Update immediately if any particles are lost during this step
2126
2127 if ((step_m + 1) % Options::delPartFreq != 0) {
2129 return false;
2130 }
2131
2132 allreduce(flagNeedUpdate, 1, std::logical_or<bool>());
2133
2134 if (flagNeedUpdate) {
2135 short bunchCount = itsBunch_m->getNumBunch();
2136 std::vector<size_t> locLostParticleNum(bunchCount, 0);
2137
2138 const int leb = itsBunch_m->getLastemittedBin();
2139 std::unique_ptr<size_t[]> localBinCount;
2140
2141 if ( isMultiBunch() ) {
2142 localBinCount = std::unique_ptr<size_t[]>(new size_t[leb]);
2143 for (int i = 0; i < leb; ++i)
2144 localBinCount[i] = 0;
2145 }
2146
2147 for (unsigned int i = 0; i < itsBunch_m->getLocalNum(); i++) {
2148 if (itsBunch_m->Bin[i] < 0) {
2149 ++locLostParticleNum[itsBunch_m->bunchNum[i]];
2150 itsBunch_m->destroy(1, i);
2151 } else if ( isMultiBunch() ) {
2152 /* we need to count the local number of particles
2153 * per energy bin
2154 */
2155 ++localBinCount[itsBunch_m->Bin[i]];
2156 }
2157 }
2158
2159 if ( isMultiBunch() ) {
2160 // set the local bin count
2161 for (int i = 0; i < leb; ++i) {
2162 itsBunch_m->setLocalBinCount(localBinCount[i], i);
2163 }
2164 }
2165
2166 std::vector<size_t> localnum(bunchCount + 1);
2167 for (size_t i = 0; i < localnum.size() - 1; ++i) {
2168 localnum[i] = itsBunch_m->getLocalNumPerBunch(i) - locLostParticleNum[i];
2169 itsBunch_m->setLocalNumPerBunch(localnum[i], i);
2170 }
2171
2172 /* We need to destroy the particles now
2173 * before we compute the means. We also
2174 * have to update the total number of particles
2175 * otherwise the statistics are wrong.
2176 */
2178
2179 /* total number of particles of individual bunches
2180 * last index of vector contains total number over all
2181 * bunches, used as a check
2182 */
2183 std::vector<size_t> totalnum(bunchCount + 1);
2184 localnum[bunchCount] = itsBunch_m->getLocalNum();
2185
2186 allreduce(localnum.data(), totalnum.data(), localnum.size(), std::plus<size_t>());
2187 itsBunch_m->setTotalNum(totalnum[bunchCount]);
2188
2189 for (short i = 0; i < bunchCount; ++i) {
2190 itsBunch_m->setTotalNumPerBunch(totalnum[i], i);
2191 }
2192
2193 size_t sum = std::accumulate(totalnum.begin(),
2194 totalnum.end() - 1, 0);
2195
2196 if ( sum != totalnum[bunchCount] ) {
2197 throw OpalException("ParallelCyclotronTracker::deleteParticle()",
2198 "Total number of particles " + std::to_string(totalnum[bunchCount]) +
2199 " != " + std::to_string(sum) + " (sum over all bunches)");
2200 }
2201
2202 size_t globLostParticleNum = 0;
2203 size_t locNumLost = std::accumulate(locLostParticleNum.begin(),
2204 locLostParticleNum.end(), 0);
2205
2206 reduce(locNumLost, globLostParticleNum, 1, std::plus<size_t>());
2207
2208 if ( globLostParticleNum > 0 ) {
2209 *gmsg << level3 << "At step " << step_m
2210 << ", lost " << globLostParticleNum << " particles" << endl;
2211 }
2212
2213 if (totalnum[bunchCount] == 0) {
2215 return flagNeedUpdate;
2216 }
2217
2218 Vector_t const meanR = calcMeanR();
2219 Vector_t const meanP = calcMeanP();
2220
2221 // Bunch (local) azimuth at meanR w.r.t. y-axis
2222 double const phi = calculateAngle(meanP(0), meanP(1)) - 0.5 * Physics::pi;
2223
2224 // Bunch (local) elevation at meanR w.r.t. xy plane
2225 double const psi = 0.5 * Physics::pi - std::acos(meanP(2) / euclidean_norm(meanP));
2226
2227 // For statistics data, the bunch is transformed into a local coordinate system
2228 // with meanP in direction of y-axis -DW
2229 globalToLocal(itsBunch_m->R, phi, psi, meanR);
2230 globalToLocal(itsBunch_m->P, phi, psi, Vector_t(0.0)); // P should be rotated, but not shifted
2231
2232 // Now destroy particles and update pertinent parameters in local frame
2233 // Note that update() will be called within boundp() -DW
2234 itsBunch_m->boundp();
2235 //itsBunch_m->update();
2236
2238
2239 localToGlobal(itsBunch_m->R, phi, psi, meanR);
2240 localToGlobal(itsBunch_m->P, phi, psi, Vector_t(0.0));
2241
2242 // If particles were deleted, recalculate bingamma and reset BinID for remaining particles
2243 if ( isMultiBunch() )
2244 mbHandler_m->updateParticleBins(itsBunch_m);
2245 }
2246
2248 return flagNeedUpdate;
2249}
2250
2252
2253 std::string f = OpalData::getInstance()->getInputBasename() + std::string("-trackOrbit.dat");
2254
2255 outfTrackOrbit_m.setf(std::ios::scientific, std::ios::floatfield);
2256 outfTrackOrbit_m.precision(8);
2257
2258 if (myNode_m == 0) {
2259 if (OpalData::getInstance()->inRestartRun()) {
2260 outfTrackOrbit_m.open(f.c_str(), std::ios::app);
2261 outfTrackOrbit_m << "# Restart at integration step " << itsBunch_m->getLocalTrackStep() << std::endl;
2262 } else {
2263 outfTrackOrbit_m.open(f.c_str());
2264 outfTrackOrbit_m << "# The six-dimensional phase space data in the global Cartesian coordinates" << std::endl;
2265 outfTrackOrbit_m << "# Part. ID x [m] beta_x*gamma y [m] beta_y*gamma z [m] beta_z*gamma" << std::endl;
2266 }
2267 }
2268}
2269
2271
2272 if (!OpalData::getInstance()->inRestartRun()) {
2273 // Start a new run (no restart)
2274
2275 double const initialReferenceTheta = referenceTheta;
2276
2277 // TODO: Replace with TracerParticle
2278 // Force the initial phase space values of the particle with ID = 0 to zero,
2279 // to set it as a reference particle.
2280 if (initialTotalNum_m > 2) {
2281 for (size_t i = 0; i < initialLocalNum_m; ++i) {
2282 if (itsBunch_m->ID[i] == 0) {
2283 itsBunch_m->R[i] = Vector_t(0.0);
2284 itsBunch_m->P[i] = Vector_t(0.0);
2285 }
2286 }
2287 }
2288
2289 // Initialize global R
2290 Vector_t const initMeanR = Vector_t({referenceR * cosRefTheta_m,
2292 referenceZ});
2293
2294 localToGlobal(itsBunch_m->R, initialReferenceTheta, initMeanR);
2295
2296 // Initialize global P (Cartesian, but input P_ref is in Pr, Ptheta, Pz,
2297 // so translation has to be done before the rotation this once)
2298 // Cave: In the local frame, the positive y-axis is the direction of movement -DW
2299 for (size_t i = 0; i < initialLocalNum_m; ++i) {
2300 itsBunch_m->P[i](0) += referencePr;
2301 itsBunch_m->P[i](1) += referencePt;
2302 itsBunch_m->P[i](2) += referencePz;
2303 }
2304
2305 // Out of the three coordinates of meanR (R, Theta, Z) only the angle
2306 // changes the momentum vector...
2307 double angle = initialReferenceTheta + beamInitialRotation;
2308 localToGlobal(itsBunch_m->P, angle);
2309
2311 if (distType == DistributionType::FROMFILE) {
2313 }
2314
2315 // Initialize the bin number of the first bunch to 0
2316 for (size_t i = 0; i < initialLocalNum_m; ++i) {
2317 itsBunch_m->Bin[i] = 0;
2318 }
2319
2320 // Set time step per particle
2321 setTimeStep();
2322
2323 // Backup initial distribution if multi bunch mode
2324 if ((initialTotalNum_m > 2) && isMultiBunch() && mbHandler_m->isForceMode()) {
2325 mbHandler_m->saveBunch(itsBunch_m);
2326 }
2327
2328 // Else: Restart from the distribution in the h5 file
2329 } else {
2330
2331 // Do a local frame restart (we have already checked that the old h5 file was saved in local
2332 // frame as well).
2334
2335 *gmsg << "* Restart in the local frame" << endl;
2336
2337 Vector_t const initMeanR = Vector_t({referenceR * cosRefTheta_m,
2339 referenceZ});
2340
2341 // Do the transformations
2344
2345 // Initialize the bin number of the first bunch to 0
2346 for (size_t i = 0; i < initialLocalNum_m; ++i) {
2347 itsBunch_m->Bin[i] = 0;
2348 }
2349
2350 // Or do a global frame restart (no transformations necessary)
2351 } else {
2352 *gmsg << "* Restart in the global frame" << endl;
2353 }
2354
2355 // continue the path length read from the h5 file
2357 }
2358
2359 // set the number of particles per bunch
2361
2362 // ------------ Get some Values ---------------------------------------------------------- //
2363 Vector_t const meanR = calcMeanR();
2364 Vector_t const meanP = calcMeanP();
2365
2366 // Bunch (local) azimuth at meanR w.r.t. y-axis
2367 double const phi = calculateAngle(meanP(0), meanP(1)) - 0.5 * Physics::pi;
2368
2369 // Bunch (local) elevation at meanR w.r.t. xy plane
2370 double const psi = 0.5 * Physics::pi - std::acos(meanP(2) / euclidean_norm(meanP));
2371
2372 double radius = std::sqrt(meanR[0] * meanR[0] + meanR[1] * meanR[1]);
2373
2374 if ( isMultiBunch() ) {
2375 mbHandler_m->setRadiusTurns(radius);
2376 }
2377
2378 // Do boundp and repartition in the local frame at beginning of this run
2379 globalToLocal(itsBunch_m->R, phi, psi, meanR);
2380 globalToLocal(itsBunch_m->P, phi, psi); // P should be rotated, but not shifted
2381
2382 itsBunch_m->boundp();
2383
2384 checkNumPart(std::string("\n* Before repartition: "));
2385 repartition();
2386 checkNumPart(std::string("\n* After repartition: "));
2387
2389
2390 *gmsg << endl << "* *********************** Bunch information in local frame: ************************";
2391 *gmsg << *itsBunch_m << endl;
2392
2393 localToGlobal(itsBunch_m->R, phi, psi, meanR);
2394 localToGlobal(itsBunch_m->P, phi, psi);
2395
2396 // Save initial distribution if not a restart
2397 if (!OpalData::getInstance()->inRestartRun()) {
2398 step_m -= 1;
2399
2402
2403 step_m += 1;
2404 }
2405
2406 // Print out the Bunch information at beginning of the run.
2408
2409 // multi-bunch simulation only
2411
2412 *gmsg << endl << "* *********************** Bunch information in global frame: ***********************";
2413 *gmsg << *itsBunch_m << endl;
2414}
2415
2417 for (size_t i = 0; i < initialLocalNum_m; ++i) {
2418 itsBunch_m->dt[i] = itsBunch_m->getdT();
2419 }
2420}
2421
2423
2424 double pTotalMean = 0.0;
2425 for (size_t i = 0; i < initialLocalNum_m; ++i) {
2426 pTotalMean += euclidean_norm(itsBunch_m->P[i]);
2427 }
2428
2429 allreduce(pTotalMean, 1, std::plus<double>());
2430
2431 pTotalMean /= initialTotalNum_m;
2432
2433 double tolerance = itsBunch_m->getMomentumTolerance();
2434 if (tolerance > 0 &&
2435 std::abs(pTotalMean - referencePtot) / pTotalMean > tolerance) {
2436 throw OpalException("ParallelCyclotronTracker::checkFileMomentum",
2437 "The total momentum of the particle distribution\n"
2438 "in the global reference frame: " +
2439 std::to_string(pTotalMean) + ",\n"
2440 "is different from the momentum given\n"
2441 "in the \"BEAM\" command: " +
2442 std::to_string(referencePtot) + ".\n"
2443 "In Opal-cycl the initial distribution\n"
2444 "is specified in the local reference frame.\n"
2445 "When using a \"FROMFILE\" type distribution, the momentum \n"
2446 "must be the same as the specified in the \"BEAM\" command,\n"
2447 "which is in global reference frame.");
2448 }
2449}
2450
2451
2452//TODO: This can be completely rewritten with TracerParticle -DW
2455
2456 if (Ippl::getNodes() > 1 ) {
2457
2458 double x;
2459 int id;
2460 dvector_t tmpr;
2461 ivector_t tmpi;
2462
2464
2465 // for all nodes, find the location of particle with ID = 0 & 1 in bunch containers
2466 int found[2] = {-1, -1};
2467 int counter = 0;
2468
2469 for (size_t i = 0; i < itsBunch_m->getLocalNum(); ++i) {
2470 if (itsBunch_m->ID[i] == 0) {
2471 found[counter] = i;
2472 counter++;
2473 }
2474 if (itsBunch_m->ID[i] == 1) {
2475 found[counter] = i;
2476 counter++;
2477 }
2478 }
2479
2480 if (myNode_m == 0) {
2481 int notReceived = Ippl::getNodes() - 1;
2482 int numberOfPart = 0;
2483 // receive other nodes
2484 while(notReceived > 0) {
2485
2486 int node = COMM_ANY_NODE;
2487 Message *rmsg = Ippl::Comm->receive_block(node, tag);
2488
2489 if (rmsg == nullptr)
2490 ERRORMSG("Could not receive from client nodes in main." << endl);
2491
2492 --notReceived;
2493
2494 rmsg->get(&numberOfPart);
2495
2496 for (int i = 0; i < numberOfPart; ++i) {
2497 rmsg->get(&id);
2498 tmpi.push_back(id);
2499 for (int ii = 0; ii < 6; ii++) {
2500 rmsg->get(&x);
2501 tmpr.push_back(x);
2502 }
2503 }
2504 delete rmsg;
2505 }
2506 // own node
2507 for (int i = 0; i < counter; ++i) {
2508
2509 tmpi.push_back(itsBunch_m->ID[found[i]]);
2510
2511 for (int j = 0; j < 3; ++j) {
2512 tmpr.push_back(itsBunch_m->R[found[i]](j));
2513 tmpr.push_back(itsBunch_m->P[found[i]](j));
2514 }
2515 }
2516 // store
2517 dvector_t::iterator itParameter = tmpr.begin();
2518
2519 for (auto tmpid : tmpi) {
2520
2521 outfTrackOrbit_m << "ID" << tmpid;
2522
2523 for (int ii = 0; ii < 6; ii++) {
2524 outfTrackOrbit_m << " " << *itParameter;
2525 ++itParameter;
2526 }
2527
2528 outfTrackOrbit_m << std::endl;
2529 }
2530 } else {
2531 // for other nodes
2532 Message *smsg = new Message();
2533 smsg->put(counter);
2534
2535 for (int i = 0; i < counter; i++) {
2536
2537 smsg->put(itsBunch_m->ID[found[i]]);
2538
2539 for (int j = 0; j < 3; j++) {
2540 smsg->put(itsBunch_m->R[found[i]](j));
2541 smsg->put(itsBunch_m->P[found[i]](j));
2542 }
2543 }
2544
2545 if (!Ippl::Comm->send(smsg, 0, tag)) {
2546 ERRORMSG("Ippl::Comm->send(smsg, 0, tag) failed " << endl);
2547 }
2548 }
2549
2551
2552 } else {
2553
2554 for (size_t i = 0; i < itsBunch_m->getLocalNum(); i++) {
2555 if (itsBunch_m->ID[i] == 0 || itsBunch_m->ID[i] == 1) {
2556
2557 outfTrackOrbit_m << "ID" << itsBunch_m->ID[i] << " ";
2558 outfTrackOrbit_m << itsBunch_m->R[i](0) << " " << itsBunch_m->P[i](0) << " ";
2559 outfTrackOrbit_m << itsBunch_m->R[i](1) << " " << itsBunch_m->P[i](1) << " ";
2560 outfTrackOrbit_m << itsBunch_m->R[i](2) << " " << itsBunch_m->P[i](2) << std::endl;
2561 }
2562 }
2563 }
2564
2566}
2567
2569
2571
2572 // dump stat file per bunch in case of multi-bunch mode
2573 if (isMultiBunch()) {
2574 double phi = 0.0, psi = 0.0;
2575 Vector_t meanR = calcMeanR();
2576
2577 // Bunch (global) angle w.r.t. x-axis (cylinder coordinates)
2578 double theta = calculateAngle(meanR(0), meanR(1)) * Units::rad2deg;
2579
2580 // fix azimuth_m --> make monotonically increasing
2582
2584
2586 Vector_t meanP = calcMeanP();
2587
2588 // Bunch (local) azimuth at meanR w.r.t. y-axis
2589 phi = calculateAngle(meanP(0), meanP(1)) - 0.5 * Physics::pi;
2590
2591 // Bunch (local) elevation at meanR w.r.t. xy plane
2592 psi = 0.5 * Physics::pi - std::acos(meanP(2) / euclidean_norm(meanP));
2593
2594 // Rotate so Pmean is in positive y direction. No shift, so that normalized emittance and
2595 // unnormalized emittance as well as centroids are calculated correctly in
2596 // PartBunch::calcBeamParameters()
2597 globalToLocal(itsBunch_m->R, phi, psi, meanR);
2598 globalToLocal(itsBunch_m->P, phi, psi);
2599 }
2600
2602
2604 localToGlobal(itsBunch_m->R, phi, psi, meanR);
2605 localToGlobal(itsBunch_m->P, phi, psi);
2606 }
2607
2609 return;
2610 }
2611
2612 // --------------------------------- Get some Values ---------------------------------------- //
2613 double const temp_t = itsBunch_m->getT();
2614 Vector_t meanR;
2615 Vector_t meanP;
2616 // Collective: ref_x..ref_pz, and below the azimuth and the fields at the reference, must
2617 // describe the particle with ID 0, not whatever sits at local index 0 on rank 0. Once ID 0
2618 // is lost they are the centroid, as in bunchDumpPhaseSpaceData().
2619 setRefPartForDump_m(meanR, meanP);
2621 meanR = calcMeanR();
2622 meanP = calcMeanP();
2623 }
2624 double phi = 0;
2625 double psi = 0;
2626
2627 // Bunch (global) angle w.r.t. x-axis (cylinder coordinates)
2628 double azimuth = calculateAngle(meanR(0), meanR(1)) * Units::rad2deg;
2629
2630 // fix azimuth_m --> make monotonically increasing
2632
2633 // -------------- Calculate the external fields at the center of the bunch ----------------- //
2634 beamline_list::iterator DumpSindex = FieldDimensions.begin();
2635
2636 extE_m = Vector_t({0.0, 0.0, 0.0});
2637 extB_m = Vector_t({0.0, 0.0, 0.0});
2638
2639 (((*DumpSindex)->second).second)->apply(meanR, meanP, temp_t, extE_m, extB_m);
2640
2641 // If we are saving in local frame, bunch and fields at the bunch center have to be rotated
2642 // TODO: Make decision if we maybe want to always save statistics data in local frame? -DW
2644 // -------------------- ----------- Do Transformations ---------------------------------- //
2645 // Bunch (local) azimuth at meanR w.r.t. y-axis
2646 phi = calculateAngle(meanP(0), meanP(1)) - 0.5 * Physics::pi;
2647
2648 // Bunch (local) elevation at meanR w.r.t. xy plane
2649 psi = 0.5 * Physics::pi - std::acos(meanP(2) / euclidean_norm(meanP));
2650
2651 // Rotate so Pmean is in positive y direction. No shift, so that normalized emittance and
2652 // unnormalized emittance as well as centroids are calculated correctly in
2653 // PartBunch::calcBeamParameters()
2654 globalToLocal(extB_m, phi, psi);
2655 globalToLocal(extE_m, phi, psi);
2656 globalToLocal(itsBunch_m->R, phi, psi);
2657 globalToLocal(itsBunch_m->P, phi, psi);
2658 }
2659
2660 FDext_m[0] = extB_m * Units::kG2T;
2661 FDext_m[1] = extE_m; // kV/mm? -DW
2662
2663 // Save the stat file, with the time step we integrate with (cf. initializeTracking_m)
2666
2667 // If we are in local mode, transform back after saving
2669 localToGlobal(itsBunch_m->R, phi, psi);
2670 localToGlobal(itsBunch_m->P, phi, psi);
2671 }
2672
2674}
2675
2676
2678 Vector_t& refP) const {
2679 // Which rank holds ID 0 is not fixed: ParticleSpatialLayout::update() and
2680 // BinaryRepartition (REPARTFREQ) move particles between ranks, and within a rank
2681 // the index changes whenever particles are destroyed. So it cannot be found by
2682 // position - only by ID, and only collectively.
2683 //
2684 // Each rank contributes the values if it holds the particle and zeros if it does
2685 // not, plus a count. One sum then gives every rank the same answer, which matters
2686 // because the caller uses the result to define the dump frame on all ranks.
2687 double buf[7] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
2688
2689 for (size_t i = 0; i < itsBunch_m->getLocalNum(); ++ i) {
2690 if (itsBunch_m->ID[i] == 0) {
2691 buf[0] = itsBunch_m->R[i](0);
2692 buf[1] = itsBunch_m->R[i](1);
2693 buf[2] = itsBunch_m->R[i](2);
2694 buf[3] = itsBunch_m->P[i](0);
2695 buf[4] = itsBunch_m->P[i](1);
2696 buf[5] = itsBunch_m->P[i](2);
2697 buf[6] = 1.0;
2698 break;
2699 }
2700 }
2701
2702 allreduce(buf, 7, std::plus<double>());
2703
2704 if (buf[6] != 1.0) {
2705 // 0 means the particle has been lost. Anything else means it is duplicated,
2706 // which would make the sum meaningless - treat both as "not available".
2707 return false;
2708 }
2709
2710 refR = Vector_t({buf[0], buf[1], buf[2]});
2711 refP = Vector_t({buf[3], buf[4], buf[5]});
2712 return true;
2713}
2714
2716 // RefPartR_m/RefPartP_m are written by every rank as H5 step attributes, which must be
2717 // identical on all ranks, and by rank 0 as ref_x..ref_pz in the stat file. They used to
2718 // be set on rank 0 only, every SPTDUMPFREQ steps.
2719 const bool found = getReferenceParticle(refR, refP);
2720
2721 if (!found) {
2722 // No rank holds ID 0 any more - it was lost. The centroid is the only well-defined
2723 // fallback: the last values or another particle would pass for ID 0, and NaN would
2724 // stop OPAL's own SDDS parser (restart, optimiser) from reading the stat file.
2725 // REFSOURCE = 2 marks every such phase-space dump; the message is once per run.
2726 if (!refLostWarned_m) {
2727 refLostWarned_m = true;
2728 *gmsg << "* Warning: at integration step " << step_m + 1
2729 << " the reference particle (ID 0) is no longer in the bunch; falling back to "
2730 << "the bunch mean for the reference values and the dump frame of this and "
2731 << "all later dumps (H5 step attribute REFSOURCE = 2 in the GLOBAL and "
2732 << "REFERENCE dump frames)." << endl;
2733 }
2734 refR = calcMeanR();
2735 refP = calcMeanP();
2736 }
2737
2738 itsBunch_m->RefPartR_m = refR;
2739 itsBunch_m->RefPartP_m = refP;
2740 return found;
2741}
2742
2744 // --------------------------------- Particle dumping --------------------------------------- //
2745 // Note: Don't dump when
2746 // 1. after one turn
2747 // in order to sychronize the dump step for multi-bunch and single bunch for comparison
2748 // with each other during post-process phase.
2749 // ------------------------------------------------------------------------------------------ //
2751
2752 // --------------------------------- Get some Values ---------------------------------------- //
2753 double const temp_t = itsBunch_m->getT();
2754
2755 Vector_t meanR;
2756 Vector_t meanP;
2757
2758 // Collective, and in every mode: the RefPartR/RefPartP step attributes. If ID 0 has been
2759 // lost, meanR/meanP are already the centroid.
2760 const bool haveRef = setRefPartForDump_m(meanR, meanP);
2761
2762 // What the REF* step attributes describe, written as REFSOURCE (see H5Writer.h)
2763 int refSource = haveRef ? 0 : 2;
2764
2765 // in case of multi-bunch mode take always bunch mean (although it takes all bunches)
2767 meanR = calcMeanR();
2768 meanP = calcMeanP();
2769 refSource = 1;
2770 }
2771
2772 double const betagamma_temp = euclidean_norm(meanP);
2773
2774 double const E = itsBunch_m->get_meanKineticEnergy();
2775
2776 // Bunch (global) angle w.r.t. x-axis (cylinder coordinates)
2777 double const theta = std::atan2(meanR(1), meanR(0));
2778
2779 // Bunch (local) azimuth at meanR w.r.t. y-axis
2780 double const phi = calculateAngle(meanP(0), meanP(1)) - 0.5 * Physics::pi;
2781
2782 // Bunch (local) elevation at meanR w.r.t. xy plane
2783 double const psi = 0.5 * Physics::pi - std::acos(meanP(2) / betagamma_temp);
2784
2785 // ---------------- Re-calculate reference values in format of input values ----------------- //
2786 // Position:
2787 // New OPAL 2.0: Init in m (back to mm just for output) -DW
2788 referenceR = computeRadius(meanR); // includes m --> mm conversion
2790 referenceZ = Units::m2mm * meanR(2);
2791
2792 // Momentum in Theta-hat, R-hat, Z-hat coordinates at position meanR:
2793 referencePtot = betagamma_temp;
2794 referencePz = meanP(2);
2795 referencePr = meanP(0) * std::cos(theta) + meanP(1) * std::sin(theta);
2796 referencePt = std::sqrt(referencePtot * referencePtot - \
2798
2799 // ----- Calculate the external fields at the center of the bunch (Cave: Global Frame) ----- //
2800 beamline_list::iterator DumpSindex = FieldDimensions.begin();
2801
2802 extE_m = Vector_t({0.0, 0.0, 0.0});
2803 extB_m = Vector_t({0.0, 0.0, 0.0});
2804
2805 (((*DumpSindex)->second).second)->apply(meanR, meanP, temp_t, extE_m, extB_m);
2806 FDext_m[0] = extB_m * Units::kG2T;
2807 FDext_m[1] = extE_m;
2808
2809 // -------------- If flag psDumpFrame is global, dump bunch in global frame ------------- //
2810 if (Options::psDumpFreq < std::numeric_limits<int>::max() ){
2811 bool dumpLocalFrame = true;
2812 std::string dumpString = "local";
2814 dumpLocalFrame = false;
2815 dumpString = "global";
2816 }
2817
2818 if (dumpLocalFrame == true) {
2819 // ---------------- If flag psDumpFrame is local, dump bunch in local frame ---------------- //
2820
2821 // The bunch is transformed into a local coordinate system with meanP in direction of y-axis
2822 globalToLocal(itsBunch_m->R, phi, psi, meanR);
2823 globalToLocal(itsBunch_m->P, phi, psi); // P should only be rotated
2824
2825 globalToLocal(extB_m, phi, psi);
2826 globalToLocal(extE_m, phi, psi);
2827 }
2828
2829 // The field is evaluated only at the reference point (meanR), so B-ref/E-ref, and
2830 // B-head/E-head and B-tail/E-tail for want of separate samples, all hold that value.
2831 for (int k = 0; k < 6; k += 2) {
2832 FDext_m[k] = extB_m * Units::kG2T;
2833 FDext_m[k + 1] = extE_m;
2834 }
2835
2836 lastDumpedStep_m = itsDataSink->dumpH5(itsBunch_m, // Local and in m
2837 FDext_m, E,
2838 refSource, // what REF* describe
2842 referenceR,
2844 referenceZ,
2845 phi * Units::rad2deg, // P_mean azimuth
2846 // at ref. R/Th/Z
2847 psi * Units::rad2deg, // P_mean elevation
2848 // at ref. R/Th/Z
2849 dumpLocalFrame); // Flag localFrame
2850
2851 if (dumpLocalFrame == true) {
2852 // Return to global frame
2853 localToGlobal(itsBunch_m->R, phi, psi, meanR);
2854 localToGlobal(itsBunch_m->P, phi, psi);
2855 }
2856
2857 // Tell user in which mode we are dumping
2858 // New: no longer dumping for num part < 3, omit phase space dump number info
2859 if (lastDumpedStep_m == -1) {
2860 *gmsg << endl << "* Integration step " << step_m + 1
2861 << " (no phase space dump for <= 2 particles)" << endl;
2862 } else {
2863 *gmsg << endl << "* Phase space dump " << lastDumpedStep_m
2864 << " (" << dumpString << " frame) at integration step " << step_m + 1 << endl;
2865 }
2866 }
2867
2868 // Print dump information on screen
2869 *gmsg << "* T = " << temp_t << " s"
2870 << ", Live Particles: " << itsBunch_m->getTotalNum() << endl;
2871 *gmsg << "* E = " << E << " MeV"
2872 << ", beta * gamma = " << betagamma_temp << endl;
2873 *gmsg << "* Bunch position: R = " << referenceR << " mm"
2874 << ", Theta = " << referenceTheta << " Deg"
2875 << ", Z = " << referenceZ << " mm" << endl;
2876 *gmsg << "* Local Azimuth = " << phi * Units::rad2deg << " Deg"
2877 << ", Local Elevation = " << psi * Units::rad2deg << " Deg" << endl;
2878
2880}
2881
2883 return (step_m > 10) && (((step_m + 1) %setup_m.stepsPerTurn) == 0);
2884}
2885
2887 // The stat-row condition of update_m(), with isTurnDone(), for each step this solve covers.
2888 for (long long step = step_m; step < step_m + setup_m.scSolveFreq; ++step) {
2889 const bool turnDone = (step > 10) && (((step + 1) % setup_m.stepsPerTurn) == 0);
2890 if (((step + 1) % Options::statDumpFreq == 0) || (Options::psDumpEachTurn && turnDone)) {
2891 return true;
2892 }
2893 }
2894 return false;
2895}
2896
2897void ParallelCyclotronTracker::update_m(double& t, const double& dt,
2898 const bool& finishedTurn)
2899{
2900 // Reference parameters
2901 t += dt;
2902
2903 updateTime(dt);
2904
2906 if ((step_m + 1) % 1000 == 0) {
2907 *gmsg << "Step " << step_m + 1 << endl;
2908 }
2909
2910 updatePathLength(dt);
2911
2912 // Here is global frame, don't do itsBunch_m->boundp();
2913
2914 if (itsBunch_m->getTotalNum()>0) {
2915 // Only dump last step if we have particles left.
2916 // Check separately for phase space (ps) and statistics (stat) data dump frequency
2917 if ( mode_m != TrackingMode::SEO && ( ((step_m + 1) % Options::psDumpFreq == 0) ||
2918 (Options::psDumpEachTurn && finishedTurn)))
2919 {
2920 // Write phase space data to h5 file
2922 }
2923
2924 if ( mode_m != TrackingMode::SEO && ( ((step_m + 1) % Options::statDumpFreq == 0) ||
2925 (Options::psDumpEachTurn && finishedTurn)))
2926 {
2927 // Write statistics data to stat file
2929 }
2930 }
2931
2932 if (Options::psDumpEachTurn && finishedTurn) {
2933 for (PluginElement* element : pluginElements_m) {
2934 element->save();
2935 }
2936 }
2937}
2938
2939
2940std::tuple<double, double, double> ParallelCyclotronTracker::initializeTracking_m() {
2941 // Read in some control parameters
2944
2945 // Define 3 special azimuthal angles where dump particle's six parameters
2946 // at each turn into 3 ASCII files. only important in single particle tracking
2947 azimuth_angle_m.resize(3);
2948 azimuth_angle_m[0] = 0.0;
2949 azimuth_angle_m[1] = 22.5 * Units::deg2rad;
2950 azimuth_angle_m[2] = 45.0 * Units::deg2rad;
2951
2952 double harm = getHarmonicNumber();
2953 double dt = itsBunch_m->getdT() * harm;
2954 double t = itsBunch_m->getT();
2955
2956 double oldReferenceTheta = referenceTheta; // init here, reset each step
2957 setup_m.deltaTheta = Physics::pi / (setup_m.stepsPerTurn); // half of the average angle per step
2958
2959 //int stepToLastInj = itsBunch_m->getSteptoLastInj(); // TODO: Do we need this? -DW
2960
2961 // Record how many bunches have already been injected. ONLY FOR MBM
2962 if (isMultiBunch()) {
2963 mbHandler_m->setNumBunch(itsBunch_m->getNumBunch());
2964 }
2965
2967
2968 // Get data from h5 file for restart run and reset current step
2969 // to last step of previous simulation
2970 if (OpalData::getInstance()->inRestartRun()) {
2971
2975
2976 *gmsg << "* Restart at integration step " << restartStep0_m
2977 << " at turn " << turnnumber_m - 1 << endl;
2978
2980 }
2981
2982 setup_m.stepsNextCheck = step_m + setup_m.stepsPerTurn; // Steps to next check for transition
2983
2985
2986 if (isMultiBunch()) {
2987 mbHandler_m->updateParticleBins(itsBunch_m);
2988 }
2989
2990 // --- Output to user --- //
2991 *gmsg << "* Beginning of this run is at t = " << t * Units::s2ns << " [ns]" << endl;
2992 *gmsg << "* The time step is set to dt = " << dt * Units::s2ns << " [ns]" << endl;
2993
2994 if ( isMultiBunch() ) {
2995 *gmsg << "* MBM: Time interval between neighbour bunches is set to "
2996 << setup_m.stepsPerTurn * dt * Units::s2ns << "[ns]" << endl;
2997 *gmsg << "* MBM: The particles energy bin reset frequency is set to "
2999 }
3000
3001 *gmsg << "* Single particle trajectory dump frequency is set to " << Options::sptDumpFreq << endl;
3002 *gmsg << "* The frequency to solve space charge fields is set to " << setup_m.scSolveFreq << endl;
3003 *gmsg << "* The repartition frequency is set to " << Options::repartFreq << endl;
3004
3005 switch ( mode_m ) {
3006 case TrackingMode::SEO: {
3007 *gmsg << endl;
3008 *gmsg << "* ------------------------- STATIC EQUILIBRIUM ORBIT MODE ----------------------------- *" << endl
3009 << "* Instruction: When the total particle number is equal to 2, SEO mode is triggered *" << endl
3010 << "* automatically. This mode does NOT include any RF cavities. The initial distribution *" << endl
3011 << "* file must be specified. In the file the first line is for reference particle and the *" << endl
3012 << "* second line is for off-center particle. The tune is calculated by FFT routines based *" << endl
3013 << "* on these two particles. *" << endl
3014 << "* ---------------- NOTE: SEO MODE ONLY WORKS SERIALLY ON SINGLE NODE ------------------ *" << endl;
3015
3016 if (Ippl::getNodes() != 1)
3017 throw OpalException("Error in ParallelCyclotronTracker::initializeTracking_m",
3018 "SEO MODE ONLY WORKS SERIALLY ON SINGLE NODE");
3019 break;
3020 }
3021 case TrackingMode::SINGLE: {
3022 *gmsg << endl;
3023 *gmsg << "* ------------------------------ SINGLE PARTICLE MODE --------------------------------- *" << endl
3024 << "* Instruction: When the total particle number is equal to 1, single particle mode is *" << endl
3025 << "* triggered automatically. The initial distribution file must be specified which should *" << endl
3026 << "* contain only one line for the single particle *" << endl
3027 << "* ---------NOTE: SINGLE PARTICLE MODE ONLY WORKS SERIALLY ON A SINGLE NODE ------------ *" << endl;
3028
3029 if (Ippl::getNodes() != 1)
3030 throw OpalException("Error in ParallelCyclotronTracker::initializeTracking_m",
3031 "SINGLE PARTICLE MODE ONLY WORKS SERIALLY ON A SINGLE NODE");
3032
3033 // For single particle mode open output files
3035 break;
3036 }
3037 case TrackingMode::BUNCH: {
3038 break;
3039 }
3041 default: {
3042 throw OpalException("ParallelCyclotronTracker::initializeTracking_m()",
3043 "No such tracking mode.");
3044 }
3045 }
3046
3047 return std::make_tuple(t, dt, oldReferenceTheta);
3048}
3049
3050
3052 dvector_t& Tdeltr,
3053 dvector_t& Tdeltz, ivector_t& TturnNumber) {
3054
3055 // gmsg prints on rank 0 only, and ID 0 can be on any rank or lost, so fetch it
3056 // collectively. The dump count and the restart hint do not depend on it.
3057 Vector_t refR, refP;
3058 if (getReferenceParticle(refR, refP)) {
3059 double FinalMomentum2 = std::pow(refP(0), 2.0) + std::pow(refP(1), 2.0) + std::pow(refP(2), 2.0);
3060 double FinalEnergy = (std::sqrt(1.0 + FinalMomentum2) - 1.0) * itsBunch_m->getM() * Units::eV2MeV;
3061 *gmsg << "* Final energy of reference particle = " << FinalEnergy << " [MeV]" << endl;
3062 } else {
3063 *gmsg << "* Final energy of reference particle: not available, "
3064 << "the reference particle (ID 0) is no longer in the bunch" << endl;
3065 }
3066 *gmsg << "* Total phase space dump number(includes the initial distribution) = " << lastDumpedStep_m + 1 << endl;
3067 *gmsg << "* One can restart simulation from the last dump step (--restart " << lastDumpedStep_m << ")" << endl;
3068
3070
3071 switch ( mode_m ) {
3072 case TrackingMode::SEO: {
3073 // Calculate tunes after tracking.
3074 *gmsg << endl;
3075 *gmsg << "* **************** The result for tune calculation (NO space charge) ******************* *" << endl
3076 << "* Number of tracked turns: " << TturnNumber.back() << endl;
3077 double nur, nuz;
3078 getTunes(Ttime, Tdeltr, Tdeltz, TturnNumber.back(), nur, nuz);
3079 break;
3080 }
3082 closeFiles();
3083 // fall through
3084 case TrackingMode::BUNCH: // we do nothing
3086 default: {
3087 // not for multibunch
3088 if (!isMultiBunch()) {
3089 *gmsg << "*" << endl;
3090 *gmsg << "* Finished during turn " << turnnumber_m << " (" << turnnumber_m - 1 << " turns completed)" << endl;
3091 *gmsg << "* Cave: Turn number is not correct for restart mode"<< endl;
3092 }
3093 }
3094 }
3095
3097
3098 if (myNode_m == 0) {
3099 outfTrackOrbit_m.close();
3100 }
3101
3102 *gmsg << endl << "* *********************** Bunch information in global frame: ***********************";
3103
3104 if (itsBunch_m->getTotalNum() > 0) {
3105 // Print out the Bunch information at end of the run.
3107 *gmsg << *itsBunch_m << endl;
3108 } else {
3109 *gmsg << endl << "* No Particles left in bunch" << endl;
3110 *gmsg << "* **********************************************************************************" << endl;
3111 }
3112}
3113
3115 if ( initialTotalNum_m == 1 ) {
3117 } else if ( initialTotalNum_m == 2 ) {
3119 } else if ( initialTotalNum_m > 2 ) {
3121 } else {
3123 }
3124}
3125
3126void ParallelCyclotronTracker::seoMode_m(double& t, const double dt, bool& /*finishedTurn*/,
3127 dvector_t& Ttime, dvector_t& Tdeltr,
3128 dvector_t& Tdeltz, ivector_t& TturnNumber) {
3129
3130 // 2 particles: Trigger SEO mode
3131 // (Switch off cavity and calculate betatron oscillation tuning)
3132 double r_tuning[2], z_tuning[2];
3133
3135 for (size_t i = 0; i < (itsBunch_m->getLocalNum()); i++) {
3136
3137 if ((step_m % Options::sptDumpFreq == 0)) {
3138 outfTrackOrbit_m << "ID" << (itsBunch_m->ID[i]);
3139 outfTrackOrbit_m << " " << itsBunch_m->R[i](0)
3140 << " " << itsBunch_m->P[i](0)
3141 << " " << itsBunch_m->R[i](1)
3142 << " " << itsBunch_m->P[i](1)
3143 << " " << itsBunch_m->R[i](2)
3144 << " " << itsBunch_m->P[i](2)
3145 << std::endl;
3146 }
3147
3148 double OldTheta = calculateAngle(itsBunch_m->R[i](0), itsBunch_m->R[i](1));
3149 r_tuning[i] = itsBunch_m->R[i](0) * std::cos(OldTheta) +
3150 itsBunch_m->R[i](1) * std::sin(OldTheta);
3151
3152 z_tuning[i] = itsBunch_m->R[i](2);
3153
3154 // Integrate for one step in the lab Cartesian frame (absolute value).
3155 itsStepper_mp->advance(itsBunch_m, i, t, dt);
3156
3157 if ( (i == 0) && isTurnDone() ) {
3158 turnnumber_m++;
3159 }
3160
3161 } // end for: finish one step tracking for all particles for initialTotalNum_m == 2 mode
3163
3164 // store dx and dz for future tune calculation if higher precision needed, reduce freqSample.
3165 if (step_m % Options::sptDumpFreq == 0) {
3166 Ttime.push_back(t);
3167 Tdeltz.push_back(z_tuning[1]);
3168 Tdeltr.push_back(r_tuning[1] - r_tuning[0]);
3169 TturnNumber.push_back(turnnumber_m);
3170 }
3171}
3172
3173
3174void ParallelCyclotronTracker::singleMode_m(double& t, const double dt,
3175 bool& finishedTurn, double& oldReferenceTheta) {
3176 // 1 particle: Trigger single particle mode
3177
3178 // ********************************************************************************** //
3179 // * This was moved here b/c collision should be tested before the actual * //
3180 // * timestep (bgf_main_collision_test() predicts the next step automatically) * //
3181
3182 // apply the plugin elements: probe, collimator, stripper, septum
3183 bool flagNeedUpdate = applyPluginElements(dt);
3184
3185 // check if we lose particles at the boundary
3187 // ********************************************************************************** //
3188
3189 if (itsBunch_m->getLocalNum() == 0) return; // might happen if particle is in collimator
3190
3192
3193 unsigned int i = 0; // we only have a single particle
3194 if ( step_m % Options::sptDumpFreq == 0 ) {
3195 outfTrackOrbit_m << "ID" <<itsBunch_m->ID[i]
3196 << " " << itsBunch_m->R[i](0)
3197 << " " << itsBunch_m->P[i](0)
3198 << " " << itsBunch_m->R[i](1)
3199 << " " << itsBunch_m->P[i](1)
3200 << " " << itsBunch_m->R[i](2)
3201 << " " << itsBunch_m->P[i](2)
3202 << std::endl;
3203 }
3204
3205 double temp_meanTheta = calculateAngle2(itsBunch_m->R[i](0),
3206 itsBunch_m->R[i](1)); // [-pi, pi]
3207
3209 temp_meanTheta, finishedTurn);
3210
3212 oldReferenceTheta, temp_meanTheta);
3213
3214 oldReferenceTheta = temp_meanTheta;
3215
3216 // used for gap crossing checking
3217 Vector_t Rold = itsBunch_m->R[i]; // [x,y,z] (m)
3218 Vector_t Pold = itsBunch_m->P[i]; // [px,py,pz] (beta*gamma)
3219
3220 // integrate for one step in the lab Cartesian frame (absolute value).
3221 itsStepper_mp->advance(itsBunch_m, i, t, dt);
3222
3223 // If gap crossing happens, do momenta kicking (not if gap crossing just happened)
3224 if (itsBunch_m->cavityGapCrossed[i] == true) {
3225 itsBunch_m->cavityGapCrossed[i] = false;
3226 } else {
3227 gapCrossKick_m(i, t, dt, Rold, Pold);
3228 }
3230
3231 // Destroy particles if they are marked as Bin = -1 in the plugin elements
3232 // or out of the global aperture
3233 flagNeedUpdate |= (itsBunch_m->Bin[i] < 0);
3234 deleteParticle(flagNeedUpdate);
3235}
3236
3237
3238void ParallelCyclotronTracker::bunchMode_m(double& t, const double dt, bool& finishedTurn) {
3239
3240 // Flag for transition from single-bunch to multi-bunches mode
3241 static bool flagTransition = false;
3242
3243 // single particle dumping
3244 if (step_m % Options::sptDumpFreq == 0)
3246
3247 // Find out if we need to do bunch injection
3248 injectBunch(flagTransition);
3249
3250// oldReferenceTheta = calculateAngle2(meanR(0), meanR(1));
3251
3252 // Calculate SC field before each time step and keep constant during integration.
3253 // Space Charge effects are included only when total macroparticles number is NOT LESS THAN 1000.
3254 if (itsBunch_m->hasFieldSolver()) {
3255
3256 if (step_m % setup_m.scSolveFreq == 0) {
3259 } else {
3260 // If we are not solving for the space charge fields at this time step
3261 // we will apply the fields from the previous step and have to rotate them
3262 // accordingly. For this we find the quaternion between the previous mean momentum (PreviousMeanP)
3263 // and the current mean momentum (meanP) and rotate the fields with this quaternion.
3264
3265 Vector_t const meanP = calcMeanP();
3266
3267 Quaternion_t quaternionToNewMeanP;
3268
3269 getQuaternionTwoVectors(PreviousMeanP, meanP, quaternionToNewMeanP);
3270
3271 // Reset PreviousMeanP. Cave: This HAS to be after the quaternion is calculated!
3273
3274 // Rotate the fields
3275 globalToLocal(itsBunch_m->Ef, quaternionToNewMeanP);
3276 globalToLocal(itsBunch_m->Bf, quaternionToNewMeanP);
3277 }
3278 }
3279
3280 // *** This was moved here b/c collision should be tested before the **********************
3281 // *** actual timestep (bgf_main_collision_test() predicts the next step automatically) -DW
3282 // Apply the plugin elements: probe, collimator, stripper, septum
3283 bool flagNeedUpdate = applyPluginElements(dt);
3284
3285 // check if we lose particles at the boundary
3287
3289
3290 for (size_t i = 0; i < itsBunch_m->getLocalNum(); i++) {
3291
3292 // used for gap crossing checking
3293 Vector_t Rold = itsBunch_m->R[i]; // [x,y,z] (m)
3294 Vector_t Pold = itsBunch_m->P[i]; // [px,py,pz] (beta*gamma)
3295
3296 // Integrate for one step in the lab Cartesian frame (absolute value).
3297 itsStepper_mp->advance(itsBunch_m, i, t, dt);
3298
3299 // If gap crossing happens, do momenta kicking (not if gap crossing just happened)
3300 if (itsBunch_m->cavityGapCrossed[i] == true) {
3301 itsBunch_m->cavityGapCrossed[i] = false;
3302 } else {
3303 gapCrossKick_m(i, t, dt, Rold, Pold);
3304 }
3305 flagNeedUpdate |= (itsBunch_m->Bin[i] < 0);
3306 }
3307
3309
3310 // Destroy particles if they are marked as Bin = -1 in the plugin elements
3311 // or out of global aperture
3312 deleteParticle(flagNeedUpdate);
3313
3314 // Recalculate bingamma and reset the BinID for each particles according to its current gamma
3315 if (isMultiBunch() && step_m % Options::rebinFreq == 0) {
3316 mbHandler_m->updateParticleBins(itsBunch_m);
3317 }
3318
3319 // Some status output for user after each turn
3320 if ( isTurnDone() ) {
3321 turnnumber_m++;
3322 finishedTurn = true;
3323
3324 *gmsg << endl;
3325 *gmsg << "*** Finished turn " << turnnumber_m - 1
3326 << ", Total number of live particles: "
3327 << itsBunch_m->getTotalNum() << endl;
3329 }
3330
3332}
3333
3334
3336 double dt,
3337 const Vector_t& Rold,
3338 const Vector_t& Pold) {
3339
3340 // Called for every particle on every step; without cavities the scan below finds nothing.
3341 if (numRFCavities_m == 0) {
3342 return;
3343 }
3344
3345 for (beamline_list::iterator sindex = ++(FieldDimensions.begin());
3346 sindex != FieldDimensions.end(); ++sindex)
3347 {
3348 bool tag_crossing = false;
3349 double DistOld = 0.0;
3350 RFCavity* rfcav;
3351
3352 if (((*sindex)->first) == ElementType::RFCAVITY) {
3353 // here check gap cross in the list, if do, set tag_crossing to TRUE
3354 rfcav = static_cast<RFCavity*>(((*sindex)->second).second);
3355 tag_crossing = checkGapCross(Rold, itsBunch_m->R[i], rfcav, DistOld);
3356 }
3357
3358 if ( tag_crossing ) {
3359 itsBunch_m->cavityGapCrossed[i] = true;
3360
3361 double oldBeta = euclidean_norm(Util::getBeta(Pold));
3362 double dt1 = DistOld / (oldBeta * Physics::c);
3363 double dt2 = dt - dt1;
3364
3365 // retrack particle from the old postion to cavity gap point
3366 // restore the old coordinates and momenta
3367 itsBunch_m->R[i] = Rold;
3368 itsBunch_m->P[i] = Pold;
3369
3370 if (dt / dt1 < 1.0e9) {
3371 itsStepper_mp->advance(itsBunch_m, i, t, dt1);
3372 }
3373 // Momentum kick
3374 RFkick(rfcav, t, dt1, i);
3375
3376 /* Retrack particle from cavity gap point for
3377 * the left time to finish the entire timestep
3378 */
3379 if (dt / dt2 < 1.0e9) {
3380 itsStepper_mp->advance(itsBunch_m, i, t, dt2);
3381 }
3382 }
3383 }
3384}
3385
3386
3388 const Vector_t& R,
3389 const Vector_t& P,
3390 const double& oldReferenceTheta,
3391 const double& temp_meanTheta) {
3392
3393 for (unsigned int i=0; i<=2; i++) {
3394 if ((oldReferenceTheta < azimuth_angle_m[i] - setup_m.deltaTheta) &&
3395 ( temp_meanTheta >= azimuth_angle_m[i] - setup_m.deltaTheta))
3396 {
3397 *(outfTheta_m[i]) << "#Turn number = " << turnnumber_m
3398 << ", Time = " << t * Units::s2ns << " [ns]" << std::endl
3399 << " " << std::hypot(R(0), R(1))
3400 << " " << P(0) * std::cos(temp_meanTheta) + P(1) * std::sin(temp_meanTheta)
3401 << " " << temp_meanTheta * Units::rad2deg
3402 << " " << - P(0) * std::sin(temp_meanTheta) + P(1) * std::cos(temp_meanTheta)
3403 << " " << R(2)
3404 << " " << P(2) << std::endl;
3405 }
3406 }
3407}
3408
3410 const Vector_t& R,
3411 const Vector_t& P,
3412 const double& temp_meanTheta,
3413 bool& finishedTurn) {
3414 if ( isTurnDone() ) {
3415 ++turnnumber_m;
3416 finishedTurn = true;
3417
3418 *gmsg << "* SPT: Finished turn " << turnnumber_m - 1 << endl;
3419
3420 *(outfTheta_m[3]) << "#Turn number = " << turnnumber_m
3421 << ", Time = " << t * Units::s2ns << " [ns]" << std::endl
3422 << " " << std::sqrt(R(0) * R(0) + R(1) * R(1))
3423 << " " << P(0) * std::cos(temp_meanTheta) +
3424 P(1) * std::sin(temp_meanTheta)
3425 << " " << temp_meanTheta / Units::deg2rad
3426 << " " << - P(0) * std::sin(temp_meanTheta) +
3427 P(1) * std::cos(temp_meanTheta)
3428 << " " << R(2)
3429 << " " << P(2) << std::endl;
3430 }
3431}
3432
3433
3435 // Firstly reset E and B to zero before fill new space charge field data for each track step
3436 itsBunch_m->Bf = Vector_t(0.0);
3437 itsBunch_m->Ef = Vector_t(0.0);
3438
3440 // --- Single bunch mode with spiral inflector --- //
3441
3442 // If we are doing a spiral inflector simulation and are using the SAAMG solver
3443 // we don't rotate or translate the bunch and gamma is 1.0 (non-relativistic).
3444
3445 itsBunch_m->setGlobalMeanR(Vector_t({0.0, 0.0, 0.0}));
3447
3449
3450 } else {
3451
3452 Vector_t const meanR = calcMeanR();
3453
3455
3456 // Since calcMeanP takes into account all particles of all bins (TODO: Check this! -DW)
3457 // Using the quaternion method with PreviousMeanP and yaxis should give the correct result
3458 Quaternion_t quaternionToYAxis;
3459
3460 getQuaternionTwoVectors(PreviousMeanP, yaxis, quaternionToYAxis);
3461
3462 globalToLocal(itsBunch_m->R, quaternionToYAxis, meanR);
3463
3464 // The mesh fit of this solve, in its frame (FIELDSOLVER, MESHFIT)
3466 if ((step_m + 1) % Options::boundpDestroyFreq == 0) {
3468 } else {
3469 itsBunch_m->boundp();
3470 }
3472
3473 if (hasMultiBunch()) {
3474 // --- Multibunch mode --- //
3475
3476 // Calculate gamma for each energy bin
3478
3479 repartition();
3480
3481 // Calculate space charge field for each energy bin
3482 for (int b = 0; b < itsBunch_m->getLastemittedBin(); b++) {
3484 itsBunch_m->setGlobalMeanR(meanR);
3485 itsBunch_m->setGlobalToLocalQuaternion(quaternionToYAxis);
3487 }
3488
3490
3491 } else {
3492 // --- Single bunch mode --- //
3493 double temp_meangamma = Util::getGamma(PreviousMeanP);
3494
3495 // FIELDSOLVER, MESHFIT=CORE: the partition of the old box is out of balance
3496 // at the first solve and after a switch between the core box and the box of
3497 // all particles
3499
3500 itsBunch_m->setGlobalMeanR(meanR);
3501 itsBunch_m->setGlobalToLocalQuaternion(quaternionToYAxis);
3502 itsBunch_m->computeSelfFields_cycl(temp_meangamma);
3503 }
3504
3505 // Transform coordinates back to global
3506 localToGlobal(itsBunch_m->R, quaternionToYAxis, meanR);
3507
3508 // Transform self field back to global frame (rotate only)
3509 localToGlobal(itsBunch_m->Ef, quaternionToYAxis);
3510 localToGlobal(itsBunch_m->Bf, quaternionToYAxis);
3511 }
3512}
3513
3514
3517 return;
3518 }
3519
3523 if (core.numLive > 0) {
3524 // Resolution of the core: cells per clipped rms width on the mesh of the last solve
3525 // (in FULL mode that of all particles) and on the mesh fitted to all particles
3526 Vector_t fullMin, fullMax;
3527 itsBunch_m->getMeshFitFullBounds(fullMin, fullMax);
3528 const Vector_t hrFull = itsBunch_m->getMeshSpacing(fullMin, fullMax);
3529 const bool full = (itsBunch_m->getMeshFitMode().mode == CoreFitSC::Mode::FULL);
3530
3531 *gmsg << "* SC mesh fit: mode " << (full ? "FULL" : "CORE") << ", "
3532 << core.numFar << " far particles (" << 100.0 * core.getFarChargeFraction()
3533 << " % of the live charge, max " << core.farMaxDistance << " sigma), "
3534 << core.numHalo << " beyond " << CoreFitSC::haloSigma << " sigma, "
3535 << core.passes << " clipped passes, " << statistics.numFlagged << " flagged, "
3536 << statistics.numOutside << " outside the mesh, ";
3537 if (core.numCore > 0) {
3538 const Vector_t& hr = statistics.meshSpacing;
3539 *gmsg << "cells per sigma " << core.sigma[0] / hr[0] << "/"
3540 << core.sigma[1] / hr[1] << "/" << core.sigma[2] / hr[2]
3541 << " (mesh of all particles ";
3542 } else {
3543 *gmsg << "no core particle (cells per sigma on the mesh of all particles ";
3544 }
3545 *gmsg << core.sigma[0] / hrFull[0] << "/" << core.sigma[1] / hrFull[1] << "/"
3546 << core.sigma[2] / hrFull[2] << "), " << statistics.turnFullSolves << " of "
3547 << statistics.turnSolves << " solves of this turn in FULL mode, "
3548 << statistics.modeSwitches << " mode switches" << endl;
3549 }
3551}
3552
3553
3554bool ParallelCyclotronTracker::computeExternalFields_m(const size_t& i, const double& t,
3555 Vector_t& Efield, Vector_t& Bfield) {
3556
3557 beamline_list::iterator sindex = FieldDimensions.begin();
3558
3559 // Flag whether a particle is out of field
3560 bool outOfBound = (((*sindex)->second).second)->apply(i, t, Efield, Bfield);
3561
3562 Bfield *= Units::kG2T;
3563 Efield *= Units::kV2V / Units::mm2m;
3564
3565 return outOfBound;
3566}
3567
3569 Vector_t& Efield, Vector_t& Bfield) {
3570
3571 beamline_list::iterator sindex = FieldDimensions.begin();
3572 // Flag whether a particle is out of field
3573 bool outOfBound = (((*sindex)->second).second)->apply(R, P, t, Efield, Bfield);
3574
3575 Bfield *= Units::kG2T;
3576 Efield *= Units::kV2V / Units::mm2m;
3577
3578 return outOfBound;
3579}
3580
3581
3582
3583void ParallelCyclotronTracker::injectBunch(bool& flagTransition) {
3585 return;
3586 }
3587
3588 const short result = mbHandler_m->injectBunch(itsBunch_m, itsReference,
3589 flagTransition);
3590
3591 switch ( result ) {
3592 case 0: {
3593 // nothing happened
3594 break;
3595 }
3596 case 1: {
3597 // bunch got saved
3600 if ( flagTransition ) {
3601 *gmsg << "* MBM: Saving beam distribution at turn " << turnnumber_m << endl;
3602 *gmsg << "* MBM: After one revolution, Multi-Bunch Mode will be invoked" << endl;
3603 }
3604 break;
3605 }
3606 case 2: {
3607 // bunch got injected
3609 break;
3610 }
3611 default: {
3612 throw OpalException("ParallelCyclotronTracker::injectBunch()",
3613 "Unknown return value " + std::to_string(result));
3614 }
3615 }
3616}
3617
3618
3620 if ( !isMultiBunch() ) {
3621 return;
3622 }
3623
3624 Vector_t meanR = calcMeanR();
3625
3626 // Bunch (global) angle w.r.t. x-axis (cylinder coordinates)
3627 double theta = calculateAngle(meanR(0), meanR(1)) * Units::rad2deg;
3628
3629 // fix azimuth_m --> make monotonically increasing
3631
3632 const double radius = computeRadius(meanR);
3633
3634 MultiBunchHandler::injection_t& inj = mbHandler_m->getInjectionValues();
3635
3636 inj.time = itsBunch_m->getT();
3638 inj.azimuth = azimuth_m;
3639 inj.radius = radius;
3640}
3641
3642
3644 /* the last element includes all particles,
3645 * all other elements are bunch number specific
3646 */
3647 std::vector<double> lpaths(1);
3648
3649 if ( isMultiBunch() ) {
3650 lpaths.resize(mbHandler_m->getNumBunch() + 1);
3651 }
3652
3653 computePathLengthUpdate(lpaths, dt);
3654
3655 pathLength_m += lpaths.back();
3657
3658 if ( isMultiBunch() ) {
3659 mbHandler_m->updatePathLength(lpaths);
3660 }
3661}
3662
3663
3665 double t = itsBunch_m->getT();
3666
3667 itsBunch_m->setT(t + dt);
3668
3669 if ( isMultiBunch() ) {
3670 mbHandler_m->updateTime(dt);
3671 }
3672}
3673
3674
3676 if (!isMultiBunch()) {
3677 return;
3678 }
3679
3680 for (short b = 0; b < mbHandler_m->getNumBunch(); ++b) {
3681 Vector_t meanR = calcMeanR(b);
3682 MultiBunchHandler::beaminfo_t& binfo = mbHandler_m->getBunchInfo(b);
3683
3684 binfo.radius = computeRadius(meanR);
3685 double azimuth = calculateAngle(meanR(0), meanR(1)) * Units::rad2deg;
3686 dumpAngle(azimuth, binfo.prevAzimuth, binfo.azimuth, b);
3687 }
3688}
3689
3690
3692 if ( isMultiBunch() ) {
3693 // we need to reset the path length of each bunch
3695 }
3696}
Inform * gmsg
Definition Main.cpp:70
DistributionType
ElementType
Definition ElementBase.h:89
T euclidean_norm(const Vector< T > &)
Euclidean norm.
Definition Vector.h:243
Vector3D cross(const Vector3D &lhs, const Vector3D &rhs)
Vector cross product.
Definition Vector3D.cpp:111
double dot(const Vector3D &lhs, const Vector3D &rhs)
Vector dot product.
Definition Vector3D.cpp:118
Quaternion Quaternion_t
Definition Quaternion.h:42
T prod_boost_vector(const boost::numeric::ublas::matrix< double > &rotation, const T &vector)
Definition BoostMatrix.h:26
Inform * gmsgALL
Definition Main.cpp:71
Inform * gmsg
Definition Main.cpp:70
bool for_each(const BareFieldIterator< T, D > &p, SameFieldID s, C)
Definition AssignDefs.h:30
T::PETE_Expr_t::PETE_Return_t sum(const PETE_Expr< T > &expr)
Definition PETE.h:1111
#define IPPL_APP_CYCLE
Definition Tags.h:103
#define IPPL_APP_TAG4
Definition Tags.h:97
const int COMM_ANY_NODE
Definition Communicate.h:40
void allreduce(const T *input, T *output, int count, Op op)
bool reduce(Communicate &, InputIterator, InputIterator, OutputIterator, const ReduceOp &, bool *IncludeVal=0)
#define ERRORMSG(msg)
Definition IpplInfo.h:350
Inform & level4(Inform &inf)
Definition Inform.cpp:48
Inform & endl(Inform &inf)
Definition Inform.cpp:42
Inform & level3(Inform &inf)
Definition Inform.cpp:47
TimeIntegrator
Definition Steppers.h:25
constexpr double haloSigma
The halo proper: live particles beyond haloSigma clipped rms widths in any axis.
Definition CoreFitSC.h:54
constexpr double q_e
The elementary charge in As.
Definition Physics.h:69
constexpr double c
The velocity of light in m/s.
Definition Physics.h:45
constexpr double pi
The value of.
Definition Physics.h:30
constexpr double GeV2MeV
Definition Units.h:80
constexpr double mm2m
Definition Units.h:29
constexpr double m2mm
Definition Units.h:26
constexpr double eV2MeV
Definition Units.h:77
constexpr double kV2V
Definition Units.h:62
constexpr double GeV2eV
Definition Units.h:68
constexpr double kG2T
Definition Units.h:59
constexpr double rad2deg
Definition Units.h:146
constexpr double deg2rad
Definition Units.h:143
constexpr double s2ns
Definition Units.h:44
int mtsSubsteps
Definition Options.cpp:57
int psDumpFreq
The frequency to dump the phase space, i.e.dump data when steppsDumpFreq==0.
Definition Options.cpp:37
int boundpDestroyFreq
Definition Options.cpp:85
bool psDumpEachTurn
phase space dump flag for OPAL-cycl
Definition Options.cpp:41
bool asciidump
Definition Options.cpp:83
int sptDumpFreq
The frequency to dump single particle trajectory of particles with ID = 0 & 1.
Definition Options.cpp:45
unsigned int delPartFreq
The frequency to delete particles (currently: OPAL-cycl only)
Definition Options.cpp:107
int scSolveFreq
The frequency to solve space charge fields.
Definition Options.cpp:55
int repartFreq
The frequency to do particles repartition for better load balance between nodes.
Definition Options.cpp:47
int rebinFreq
The frequency to reset energy bin ID for all particles.
Definition Options.cpp:53
DumpFrame psDumpFrame
flag to decide in which coordinate frame the phase space will be dumped for OPAL-cycl
Definition Options.cpp:43
int statDumpFreq
The frequency to dump statistical values, e.e. dump data when stepstatDumpFreq==0.
Definition Options.cpp:39
bool angleBetweenAngles(const double angle, const double min, const double max)
check if angle (in rad and in range [0,2pi]) is within [min, max]
Definition Util.h:209
std::string doubleVectorToString(const std::vector< double > &v)
Definition Util.cpp:183
std::string boolVectorToUpperString(const std::vector< bool > &b)
Definition Util.cpp:168
Vector_t getBeta(Vector_t p)
Definition Util.h:54
double getGamma(Vector_t p)
Definition Util.h:49
const std::string & getOpalName() const
Return object name.
Definition Object.cpp:310
ParticleAttrib< Vector_t > Ef
double get_meanKineticEnergy() const
ParticlePos_t & R
void getMeshFitFullBounds(Vector_t &rmin, Vector_t &rmax) const
MESHFIT=CORE: the bounds of all particles of the same fit.
ParticleAttrib< int > Bin
Vector_t RefPartP_m
void boundp_destroyCycl()
const MeshFitParameters & getMeshFit() const
double getQ() const
Access to reference data.
double getChargePerParticle() const
get the macro particle charge
size_t getLocalNum() const
void set_sPos(double s)
void setLocalTrackStep(long long n)
step in a TRACK command
void setComputeSCDiagnostics(bool compute)
void setLocalBinCount(size_t num, int bin)
ParticleAttrib< double > M
size_t getTotalNum() const
ParticleAttrib< Vector_t > P
double getdT() const
FieldSolverType getFieldSolverType() const
Return the fieldsolver type if we have a fieldsolver.
void setLocalNumPerBunch(size_t numpart, short n)
size_t getLocalNumPerBunch(short n) const
void setGlobalToLocalQuaternion(Quaternion_t globalToLocalQuaternion)
ParticleAttrib< ParticleOrigin > POrigin
virtual void computeSelfFields_cycl(double gamma)=0
Vector_t RefPartR_m
ParticleAttrib< double > Q
const CoreFitSC::CoreSelection & getMeshFitCore() const
size_t getTotalNumPerBunch(short n) const
ParticleAttrib< short > cavityGapCrossed
void setTotalNum(size_t n)
Vector_t getMeshSpacing(const Vector_t &rmin, const Vector_t &rmax) const
Mesh spacing that boundp() gives to particles within [rmin, rmax].
long long getLocalTrackStep() const
void setGlobalMeanR(Vector_t globalMeanR)
short getNumBunch() const
virtual void do_binaryRepart()
ParticleAttrib< double > dt
int getStepsPerTurn() const
bool isMeshFitRepartitionDue() const
void countTotalNumPerBunch()
DistributionType getDistType() const
virtual void setBinCharge(int bin, double q)
Set the charge of one bin to the value of q and all other to zero.
void performDestroy(bool updateLocalNum=false)
void setMeshFitSolveStep(bool solveStep)
ParticleAttrib< short > bunchNum
void setTotalNumPerBunch(size_t numpart, short n)
void destroy(size_t M, size_t I, bool doNow=false)
ParticleAttrib< Vector_t > Bf
double getMomentumTolerance() const
const CoreFitSC::ModeState & getMeshFitMode() const
virtual void boundp()
void setT(double t)
ParticleIndex_t & ID
double get_sPos() const
double getM() const
double getT() const
const MeshFitStatistics & getMeshFitStatistics() const
std::string getInputBasename()
get input file name without extension
Definition OpalData.cpp:674
static OpalData * getInstance()
Definition OpalData.cpp:196
BoundaryGeometry * getGlobalGeometry()
Definition OpalData.cpp:461
void setOpenMode(OpenMode openMode)
Definition OpalData.cpp:349
bool inRestartRun()
true if we do a restart run
Definition OpalData.cpp:312
int lombAnalysis(double *x, double *y, int Ndat, int nhis)
Definition Ctunes.cpp:141
void operator()(double x)
void computePathLengthUpdate(std::vector< double > &dl, const double &dt)
std::vector< PluginElement * > pluginElements_m
void dumpAzimuthAngles_m(const double &t, const Vector_t &R, const Vector_t &P, const double &oldReferenceTheta, const double &temp_meanTheta)
unsigned int numRFCavities_m
RFCAVITY entries in FieldDimensions; gapCrossKick_m() has nothing to do without them.
IpplTimings::TimerRef IntegrationTimer_m
IpplTimings::TimerRef PluginElemTimer_m
virtual void visitDegrader(const Degrader &)
Apply the algorithm to a degrader.
virtual void visitRBend(const RBend &)
Apply the algorithm to a rectangular bend.
static Vector_t const xaxis
The positive axes unit vectors.
virtual void visitProbe(const Probe &)
Apply the algorithm to a probe.
virtual void visitVacuum(const Vacuum &)
Apply the algorithm to a vacuum space.
std::function< bool(const double &, const size_t &, Vector_t &, Vector_t &)> function_t
bool computeExternalFields_m(const Vector_t &R, const Vector_t &P, const double &t, Vector_t &Efield, Vector_t &Bfield)
Calculate the field map at an arbitrary point.
std::vector< double > azimuth_angle_m
the different azimuthal angles for the outfTheta_m output files
bool setRefPartForDump_m(Vector_t &refR, Vector_t &refP)
std::unique_ptr< MultiBunchHandler > mbHandler_m
void injectBunch(bool &flagTransition)
void rotateAroundZ(ParticleAttrib< Vector_t > &particleVectors, double const phi)
virtual void visitStripper(const Stripper &)
Apply the algorithm to a particle stripper.
void normalizeQuaternion(Quaternion_t &quaternion)
virtual void visitCCollimator(const CCollimator &)
Apply the algorithm to a collimator.
void singleMode_m(double &t, const double dt, bool &finishedTurn, double &oldReferenceTheta)
void update_m(double &t, const double &dt, const bool &finishedTurn)
Update time and path length, write to output files.
std::vector< std::unique_ptr< std::ofstream > > outfTheta_m
output coordinates at different azimuthal angles and one after every turn
void rotateAroundX(ParticleAttrib< Vector_t > &particleVectors, double const psi)
double calculateAngle(double x, double y)
bool isTurnDone()
Check if turn done.
virtual void visitBeamline(const Beamline &)
Apply the algorithm to a beam line.
bool checkGapCross(Vector_t Rold, Vector_t Rnew, RFCavity *rfcavity, double &DistOld)
virtual void visitOffset(const Offset &)
Apply the algorithm to a offset (placement).
IpplTimings::TimerRef DelParticleTimer_m
bool RFkick(RFCavity *rfcavity, const double t, const double dt, const int Pindex)
virtual void visitScalingFFAMagnet(const ScalingFFAMagnet &bend)
Apply the algorithm to a scaling FFA magnet.
double computeRadius(const Vector_t &meanR) const
void updatePathLength(const double &dt)
void openFiles(size_t numFiles, std::string fn)
@ open / close output coordinate files
virtual void visitSBend3D(const SBend3D &)
Apply the algorithm to a sector bend with 3D field map.
double bega
The reference variables.
void dumpAngle(const double &theta, double &prevAzimuth, double &azimuth, const short &bunchNr=0)
bool applyPluginElements(const double dt)
virtual void visitCorrector(const Corrector &)
Apply the algorithm to a closed orbit corrector.
std::tuple< double, double, double > initializeTracking_m()
std::pair< ElementType, element_pair > type_pair
virtual void visitRing(const Ring &ring)
Apply the algorithm to a ring.
IpplTimings::TimerRef BinRepartTimer_m
void globalToLocal(ParticleAttrib< Vector_t > &vectorArray, double phi, Vector_t const translationToGlobal=0)
bool getFieldsAtPoint(const double &t, const size_t &Pindex, Vector_t &Efield, Vector_t &Bfield)
std::vector< CavityCrossData > cavCrossDatas_m
virtual void visitDrift(const Drift &)
Apply the algorithm to a drift space.
std::unique_ptr< Stepper< function_t > > itsStepper_mp
struct ParallelCyclotronTracker::settings setup_m
bool refLostWarned_m
setRefPartForDump_m() has reported the loss of ID 0 in this run
void finalizeTracking_m(dvector_t &Ttime, dvector_t &Tdeltr, dvector_t &Tdeltz, ivector_t &TturnNumber)
virtual void visitVariableRFCavityFringeField(const VariableRFCavityFringeField &cav)
Apply the algorithm to a variable RF cavity with Fringe Field.
void gapCrossKick_m(size_t i, double t, double dt, const Vector_t &Rold, const Vector_t &Pold)
void getQuaternionTwoVectors(Vector_t u, Vector_t v, Quaternion_t &quaternion)
virtual void visitSBend(const SBend &)
Apply the algorithm to a sector bend.
virtual void visitMarker(const Marker &)
Apply the algorithm to a marker.
virtual void execute()
Apply the algorithm to the top-level beamline.
void dumpThetaEachTurn_m(const double &t, const Vector_t &R, const Vector_t &P, const double &temp_meanTheta, bool &finishedTurn)
void bunchMode_m(double &t, const double dt, bool &finishedTurn)
std::list< Component * > myElements
std::unique_ptr< LossDataSink > lossDs_m
virtual void visitMultipoleT(const MultipoleT &)
Apply the algorithm to an arbitrary multipole.
virtual void visitVariableRFCavity(const VariableRFCavity &cav)
Apply the algorithm to a variabel RF cavity.
bool getReferenceParticle(Vector_t &refR, Vector_t &refP) const
void buildupFieldList(double BcParameter[], ElementType elementType, Component *elptr)
void rotateWithQuaternion(ParticleAttrib< Vector_t > &vectorArray, Quaternion_t const quaternion)
virtual void visitMultipole(const Multipole &)
Apply the algorithm to a multipole.
virtual void visitSolenoid(const Solenoid &)
Apply the algorithm to a solenoid.
Steppers::TimeIntegrator stepper_m
IpplTimings::TimerRef TransformTimer_m
Vector_t calcMeanR(short bunchNr=-1) const
double calculateAngle2(double x, double y)
virtual void visitCyclotron(const Cyclotron &cycl)
Apply the algorithm to a cyclotron.
void localToGlobal(ParticleAttrib< Vector_t > &vectorArray, double phi, Vector_t const translationToGlobal=0)
virtual void visitRFCavity(const RFCavity &)
Apply the algorithm to a RF cavity.
bool getTunes(dvector_t &t, dvector_t &r, dvector_t &z, int lastTurn, double &nur, double &nuz)
virtual void visitFlexibleCollimator(const FlexibleCollimator &)
Apply the algorithm to a flexible collimator.
virtual void visitVerticalFFAMagnet(const VerticalFFAMagnet &bend)
Apply the algorithm to a vertical FFA magnet.
virtual void visitSeptum(const Septum &)
Apply the algorithm to a septum.
void seoMode_m(double &t, const double dt, bool &finishedTurn, dvector_t &Ttime, dvector_t &Tdeltr, dvector_t &Tdeltz, ivector_t &TturnNumber)
int maxSteps_m
The maximal number of steps the system is integrated.
virtual void visitOutputPlane(const OutputPlane &)
Apply the algorithm to a outputplane.
virtual void visitMonitor(const Monitor &)
Apply the algorithm to a beam position monitor.
static void writeFields(Component *field)
static void writeFields(Component *field)
double getWidth()
double getZStart()
Member variable access.
Definition CCollimator.h:95
double getZEnd()
Interface for a single beam element.
Definition Component.h:50
Interface for general corrector.
Definition Corrector.h:35
virtual std::vector< double > getEScale() const
virtual double getCyclHarm() const
virtual bool getSpiralFlag() const
virtual double getPRinit() const
void checkInitialReferenceParticle(double refR, double refTheta, double refZ)
virtual double getPZinit() const
virtual std::string getFieldMapFN() const
virtual double getRmin() const
virtual double getMaxR() const
virtual std::vector< double > getRfFrequ() const
virtual double getRmax() const
virtual double getMaxZ() const
virtual double getBScale() const
virtual double getZinit() const
virtual double getPHIinit() const
void setTurnNumber(int turn)
Turn number written into the loss records of apply(); the tracker sets it every step.
virtual double getSymmetry() const
virtual double getMinZ() const
virtual std::vector< double > getRfPhi() const
BFieldType getBFieldType() const
virtual void initialise(PartBunchBase< double, 3 > *bunch, double &startField, double &endField)
virtual std::vector< bool > getSuperpose() const
unsigned int getNumberOfTrimcoils() const
virtual double getRinit() const
virtual double getMinR() const
const std::string & getCyclotronType() const
Interface for drift space.
Definition Drift.h:33
virtual const std::string & getName() const
Get element name.
virtual double getElementLength() const
Get design length.
virtual void accept(BeamlineVisitor &visitor) const =0
Apply visitor.
virtual ElementBase * clone() const =0
Return clone.
virtual bool hasAttribute(const std::string &aKey) const
Test for existence of an attribute.
std::string getTypeString() const
Interface for a marker.
Definition Marker.h:32
Interface for general multipole.
Definition Multipole.h:47
ElementBase * clone() const override
Vector_t getCentre() const
ElementBase * clone() const override
double getHorizontalExtent() const
void setGlobalFieldMap(Component *field)
Vector_t getNormal() const
double getYStart() const
virtual void initialise(PartBunchBase< double, 3 > *bunch, double &startField, double &endField) override
Pure virtual implementation of Component.
double getXEnd() const
double getXStart() const
Member variable access.
double getYEnd() const
Definition Probe.h:31
Definition RBend.h:58
std::string getPhaseModelName()
Definition RFCavity.h:461
virtual double getRmax() const
Definition RFCavity.cpp:292
void getMomentaKick(const double normalRadius, double momentum[], const double t, const double dtCorrt, const int PID, const double restMass, const int chargenumber)
used in OPAL-cycl
Definition RFCavity.cpp:366
virtual double getAzimuth() const
Definition RFCavity.cpp:301
std::string getAmplitudeModelName()
Definition RFCavity.h:446
CavityType getCavityType() const noexcept
Definition RFCavity.h:411
virtual double getCosAzimuth() const
Definition RFCavity.cpp:309
virtual void initialise(PartBunchBase< double, 3 > *bunch, double &startField, double &endField) override
Definition RFCavity.cpp:160
std::string getCavityTypeString() const noexcept
Definition RFCavity.cpp:334
virtual double getSinAzimuth() const
Definition RFCavity.cpp:305
virtual std::string getFieldMapFN() const
Definition RFCavity.cpp:338
virtual double getCycFrequency() const
Definition RFCavity.cpp:352
virtual double getGapWidth() const
Definition RFCavity.cpp:317
std::string getFrequencyModelName()
Definition RFCavity.h:476
virtual double getPerpenDistance() const
Definition RFCavity.cpp:313
virtual double getPhi0() const
Definition RFCavity.cpp:321
virtual double getRmin() const
Definition RFCavity.cpp:283
Ring describes a ring type geometry for tracking.
Definition Ring.h:53
double getBeamRInit() const
Definition Ring.h:225
double getBeamPRInit() const
Definition Ring.h:243
double getSymmetry() const
Definition Ring.h:282
virtual ElementBase * clone() const override
Definition Ring.h:145
virtual void initialise(PartBunchBase< double, 3 > *bunch, double &startField, double &endField) override
Definition Ring.cpp:160
double getBeamPhiInit() const
Definition Ring.h:231
double getBeamThetaInit() const
Definition Ring.h:237
double getHarmonicNumber()
Definition Ring.h:212
void lockRing()
Definition Ring.cpp:295
void appendElement(const Component &element)
Definition Ring.cpp:238
Definition SBend.h:68
ScalingFFAMagnet * clone() const override
virtual void initialise(PartBunchBase< double, 3 > *bunch, double &startField, double &endField) override
Pure virtual implementation of Component.
Definition Septum.cpp:47
double getWidth() const
Definition Septum.cpp:57
Interface for solenoids.
Definition Solenoid.h:36
double getOPMass() const
Definition Stripper.cpp:94
double getOPCharge() const
Definition Stripper.cpp:90
bool getStop() const
Definition Stripper.cpp:102
double getPressure() const
Definition Vacuum.cpp:117
std::string getPressureMapFN() const
Definition Vacuum.cpp:130
double getPScale() const
Definition Vacuum.cpp:138
virtual void initialise(PartBunchBase< double, 3 > *bunch, double &startField, double &endField) override
Definition Vacuum.cpp:222
std::string getResidualGasName() const
Definition Vacuum.cpp:104
virtual bool checkVacuum(PartBunchBase< double, 3 > *bunch, Cyclotron *cycl)
Definition Vacuum.cpp:190
double getTemperature() const
Definition Vacuum.cpp:151
bool getStop() const
Definition Vacuum.cpp:164
static std::shared_ptr< AbstractTimeDependence > getTimeDependence(std::string name)
const PartData itsReference
The reference information.
Result of selectCore(), the same on every rank.
Definition CoreFitSC.h:117
unsigned int passes
clipped passes done, 0 to maxClipPasses
Definition CoreFitSC.h:131
double getFarChargeFraction() const
Far charge over live charge, 0 without live charge.
Definition CoreFitSC.cpp:84
std::size_t numLive
particles with Bin >= 0
Definition CoreFitSC.h:123
std::size_t numFar
the other live particles
Definition CoreFitSC.h:125
Vector_t sigma
clipped rms [m]
Definition CoreFitSC.h:119
std::size_t numHalo
live particles beyond haloSigma * sigma in any axis
Definition CoreFitSC.h:126
std::size_t numCore
live particles within nSigma * sigma in every axis
Definition CoreFitSC.h:124
MESHFIT=CORE: statistics of the solves of this TRACK/RUN, for the stat file and the log.
size_t numOutside
particles outside the mesh domain at the last update()
size_t turnFullSolves
solves in FULL mode in this turn
size_t modeSwitches
switches between CORE and FULL
size_t turnSolves
solves in this turn
double getBeta() const
The relativistic beta per particle.
Definition PartData.h:134
double getGamma() const
The relativistic gamma per particle.
Definition PartData.h:138
PartBunchBase< double, 3 > * itsBunch_m
The bunch of particles to be tracked.
Definition Tracker.h:151
An abstract sequence of beam line components.
Definition Beamline.h:34
virtual void iterate(BeamlineVisitor &, bool r2l) const
Apply visitor to all elements of the line.
Definition TBeamline.h:205
void kick(const Vector_t &R, Vector_t &P, const Vector_t &Ef, const Vector_t &Bf, const double &dt) const
Definition BorisPusher.h:65
Leap-Frog 2nd order.
Definition LF2.h:26
4-th order Runnge-Kutta stepper
Definition RK4.h:27
int partInside(const Vector_t &r, const Vector_t &v, const double dt, Vector_t &intecoords, int &triId)
void setMultiBunchInitialPathLengh(MultiBunchHandler *mbhandler_p)
Definition DataSink.cpp:229
void dumpSDDS(PartBunchBase< double, 3 > *beam, Vector_t FDext[], const double &azimuth, const double &timeStep) const
Write the stat file (OPAL-cycl)
Definition DataSink.cpp:107
void dumpH5(PartBunchBase< double, 3 > *beam, Vector_t FDext[]) const
Definition DataSink.cpp:87
void writeMultiBunchStatistics(PartBunchBase< double, 3 > *beam, MultiBunchHandler *mbhandler)
Definition DataSink.cpp:208
MeshFitType type
Definition FieldSolver.h:67
The base class for all OPAL exceptions.
Message * receive_block(int &node, int &tag)
void barrier(void)
Message & put(const T &val)
Definition Message.h:406
Message & get(const T &cval)
Definition Message.h:476
int next_tag(int t, int s=1000)
Definition TagMaker.h:39
static int getNodes()
Definition IpplInfo.cpp:689
static Communicate * Comm
Definition IpplInfo.h:84
static TimerRef getTimer(const char *nm)
static void stopTimer(TimerRef t)
static void startTimer(TimerRef t)
Vektor< double, 3 > Vector_t
Definition Vektor.h:6