OPAL (Object Oriented Parallel Accelerator Library) 2024.2
OPAL
PartBunchBase.hpp
Go to the documentation of this file.
1//
2// Class PartBunchBase
3// Base class for representing particle bunches.
4//
5// Copyright (c) 2008 - 2021, Paul Scherrer Institut, Villigen PSI, Switzerland
6// All rights reserved
7//
8// This file is part of OPAL.
9//
10// OPAL is free software: you can redistribute it and/or modify
11// it under the terms of the GNU General Public License as published by
12// the Free Software Foundation, either version 3 of the License, or
13// (at your option) any later version.
14//
15// You should have received a copy of the GNU General Public License
16// along with OPAL. If not, see <https://www.gnu.org/licenses/>.
17//
18#ifndef PART_BUNCH_BASE_HPP
19#define PART_BUNCH_BASE_HPP
20
22#include "Algorithms/PartBins.h"
24#include "Algorithms/PartData.h"
27#include "Physics/Physics.h"
28#include "Physics/Units.h"
32#include "Utilities/Options.h"
34#include "Utilities/Util.h"
35
36#include <cmath>
37#include <functional>
38#include <numeric>
39#include <sstream>
40#include <string>
41
42extern Inform* gmsg;
43
44template <class T, unsigned Dim>
46 : R(*(pb->R_p)),
47 ID(*(pb->ID_p)),
48 pbin_m(nullptr),
49 pmsg_m(nullptr),
50 f_stream(nullptr),
51 fixed_grid(false),
52 reference(ref),
53 unit_state_(units),
54 stateOfLastBoundP_(unitless),
55 dt_m(0.0),
56 t_m(0.0),
57 spos_m(0.0),
58 globalMeanR_m(Vector_t({0.0, 0.0, 0.0})),
59 globalToLocalQuaternion_m(Quaternion_t(1.0, 0.0, 0.0, 0.0)),
60 rmax_m(0.0),
61 rmin_m(0.0),
62 rmsDensity_m(0.0),
63 hr_m(-1.0),
64 nr_m(0),
65 fs_m(nullptr),
66 couplingConstant_m(0.0),
67 qi_m(0.0),
68 massPerParticle_m(0.0),
69 distDump_m(0),
70 dh_m(1e-12),
71 tEmission_m(0.0),
72 bingamma_m(nullptr),
73 binemitted_m(nullptr),
74 stepsPerTurn_m(0),
75 localTrackStep_m(0),
76 globalTrackStep_m(0),
77 numBunch_m(1),
78 bunchTotalNum_m(1),
79 bunchLocalNum_m(1),
80 SteptoLastInj_m(0),
81 globalPartPerNode_m(nullptr),
82 dist_m(nullptr),
83 dcBeam_m(false),
84 periodLength_m(Physics::c / 1e9),
85 pbase_m(pb)
87 setup(pb);
89
90/*
91 * Bunch common member functions
92 */
94template <class T, unsigned Dim>
96 if (dist_m != nullptr) {
97 size_t isBeamEmitted = dist_m->getIfDistEmitting();
98 reduce(isBeamEmitted, isBeamEmitted, OpAddAssign());
99 if (isBeamEmitted > 0)
100 return true;
101 else
102 return false;
103 } else
104 return false;
106
108template <class T, unsigned Dim>
110 /*
111 * Get maximum last emitted energy bin.
112 */
113 int lastEmittedBin = dist_m->getLastEmittedEnergyBin();
114 reduce(lastEmittedBin, lastEmittedBin, OpMaxAssign());
115 return lastEmittedBin;
117
119template <class T, unsigned Dim>
121 return dist_m->getNumberOfEmissionSteps();
123
125template <class T, unsigned Dim>
127 return dist_m->getNumberOfEnergyBins();
128}
129
131template <class T, unsigned Dim>
133
134 size_t isBeamEmitting = dist_m->getIfDistEmitting();
135 reduce(isBeamEmitting, isBeamEmitting, OpAddAssign());
136 if (isBeamEmitting > 0) {
137 *gmsg << "*****************************************************" << endl
138 << "Warning: attempted to rebin, but not all distribution" << endl
139 << "particles have been emitted. Rebin failed." << endl
140 << "*****************************************************" << endl;
141 } else {
142 if (dist_m->Rebin())
143 this->Bin = 0;
144 }
145}
147
148template <class T, unsigned Dim>
149void PartBunchBase<T, Dim>::setEnergyBins(int numberOfEnergyBins) {
150 bingamma_m = std::unique_ptr<double[]>(new double[numberOfEnergyBins]);
151 binemitted_m = std::unique_ptr<size_t[]>(new size_t[numberOfEnergyBins]);
152 for (int i = 0; i < numberOfEnergyBins; i++)
153 binemitted_m[i] = 0;
155
156
157template <class T, unsigned Dim>
159
160 if (dist_m != nullptr)
161 return dist_m->getNumberOfEnergyBins() > 0;
162 else
163 return false;
164}
166
167template <class T, unsigned Dim>
169
170 if (unit_state_ == unitless)
171 throw SwitcherError("PartBunch::switchToUnitlessPositions",
172 "Cannot make a unitless PartBunch unitless");
173
174 bool hasToReset = false;
175 if (!R.isDirty()) hasToReset = true;
176
177 for (size_t i = 0; i < getLocalNum(); i++) {
178 double dt = getdT();
179 if (use_dt_per_particle)
180 dt = this->dt[i];
181
182 R[i] /= Vector_t(Physics::c * dt);
183 }
184
185 unit_state_ = unitless;
186
187 if (hasToReset) R.resetDirtyFlag();
190//FIXME: unify methods, use convention that all particles have own dt
191template <class T, unsigned Dim>
193
194 if (unit_state_ == units)
195 throw SwitcherError("PartBunch::switchOffUnitlessPositions",
196 "Cannot apply units twice to PartBunch");
197
198 bool hasToReset = false;
199 if (!R.isDirty()) hasToReset = true;
200
201 for (size_t i = 0; i < getLocalNum(); i++) {
202 double dt = getdT();
203 if (use_dt_per_particle)
204 dt = this->dt[i];
206 R[i] *= Vector_t(Physics::c * dt);
208
209 unit_state_ = units;
210
211 if (hasToReset) R.resetDirtyFlag();
212}
213
214
215template <class T, unsigned Dim>
217 // do nothing here
218}
220
221template <class T, unsigned Dim>
223 std::vector<Distribution*> addedDistributions,
224 size_t& np) {
225 Inform m("setDistribution " );
226 dist_m = d;
227 dist_m->createOpalT(this, addedDistributions, np);
228
229// if (Options::cZero)
230// dist_m->create(this, addedDistributions, np / 2);
231// else
232// dist_m->create(this, addedDistributions, np);
233}
234
235template <class T, unsigned Dim>
237 size_t numberOfParticles,
238 double current,
239 const Beamline& bl) {
240 dist_m = d;
241 dist_m->createOpalCycl(this, numberOfParticles, current, bl);
242}
243
244
245template <class T, unsigned Dim>
247 return fixed_grid;
248}
249
250
251template <class T, unsigned Dim>
253 return (pbin_m != nullptr);
254}
255
256
257template <class T, unsigned Dim>
259 tEmission_m = t;
260}
261
262
263template <class T, unsigned Dim>
265 return tEmission_m;
266}
267
268
269template <class T, unsigned Dim>
271 if (dist_m != nullptr)
272 return dist_m->getIfDistEmitting();
273 else
274 return false;
275}
276
277
278template <class T, unsigned Dim>
280 if (pbin_m != nullptr)
281 return pbin_m->weHaveBins();
282 else
283 return false;
284}
285
286
287template <class T, unsigned Dim>
289 pbin_m = pbin;
290 *gmsg << *pbin_m << endl;
291 setEnergyBins(pbin_m->getNBins());
292}
293
294
295template <class T, unsigned Dim>
297 pbin_m = pbin;
298 setEnergyBins(pbin_m->getNBins());
299}
302template <class T, unsigned Dim>
304 return dist_m->emitParticles(this, eZ);
306
307
308template <class T, unsigned Dim>
310 size_t numParticles = getLocalNum();
311 reduce(numParticles, numParticles, OpAddAssign());
312 setTotalNum(numParticles);
314
316template <class T, unsigned Dim>
318 this->Bin = 0;
319 pbin_m->resetBins();
320 // delete pbin_m; we did not allocate it!
321 pbin_m = nullptr;
325template <class T, unsigned Dim>
327 if (pbin_m != nullptr)
328 return pbin_m->getLastemittedBin();
329 else
330 return 0;
334template <class T, unsigned Dim>
336 if (pbin_m != nullptr) {
337 pbin_m->setPartNum(bin, num);
342template <class T, unsigned Dim>
344
345 const int emittedBins = dist_m->getNumberOfEnergyBins();
347 size_t s = 0;
349 for (int i = 0; i < emittedBins; i++)
350 bingamma_m[i] = 0.0;
351
352 for (unsigned int n = 0; n < getLocalNum(); n++)
353 bingamma_m[this->Bin[n]] += std::sqrt(1.0 + dot(this->P[n], this->P[n]));
355 std::unique_ptr<size_t[]> particlesInBin(new size_t[emittedBins]);
356 reduce(bingamma_m.get(), bingamma_m.get() + emittedBins, bingamma_m.get(), OpAddAssign());
357 reduce(binemitted_m.get(), binemitted_m.get() + emittedBins, particlesInBin.get(), OpAddAssign());
358 for (int i = 0; i < emittedBins; i++) {
359 size_t &pInBin = particlesInBin[i];
360 if (pInBin != 0) {
361 bingamma_m[i] /= pInBin;
362 INFOMSG(level2 << "Bin " << std::setw(3) << i
363 << " gamma = " << std::setw(8) << std::scientific
364 << std::setprecision(5) << bingamma_m[i]
365 << "; NpInBin= " << std::setw(8)
366 << std::setfill(' ') << pInBin << endl);
367 } else {
368 bingamma_m[i] = 1.0;
369 INFOMSG(level2 << "Bin " << std::setw(3) << i << " has no particles " << endl);
371 s += pInBin;
372 }
373 particlesInBin.reset();
375
376 if (s != getTotalNum() && !OpalData::getInstance()->hasGlobalGeometry())
377 ERRORMSG("sum(Bins)= " << s << " != sum(R)= " << getTotalNum() << endl;);
378
379 if (emittedBins >= 2) {
380 for (int i = 1; i < emittedBins; i++) {
381 if (binemitted_m[i - 1] != 0 && binemitted_m[i] != 0)
382 INFOMSG(level2 << "d(gamma)= " << 100.0 * std::abs(bingamma_m[i - 1] - bingamma_m[i]) / bingamma_m[i] << " [%] "
383 << "between bin " << i - 1 << " and " << i << endl);
384 }
386}
387
388
389template <class T, unsigned Dim>
391
392 const int emittedBins = pbin_m->getLastemittedBin();
393
394 for (int i = 0; i < emittedBins; i++)
395 bingamma_m[i] = 0.0;
396 for (unsigned int n = 0; n < getLocalNum(); n++) {
397 if ( this->Bin[n] > -1 ) {
398 bingamma_m[this->Bin[n]] += std::sqrt(1.0 + dot(this->P[n], this->P[n]));
399 }
400 }
401
402 allreduce(*bingamma_m.get(), emittedBins, std::plus<double>());
404 for (int i = 0; i < emittedBins; i++) {
405 if (pbin_m->getTotalNumPerBin(i) > 0) {
406 bingamma_m[i] /= pbin_m->getTotalNumPerBin(i);
407 } else {
408 bingamma_m[i] = 0.0;
410 INFOMSG("Bin " << i << " : particle number = " << pbin_m->getTotalNumPerBin(i)
411 << " gamma = " << bingamma_m[i] << endl);
412 }
414}
415
416template <class T, unsigned Dim>
418 momentsComputer_m.computeDebyeLength(*this, rmsDensity_m);
419
421
423template <class T, unsigned Dim>
425 return bingamma_m[bin];
427
428
429template <class T, unsigned Dim>
430void PartBunchBase<T, Dim>::setBinCharge(int bin, double q) {
431 this->Q = where(eq(this->Bin, bin), q, 0.0);
433
435template <class T, unsigned Dim>
437 this->Q = where(eq(this->Bin, bin), this->qi_m, 0.0);
439
441template <class T, unsigned Dim>
444 std::size_t localnum = 0;
445 const Vector_t meanR = get_rmean();
447 for (unsigned long k = 0; k < getLocalNum(); ++ k)
448 if (std::abs(R[k](0) - meanR(0)) > x(0) ||
449 std::abs(R[k](1) - meanR(1)) > x(1) ||
450 std::abs(R[k](2) - meanR(2)) > x(2)) {
452 ++localnum;
453 }
455 gather(&localnum, &globalPartPerNode_m[0], 1);
456
457 size_t npOutside = std::accumulate(globalPartPerNode_m.get(),
458 globalPartPerNode_m.get() + Ippl::getNodes(), 0,
459 std::plus<size_t>());
460
461 return npOutside;
463
464
474template <class T, unsigned Dim>
476 std::vector<double>& lineDensity,
477 std::pair<double, double>& meshInfo) {
478 Vector_t rmin, rmax;
479 get_bounds(rmin, rmax);
480
481 if (nBins < 2) {
482 Vektor<int, 3>/*NDIndex<3>*/ grid;
483 this->updateDomainLength(grid);
484 nBins = grid[2];
485 }
487 double length = rmax(2) - rmin(2);
488 double zmin = rmin(2) - dh_m * length, zmax = rmax(2) + dh_m * length;
489 double hz = (zmax - zmin) / (nBins - 2);
490 double perMeter = 1.0 / hz;//(zmax - zmin);
491 zmin -= hz;
493 lineDensity.resize(nBins, 0.0);
494 std::fill(lineDensity.begin(), lineDensity.end(), 0.0);
495
496 const unsigned int lN = getLocalNum();
497 for (unsigned int i = 0; i < lN; ++ i) {
498 const double z = R[i](2) - 0.5 * hz;
499 unsigned int idx = (z - zmin) / hz;
500 double tau = (z - zmin) / hz - idx;
502 lineDensity[idx] += Q[i] * (1.0 - tau) * perMeter;
503 lineDensity[idx + 1] += Q[i] * tau * perMeter;
505
506 reduce(&(lineDensity[0]), &(lineDensity[0]) + nBins, &(lineDensity[0]), OpAddAssign());
507
508 meshInfo.first = zmin;
509 meshInfo.second = hz;
511
513template <class T, unsigned Dim>
515 /*
516 Assume rmin_m < 0.0
517 */
518
519 IpplTimings::startTimer(boundpTimer_m);
520 //if (!R.isDirty() && stateOfLastBoundP_ == unit_state_) return;
521 if ( !(R.isDirty() || ID.isDirty() ) && stateOfLastBoundP_ == unit_state_) return; //-DW
522
523 stateOfLastBoundP_ = unit_state_;
524
525 if (!isGridFixed()) {
526 const int dimIdx = (dcBeam_m? 2: 3);
527
534 this->updateDomainLength(nr_m);
535 IpplTimings::startTimer(boundpBoundsTimer_m);
536 getSolverMeshBounds(rmin_m, rmax_m);
537 IpplTimings::stopTimer(boundpBoundsTimer_m);
538 Vector_t len = rmax_m - rmin_m;
539
540 double volume = 1.0;
541 for (int i = 0; i < dimIdx; i++) {
542 double length = std::abs(rmax_m[i] - rmin_m[i]);
543 if (length < 1e-10) {
544 rmax_m[i] += 1e-10;
545 rmin_m[i] -= 1e-10;
546 } else {
547 rmax_m[i] += dh_m * length;
548 rmin_m[i] -= dh_m * length;
549 }
550 hr_m[i] = (rmax_m[i] - rmin_m[i]) / (nr_m[i] - 1);
551 }
552 if (dcBeam_m) {
553 rmax_m[2] = rmin_m[2] + periodLength_m;
554 hr_m[2] = periodLength_m / (nr_m[2] - 1);
555 }
556 for (int i = 0; i < dimIdx; ++ i) {
557 volume *= std::abs(rmax_m[i] - rmin_m[i]);
558 }
560 if (getIfBeamEmitting() && dist_m != nullptr) {
561 // keep particles per cell ratio high, don't spread a hand full particles across the whole grid
562 double percent = std::max(1.0 / (nr_m[2] - 1), dist_m->getPercentageEmitted());
563 double length = std::abs(rmax_m[2] - rmin_m[2]) / (1.0 + 2 * dh_m);
564 if (percent < 1.0 && percent > 0.0) {
565 rmax_m[2] -= dh_m * length;
566 rmin_m[2] = rmax_m[2] - length / percent;
567
568 length /= percent;
569
570 rmax_m[2] += dh_m * length;
571 rmin_m[2] -= dh_m * length;
572
573 hr_m[2] = (rmax_m[2] - rmin_m[2]) / (nr_m[2] - 1);
577 if (volume < 1e-21 && getTotalNum() > 1 && std::abs(sum(Q)) > 0.0) {
578 WARNMSG(level1 << "!!! Extremely high particle density detected !!!" << endl);
580 //INFOMSG("It is a full boundp hz= " << hr_m << " rmax= " << rmax_m << " rmin= " << rmin_m << endl);
581
582 if (hr_m[0] * hr_m[1] * hr_m[2] <= 0) {
583 throw GeneralClassicException("boundp() ", "h<0, can not build a mesh");
584 }
586 if (meshFit_m.type == MeshFitType::CORE) {
587 // the range of the cell centres, which the solve on a core-fitted mesh gathers
588 scMeshMin_m = rmin_m;
589 scMeshMax_m = rmax_m;
590 }
591
592 Vector_t origin = rmin_m - Vector_t({hr_m[0] / 2.0, hr_m[1] / 2.0, hr_m[2] / 2.0});
593 this->updateFields(hr_m, origin);
594
595 if (fs_m->getFieldSolverType() == FieldSolverType::P3M) {
596 Layout_t* layoutp = static_cast<Layout_t*>(&getLayout());
597 layoutp->setCacheDimension(0,fs_m->solver_m->getinteractionRadius());
598 layoutp->setCacheDimension(1,fs_m->solver_m->getinteractionRadius());
600 double gammaz = sum(this->P)[2] / getTotalNum();
601 gammaz *= gammaz;
602 gammaz = std::sqrt(gammaz + 1.0);
603
604 //Interaction radius is set in the boosted frame but ghost particles
605 //are identified in the lab frame that's why we divide by gammaz here
606 layoutp->setCacheDimension(2,fs_m->solver_m->getinteractionRadius()/gammaz);
607 layoutp->enableCaching();
611 IpplTimings::startTimer(boundpUpdateTimer_m);
612 update();
613 IpplTimings::stopTimer(boundpUpdateTimer_m);
614 R.resetDirtyFlag();
615
616 IpplTimings::stopTimer(boundpTimer_m);
617}
618
619
620template <class T, unsigned Dim>
622
623 Vector_t len;
624 const int dimIdx = 3;
625 IpplTimings::startTimer(boundpTimer_m);
626
627 std::unique_ptr<size_t[]> countLost;
628 if (weHaveBins()) {
629 const int tempN = pbin_m->getLastemittedBin();
630 countLost = std::unique_ptr<size_t[]>(new size_t[tempN]);
631 for (int ii = 0; ii < tempN; ii++) countLost[ii] = 0;
632 }
633
634 this->updateDomainLength(nr_m);
635
636 IpplTimings::startTimer(boundpBoundsTimer_m);
637 get_bounds(rmin_m, rmax_m);
638 IpplTimings::stopTimer(boundpBoundsTimer_m);
639
640 len = rmax_m - rmin_m;
641
642 calcBeamParameters();
643
644 int checkfactor = Options::remotePartDel;
645 if (checkfactor != 0) {
646 //INFOMSG("checkfactor= " << checkfactor << endl);
647 // check the bunch if its full size is larger than checkfactor times of its rms size
648 Vector_t rmean = momentsComputer_m.getMeanPosition();
649 Vector_t rrms = momentsComputer_m.getStandardDeviationPosition();
650 if(checkfactor < 0) {
651 checkfactor *= -1;
652 if (len[0] > checkfactor * rrms[0] ||
653 len[1] > checkfactor * rrms[1] ||
654 len[2] > checkfactor * rrms[2])
655 {
656 for(unsigned int ii = 0; ii < this->getLocalNum(); ii++) {
657 /* delete the particle if the distance to the beam center
658 * is larger than 8 times of beam's rms size
659 */
660 if (std::abs(R[ii](0) - rmean(0)) > checkfactor * rrms[0] ||
661 std::abs(R[ii](1) - rmean(1)) > checkfactor * rrms[1] ||
662 std::abs(R[ii](2) - rmean(2)) > checkfactor * rrms[2])
663 {
664 // put particle onto deletion list
665 destroy(1, ii);
666 //update bin parameter
667 if (weHaveBins())
668 countLost[Bin[ii]] += 1 ;
669 // MESHFIT=CORE: flag it lost, so that the core selection
670 // below leaves it out
671 if (meshFit_m.type == MeshFitType::CORE)
672 Bin[ii] = -1;
673 /* INFOMSG("REMOTE PARTICLE DELETION: ID = " << ID[ii] << ", R = " << R[ii]
674 * << ", beam rms = " << rrms_m << endl;);
675 */
676 }
677 }
678 }
679 }
680 else {
681 if (len[0] > checkfactor * rrms[0] ||
682 len[2] > checkfactor * rrms[2])
683 {
684 for(unsigned int ii = 0; ii < this->getLocalNum(); ii++) {
685 /* delete the particle if the distance to the beam center
686 * is larger than 8 times of beam's rms size
687 */
688 if (std::abs(R[ii](0) - rmean(0)) > checkfactor * rrms[0] ||
689 std::abs(R[ii](2) - rmean(2)) > checkfactor * rrms[2])
690 {
691 // put particle onto deletion list
692 destroy(1, ii);
693 //update bin parameter
694 if (weHaveBins())
695 countLost[Bin[ii]] += 1 ;
696 // MESHFIT=CORE: flag it lost, so that the core selection
697 // below leaves it out
698 if (meshFit_m.type == MeshFitType::CORE)
699 Bin[ii] = -1;
700 /* INFOMSG("REMOTE PARTICLE DELETION: ID = " << ID[ii] << ", R = " << R[ii]
701 * << ", beam rms = " << rrms_m << endl;);
702 */
703 }
704 }
705 }
706 }
707 }
708
709 // The REMOTEPARTDEL test takes the bounds of all particles, the mesh those of
710 // getSolverMeshBounds(), as in boundp(). The particles queued for deletion above are
711 // still in the bunch until update() below; with MESHFIT=CORE they are flagged lost.
712 if (meshFit_m.type == MeshFitType::CORE) {
713 IpplTimings::startTimer(boundpBoundsTimer_m);
714 getSolverMeshBounds(rmin_m, rmax_m);
715 IpplTimings::stopTimer(boundpBoundsTimer_m);
716 }
717
718 for (int i = 0; i < dimIdx; i++) {
719 double length = std::abs(rmax_m[i] - rmin_m[i]);
720 if (length < 1e-10) {
721 rmax_m[i] += 1e-10;
722 rmin_m[i] -= 1e-10;
723 } else {
724 rmax_m[i] += dh_m * length;
725 rmin_m[i] -= dh_m * length;
726 }
727 hr_m[i] = (rmax_m[i] - rmin_m[i]) / (nr_m[i] - 1);
728 }
729
730 if (meshFit_m.type == MeshFitType::CORE) {
731 // the range of the cell centres, which the solve on a core-fitted mesh gathers
732 scMeshMin_m = rmin_m;
733 scMeshMax_m = rmax_m;
734 }
735
736 // rescale mesh, with the same origin as boundp(). With the origin at rmin_m instead,
737 // every call moved all rank boundaries by half a cell, and the next boundp() moved them
738 // back: the particles near each cut changed owner twice, and the push in between ran in
739 // a skewed decomposition.
740 Vector_t origin = rmin_m - Vector_t({hr_m[0] / 2.0, hr_m[1] / 2.0, hr_m[2] / 2.0});
741 this->updateFields(hr_m, origin);
742
743 if (weHaveBins()) {
744 pbin_m->updatePartInBin_cyc(countLost.get());
745 }
746
747 IpplTimings::startTimer(boundpUpdateTimer_m);
748 update();
749 IpplTimings::stopTimer(boundpUpdateTimer_m);
750
751 /* we also need to update the number of particles per bunch
752 * expensive since does an allreduce!
753 *
754 * This has to come after update(): destroy() above only queues the
755 * particles, update() is what removes them. Counting before it left the
756 * per-bunch totals holding the remotely deleted particles, and the next
757 * deleteParticle() then failed its consistency check
758 * ("Total number of particles N != N+k (sum over all bunches)").
759 */
760 countTotalNumPerBunch();
761
762 IpplTimings::stopTimer(boundpTimer_m);
763}
764
765
766template <class T, unsigned Dim>
768
769 this->updateDomainLength(nr_m);
770
771 std::vector<size_t> tmpbinemitted;
772
773 boundp();
774
775 size_t ne = 0;
776 const size_t localNum = getLocalNum();
777
778 double rzmean = momentsComputer_m.getMeanPosition()(2);
779 double rzrms = momentsComputer_m.getStandardDeviationPosition()(2);
780 const bool haveEnergyBins = weHaveEnergyBins();
781 if (haveEnergyBins) {
782 tmpbinemitted.resize(getNumberOfEnergyBins(), 0.0);
783 }
784 for (unsigned int i = 0; i < localNum; i++) {
785 if (Bin[i] < 0 || (Options::remotePartDel > 0 && std::abs(R[i](2) - rzmean) < Options::remotePartDel * rzrms)) {
786 ne++;
787 destroy(1, i);
788 } else if (haveEnergyBins) {
789 tmpbinemitted[Bin[i]]++;
790 }
791 }
792
793 boundp();
794
795 calcBeamParameters();
796 gatherLoadBalanceStatistics();
797
798 if (haveEnergyBins) {
799 const int lastBin = dist_m->getLastEmittedEnergyBin();
800 for (int i = 0; i < lastBin; i++) {
801 binemitted_m[i] = tmpbinemitted[i];
802 }
803 }
804 reduce(ne, ne, OpAddAssign());
805 return ne;
806}
807
808
809template <class T, unsigned Dim>
811
812 std::unique_ptr<size_t[]> tmpbinemitted;
813
814 const size_t localNum = getLocalNum();
815 const size_t totalNum = getTotalNum();
816 size_t ne = 0;
817
818 if (weHaveEnergyBins()) {
819 tmpbinemitted = std::unique_ptr<size_t[]>(new size_t[getNumberOfEnergyBins()]);
820 for (int i = 0; i < getNumberOfEnergyBins(); i++) {
821 tmpbinemitted[i] = 0;
822 }
823 for (unsigned int i = 0; i < localNum; i++) {
824 if (Bin[i] < 0) {
825 destroy(1, i);
826 ++ ne;
827 } else
828 tmpbinemitted[Bin[i]]++;
829 }
830 } else {
831 Inform dmsg("destroy: ", INFORM_ALL_NODES);
832 for (size_t i = 0; i < localNum; i++) {
833 if ((Bin[i] < 0)) {
834 ne++;
835 destroy(1, i);
836 }
837 }
838 }
839
840 if (ne > 0) {
841 performDestroy(true);
842 }
843
844 calcBeamParameters();
845 gatherLoadBalanceStatistics();
846
847 if (weHaveEnergyBins()) {
848 const int lastBin = dist_m->getLastEmittedEnergyBin();
849 for (int i = 0; i < lastBin; i++) {
850 binemitted_m[i] = tmpbinemitted[i];
851 }
852 }
853 size_t newTotalNum = getLocalNum();
854 reduce(newTotalNum, newTotalNum, OpAddAssign());
855
856 setTotalNum(newTotalNum);
857
858 return totalNum - newTotalNum;
859}
860
861
862template <class T, unsigned Dim>
864 return 0.0;
865}
866
867template <class T, unsigned Dim>
869 return 0.0;
870}
871
872template <class T, unsigned Dim>
874 return 0.0;
875}
876
877template <class T, unsigned Dim>
879 return 0.0;
880}
881
882template <class T, unsigned Dim>
884 return 0;
885}
886
887//ff
888template <class T, unsigned Dim>
890 return this->R[i](0);
891}
892
893//ff
894template <class T, unsigned Dim>
896 return this->R[i](1);
897}
898
899//ff
900template <class T, unsigned Dim>
902 return this->R[i](2);
903}
904
905//ff
906template <class T, unsigned Dim>
908 return 0.0;
909}
910
911//ff
912template <class T, unsigned Dim>
914 return 0.0;
915}
916
917
918template <class T, unsigned Dim>
919void PartBunchBase<T, Dim>::setZ(int /*i*/, double /*zcoo*/) {
920};
921
922
923template <class T, unsigned Dim>
925
926 this->getLocalBounds(rmin, rmax);
927
928 double min[2*Dim];
929
930 for (unsigned int i = 0; i < Dim; ++i) {
931 min[2*i] = rmin[i];
932 min[2*i + 1] = -rmax[i];
933 }
934
935 allreduce(min, 2*Dim, std::less<double>());
936
937 for (unsigned int i = 0; i < Dim; ++i) {
938 rmin[i] = min[2*i];
939 rmax[i] = -min[2*i + 1];
940 }
941}
942
943
944template <class T, unsigned Dim>
946 const size_t localNum = getLocalNum();
947 if (localNum == 0) {
948 double maxValue = 1e8;
949 rmin = Vector_t({maxValue, maxValue, maxValue});
950 rmax = Vector_t({-maxValue, -maxValue, -maxValue});
951 return;
952 }
953
954 rmin = R[0];
955 rmax = R[0];
956 for (size_t i = 1; i < localNum; ++ i) {
957 for (unsigned short d = 0; d < 3u; ++ d) {
958 if (rmin(d) > R[i](d)) rmin(d) = R[i](d);
959 else if (rmax(d) < R[i](d)) rmax(d) = R[i](d);
960 }
961 }
962}
963
964
965template <class T, unsigned Dim>
966std::pair<Vector_t, double> PartBunchBase<T, Dim>::getBoundingSphere() {
967 Vector_t rmin, rmax;
968 get_bounds(rmin, rmax);
969
970 std::pair<Vector_t, double> sphere;
971 sphere.first = 0.5 * (rmin + rmax);
972 sphere.second = std::sqrt(dot(rmax - sphere.first, rmax - sphere.first));
973
974 return sphere;
975}
976
977
978template <class T, unsigned Dim>
980 Vector_t rmin, rmax;
981 getLocalBounds(rmin, rmax);
982
983 std::pair<Vector_t, double> sphere;
984 sphere.first = 0.5 * (rmin + rmax);
985 sphere.second = std::sqrt(dot(rmax - sphere.first, rmax - sphere.first));
986
987 return sphere;
988}
989
990
991template <class T, unsigned Dim>
993 Inform msg("PartBunch ");
994
995 size_t i = getLocalNum();
996 create(1);
997
998 R[i] = particle.getR();
999 P[i] = particle.getP();
1000
1001 update();
1002 msg << "Created one particle i= " << i << endl;
1003}
1004
1005
1006template <class T, unsigned Dim>
1008 R[ii](0) = z[0];
1009 P[ii](0) = z[1];
1010 R[ii](1) = z[2];
1011 P[ii](1) = z[3];
1012 R[ii](2) = z[4];
1013 P[ii](2) = z[5];
1014}
1015
1016
1017template <class T, unsigned Dim>
1019 R[ii] = particle.getR();
1020 P[ii] = particle.getP();
1021}
1022
1023
1024template <class T, unsigned Dim>
1026 OpalParticle particle(ID[ii],
1027 Vector_t({R[ii](0), R[ii](1), 0}), P[ii],
1028 R[ii](2), Q[ii], M[ii]);
1029 return particle;
1030}
1031
1032
1033template <class T, unsigned Dim>
1035 double& axmax, double& aymax) {
1036 axmax = aymax = 0.0;
1037 OpalParticle particle;
1038
1039 for (unsigned int ii = 0; ii < getLocalNum(); ii++) {
1040
1041 particle = getParticle(ii);
1042 FVector<double, 6> vec({particle.getX(), particle.getPx(),
1043 particle.getY(), particle.getPy(),
1044 particle.getZ(), particle.getPz()});
1045 FVector<double, 6> result;
1046 result = D * vec;
1047 // double xnor =
1048 // D(0, 0) * part.getX() + D(0, 1) * part.getPx() + D(0, 2) * part.getY() +
1049 // D(0, 3) * part.getPy() + D(0, 4) * part.getL() + D(0, 5) * part.getPLon();
1050 // double pxnor =
1051 // D(1, 0) * part.getX() + D(1, 1) * part.getPx() + D(1, 2) * part.getY() +
1052 // D(1, 3) * part.getPy() + D(1, 4) * part.getL() + D(1, 5) * part.getPLon();
1053 // double ynor =
1054 // D(2, 0) * part.getX() + D(2, 1) * part.getPx() + D(2, 2) * part.getY() +
1055 // D(2, 3) * part.getPy() + D(2, 4) * part.getL() + D(2, 5) * part.getPLon();
1056 // double pynor =
1057 // D(3, 0) * part.getX() + D(3, 1) * part.getPx() + D(3, 2) * part.getY() +
1058 // D(3, 3) * part.getPy() + D(3, 4) * part.getL() + D(3, 5) * part.getPLon();
1059
1060 axmax = std::max(axmax, (std::pow(result[0], 2) + std::pow(result[1], 2)));
1061 aymax = std::max(aymax, (std::pow(result[2], 2) + std::pow(result[3], 2)));
1062 }
1063}
1064
1065
1066template <class T, unsigned Dim>
1068 dt_m = dt;
1069}
1070
1071
1072template <class T, unsigned Dim>
1074 return dt_m;
1075}
1076
1077
1078template <class T, unsigned Dim>
1080 t_m = t;
1081}
1082
1083
1084template <class T, unsigned Dim>
1086 t_m += dt_m;
1087}
1088
1089
1090template <class T, unsigned Dim>
1092 return t_m;
1093}
1094
1095
1096template <class T, unsigned Dim>
1098 return spos_m;
1099}
1100
1101
1102template <class T, unsigned Dim>
1104 spos_m = s;
1105}
1106
1107
1108template <class T, unsigned Dim>
1110 return momentsComputer_m.getMeanGamma();
1111}
1112
1113
1114template <class T, unsigned Dim>
1116 return momentsComputer_m.getMeanKineticEnergy();
1117}
1118
1119
1120template <class T, unsigned Dim>
1122 return momentsComputer_m.getTemperature();
1123}
1124
1125template <class T, unsigned Dim>
1127 return momentsComputer_m.getDebyeLength();
1128}
1129
1130template <class T, unsigned Dim>
1132 return momentsComputer_m.getPlasmaParameter();
1133}
1134
1135template <class T, unsigned Dim>
1137 return rmsDensity_m;
1138}
1139
1140template <class T, unsigned Dim>
1142 return rmin_m;
1143}
1144
1145
1146template <class T, unsigned Dim>
1148 return rmax_m;
1149}
1150
1151
1152template <class T, unsigned Dim>
1154 return momentsComputer_m.getMeanPosition();
1155}
1156
1157
1158template <class T, unsigned Dim>
1160 return momentsComputer_m.getStandardDeviationPosition();
1161}
1162
1163
1164template <class T, unsigned Dim>
1166 return momentsComputer_m.getStandardDeviationRP();
1167}
1168
1169
1170template <class T, unsigned Dim>
1172 return momentsComputer_m.getMeanPosition();
1173}
1174
1175
1176template <class T, unsigned Dim>
1178 return momentsComputer_m.getStandardDeviationMomentum();
1179}
1180
1181
1182template <class T, unsigned Dim>
1184 return momentsComputer_m.getMeanMomentum();
1185}
1186
1187
1188template <class T, unsigned Dim>
1190 if (dist_m)// && dist_m->getType() != DistrTypeT::FROMFILE)
1191 return dist_m->get_pmean();
1192
1193 double gamma = 0.1 / getM() + 1; // set default 0.1 eV
1194 return Vector_t({0, 0, std::sqrt(std::pow(gamma, 2) - 1)});
1195}
1196
1197
1198template <class T, unsigned Dim>
1200 return momentsComputer_m.getGeometricEmittance();
1201}
1202
1203
1204template <class T, unsigned Dim>
1206 return momentsComputer_m.getNormalizedEmittance();
1207}
1208
1209
1210template <class T, unsigned Dim>
1212 return momentsComputer_m.getHalo();
1213}
1214
1215template <class T, unsigned Dim>
1217 return momentsComputer_m.get68Percentile();
1218}
1219
1220template <class T, unsigned Dim>
1222 return momentsComputer_m.get95Percentile();
1223}
1224
1225template <class T, unsigned Dim>
1227 return momentsComputer_m.get99Percentile();
1228}
1229
1230template <class T, unsigned Dim>
1232 return momentsComputer_m.get99_99Percentile();
1233}
1234
1235template <class T, unsigned Dim>
1237 return momentsComputer_m.getNormalizedEmittance68Percentile();
1238}
1239
1240template <class T, unsigned Dim>
1242 return momentsComputer_m.getNormalizedEmittance95Percentile();
1243}
1244
1245template <class T, unsigned Dim>
1247 return momentsComputer_m.getNormalizedEmittance99Percentile();
1248}
1249
1250template <class T, unsigned Dim>
1252 return momentsComputer_m.getNormalizedEmittance99_99Percentile();
1253}
1254
1255template <class T, unsigned Dim>
1257 return momentsComputer_m.getDx();
1258}
1259
1260
1261template <class T, unsigned Dim>
1263 return momentsComputer_m.getDy();
1264}
1265
1266
1267template <class T, unsigned Dim>
1269 return momentsComputer_m.getDDx();
1270}
1271
1272
1273template <class T, unsigned Dim>
1275 return momentsComputer_m.getDDy();
1276}
1277
1278
1279template <class T, unsigned Dim>
1281 return hr_m;
1282}
1283
1284
1285template <class T, unsigned Dim>
1287 dh_m = dh;
1288}
1289
1290
1291template <class T, unsigned Dim>
1293 // A mesh fitted to the core leaves the far particles outside its domain. The particle
1294 // layout then gives each of them to the rank that owns the nearest point of the domain.
1295 // This has to be set before the first mesh fit of the run, in Distribution::create()
1296 // or at a restart: with more than one rank, update() would otherwise refuse a particle
1297 // outside the domain. The layout is only touched when CORE is set or unset.
1298 if (meshFit.type == MeshFitType::CORE || meshFit_m.type == MeshFitType::CORE) {
1299 Layout_t* layoutp = static_cast<Layout_t*>(&getLayout());
1300 try {
1301 layoutp->setOutsideToNearest(meshFit.type == MeshFitType::CORE);
1302 } catch (const IpplException& ex) {
1303 throw OpalException(ex.where(), ex.what());
1304 }
1305 }
1306
1307 // created here, so that the timing file of a run without CORE does not list them
1308 if (meshFit.type == MeshFitType::CORE) {
1309 meshFitTimer_m = IpplTimings::getTimer("SC mesh fit");
1310 farFieldTimer_m = IpplTimings::getTimer("SC far field");
1311 exactCoreTimer_m = IpplTimings::getTimer("SC exact core field");
1312 }
1313
1314 meshFit_m = meshFit;
1315 // nothing selected or solved yet in this TRACK/RUN; it starts in CORE mode
1316 scCore_m = CoreFitSC::CoreSelection();
1317 scMode_m = CoreFitSC::ModeState();
1318 scRepartitionDue_m = false;
1319 scHasSolved_m = false;
1320 scStatistics_m = MeshFitStatistics();
1321 scWarned_m = 0;
1322 scCoreMesh_m = false;
1323 scNumCore_m = 0;
1324 scFitted_m = false;
1325}
1326
1327
1328template <class T, unsigned Dim>
1330 return meshFit_m;
1331}
1332
1333
1334template <class T, unsigned Dim>
1336 meshFitSolveStep_m = solveStep;
1337}
1338
1339
1340template <class T, unsigned Dim>
1342 return scCore_m;
1343}
1344
1345
1346template <class T, unsigned Dim>
1348 rmin = scFullMin_m;
1349 rmax = scFullMax_m;
1350}
1351
1352
1353template <class T, unsigned Dim>
1355 // the enlargement of boundp(), without its DC beam and emission cases
1356 Vector_t hr;
1357 for (unsigned short d = 0; d < 3u; ++ d) {
1358 const double length = std::abs(rmax[d] - rmin[d]);
1359 const double margin = (length < 1e-10) ? 1e-10 : dh_m * length;
1360 hr[d] = ((rmax[d] + margin) - (rmin[d] - margin)) / (nr_m[d] - 1);
1361 }
1362 return hr;
1363}
1364
1365
1366template <class T, unsigned Dim>
1368 return scMode_m;
1369}
1370
1371
1372template <class T, unsigned Dim>
1374 scMode_m = mode;
1375}
1376
1377
1378template <class T, unsigned Dim>
1380 return meshFit_m.type == MeshFitType::CORE && scCoreMesh_m;
1381}
1382
1383
1384template <class T, unsigned Dim>
1386 return meshFit_m.type == MeshFitType::CORE && scRepartitionDue_m;
1387}
1388
1389
1390template <class T, unsigned Dim>
1393 return scStatistics_m;
1394}
1395
1396
1397template <class T, unsigned Dim>
1399 scStatistics_m.turnSolves = 0;
1400 scStatistics_m.turnFullSolves = 0;
1401 scWarned_m = 0;
1402}
1403
1404
1405template <class T, unsigned Dim>
1406void PartBunchBase<T, Dim>::warnMeshFitOnce(MeshFitWarning warning, const std::string& message) {
1407 if ((scWarned_m & warning) == 0) {
1408 scWarned_m |= warning;
1409 *gmsg << "* Warning: SC mesh fit at integration step " << getLocalTrackStep() + 1
1410 << ": " << message << " (at most once per turn)" << endl;
1411 }
1412}
1413
1414
1415template <class T, unsigned Dim>
1417 get_bounds(rmin, rmax);
1418 if (meshFit_m.type != MeshFitType::CORE) {
1419 return;
1420 }
1421
1422 // The core of the particles in the frame of this fit. Every fit selects, so that the
1423 // mesh and the particle classes of the solve always belong to the same box.
1424 IpplTimings::startTimer(meshFitTimer_m);
1425 const ParticleAttrib<Vector_t>& Rc = R;
1426 const ParticleAttrib<double>& Qc = Q;
1427 const ParticleAttrib<int>& Binc = Bin;
1428 const size_t localNum = getLocalNum();
1429 const CoreFitSC::CoreSelection selection =
1430 CoreFitSC::selectCore(localNum > 0 ? &Rc[0] : nullptr,
1431 localNum > 0 ? &Qc[0] : nullptr,
1432 localNum > 0 ? &Binc[0] : nullptr,
1433 localNum, meshFit_m.nSigma, meshFit_m.clip,
1435 IpplTimings::stopTimer(meshFitTimer_m);
1436
1437 // Only the fit of a space-charge solve step decides the mode, from reduced values, so
1438 // that every rank switches, and at most once per step. It is also the fit reported in
1439 // the stat file and the log.
1440 if (meshFitSolveStep_m) {
1441 const CoreFitSC::ModeState previous = scMode_m;
1442 scMode_m = CoreFitSC::decideMode(previous, selection.numCore, selection.numLive,
1443 selection.getFarChargeFraction(),
1444 meshFit_m.maxFarFraction, Options::repartFreq);
1445 const bool switched = (scMode_m.mode != previous.mode);
1446 scRepartitionDue_m = (switched || !scHasSolved_m);
1447 scHasSolved_m = true;
1448
1449 scCore_m = selection;
1450 scFullMin_m = rmin;
1451 scFullMax_m = rmax;
1452
1453 // set by the solve on a core-fitted mesh
1454 scStatistics_m.numFlagged = 0;
1455 ++ scStatistics_m.turnSolves;
1456 if (scMode_m.mode == CoreFitSC::Mode::FULL) {
1457 ++ scStatistics_m.fullSolves;
1458 ++ scStatistics_m.turnFullSolves;
1459 }
1460 if (switched) {
1461 ++ scStatistics_m.modeSwitches;
1462 const bool toFull = (scMode_m.mode == CoreFitSC::Mode::FULL);
1463 *gmsg << "* SC mesh fit at integration step " << getLocalTrackStep() + 1
1464 << ": the mesh is fitted to " << (toFull ? "all particles" : "the core")
1465 << " from now on (MESHFIT mode " << (toFull ? "FULL" : "CORE") << "), "
1466 << selection.numCore << " of " << selection.numLive
1467 << " live particles in the core, far charge "
1468 << 100.0 * selection.getFarChargeFraction() << " % of the live charge"
1469 << endl;
1470 }
1471
1473 std::ostringstream message;
1474 message << "the far charge is " << 100.0 * selection.getFarChargeFraction()
1475 << " % of the live charge (MESHFITMAXFAR "
1476 << 100.0 * meshFit_m.maxFarFraction << " %)";
1477 warnMeshFitOnce(FarChargeWarning, message.str());
1478 }
1479 // a far particle lies outside the core bounds in some axis, so these can only be
1480 // equal to the bounds of all particles if something is wrong
1481 if (selection.numFar > 0 && selection.numCore > 0 &&
1482 selection.boundsMin == rmin && selection.boundsMax == rmax) {
1483 warnMeshFitOnce(FullBoxWarning, "the core bounds equal the bounds of all "
1484 "particles, although there are far particles");
1485 }
1486 }
1487
1488 scFitted_m = true;
1489 scNumCore_m = selection.numCore;
1490 scCoreMesh_m = (scMode_m.mode == CoreFitSC::Mode::CORE && selection.numCore > 0);
1491 if (scCoreMesh_m) {
1492 // The core bounds, widened to the particles flagged lost within the core window:
1493 // they stay in the bunch until the tracker deletes them, and boundp_destroyCycl()
1494 // flags those it queues for deletion. With a MESHFITNSIGMA so large that every
1495 // particle lies in the window, the mesh is that of MESHFIT=ALL.
1496 IpplTimings::startTimer(meshFitTimer_m);
1497 CoreFitSC::getMeshBox(localNum > 0 ? &Rc[0] : nullptr,
1498 localNum > 0 ? &Binc[0] : nullptr,
1499 localNum, selection, meshFit_m.nSigma,
1500 CoreFitSC::IpplReducer(), rmin, rmax);
1501 IpplTimings::stopTimer(meshFitTimer_m);
1502 scBoxMin_m = rmin;
1503 scBoxMax_m = rmax;
1504 }
1505}
1506
1507
1508template <class T, unsigned Dim>
1510 if (meshFit_m.type != MeshFitType::CORE || !scFitted_m) {
1511 return;
1512 }
1513
1514 // Particles outside the domain [origin, origin + nr h) of the mesh, counted here and not
1515 // by the particle layout, whose swap does not run on one rank. After a fit to the core
1516 // only particles outside the core can be outside the mesh.
1517 const NDRegion<T, Dim>& domain =
1518 static_cast<Layout_t*>(&getLayout())->getLayout().getDomain();
1519 const ParticleAttrib<Vector_t>& Rc = R;
1520 const size_t localNum = getLocalNum();
1521 double counts[2] = {0.0, static_cast<double>(localNum)};
1522 for (size_t i = 0; i < localNum; ++ i) {
1523 for (unsigned int d = 0; d < Dim; ++ d) {
1524 if (!(Rc[i](d) >= domain[d].min() && Rc[i](d) < domain[d].max())) {
1525 counts[0] += 1.0;
1526 break;
1527 }
1528 }
1529 }
1530 allreduce(counts, 2, std::plus<double>());
1531 scStatistics_m.numOutside = static_cast<size_t>(counts[0]);
1532
1533 // In a frame the mesh was not fitted to, most particles are outside.
1534 const double numNotCore = std::max(counts[1] - static_cast<double>(scNumCore_m), 0.0);
1535 if (counts[0] > 2.0 * numNotCore + 100.0) {
1536 throw OpalException("PartBunchBase::update()",
1537 "FIELDSOLVER, MESHFIT=\"CORE\": " +
1538 std::to_string(scStatistics_m.numOutside) + " of " +
1539 std::to_string(static_cast<size_t>(counts[1])) +
1540 " particles are outside the space-charge mesh, but only " +
1541 std::to_string(static_cast<size_t>(numNotCore)) +
1542 " are outside the core of the last mesh fit. The particles were "
1543 "updated in a frame the mesh was not fitted to.");
1544 }
1545}
1546
1547
1548template <class T, unsigned Dim>
1550
1551 for (int i = 0; i < Ippl::getNodes(); i++)
1552 globalPartPerNode_m[i] = 0;
1553
1554 std::size_t localnum = getLocalNum();
1555 gather(&localnum, &globalPartPerNode_m[0], 1);
1556}
1557
1558
1559template <class T, unsigned Dim>
1561 return globalPartPerNode_m[p];
1562}
1563
1564
1565template <class T, unsigned Dim>
1569
1570
1571template <class T, unsigned Dim>
1573
1574 IpplTimings::startTimer(statParamTimer_m);
1575 get_bounds(rmin_m, rmax_m);
1576 momentsComputer_m.compute(*this);
1577 IpplTimings::stopTimer(statParamTimer_m);
1578}
1579
1580template <class T, unsigned Dim>
1582 return couplingConstant_m;
1583}
1584
1585
1586template <class T, unsigned Dim>
1588 couplingConstant_m = c;
1589}
1590
1591
1592template <class T, unsigned Dim>
1594 qi_m = q;
1595 if (getTotalNum() != 0)
1596 Q = qi_m;
1597 else
1598 WARNMSG("Could not set total charge in PartBunch::setCharge based on getTotalNum" << endl);
1599}
1600
1601
1602template <class T, unsigned Dim>
1604 qi_m = q;
1605}
1606
1607
1608template <class T, unsigned Dim>
1610 massPerParticle_m = mass;
1611 if (getTotalNum() != 0)
1612 M = mass;
1613}
1614
1615template <class T, unsigned Dim>
1617 massPerParticle_m = mass;
1618}
1619
1620
1621template <class T, unsigned Dim>
1623 return sum(Q);
1624}
1625
1626
1627template <class T, unsigned Dim>
1629 return qi_m;
1630}
1631
1632template <class T, unsigned Dim>
1634 return massPerParticle_m;
1635}
1636
1637template <class T, unsigned Dim>
1639 fs_m = fs;
1640 fs_m->initSolver(this);
1641
1646 if (!OpalData::getInstance()->hasBunchAllocated()) {
1647 this->initialize(fs_m->getFieldLayout());
1648// this->setMesh(fs_m->getMesh());
1649// this->setFieldLayout(fs_m->getFieldLayout());
1650 }
1651
1652}
1653
1654
1655template <class T, unsigned Dim>
1657 if (fs_m)
1658 return fs_m->hasValidSolver();
1659 else
1660 return false;
1661}
1662
1663
1665template <class T, unsigned Dim>
1667 if (fs_m) {
1668 return fs_m->getFieldSolverType();
1669 } else {
1670 return FieldSolverType::NONE;
1671 }
1672}
1673
1674
1675template <class T, unsigned Dim>
1677 stepsPerTurn_m = n;
1678}
1679
1680
1681template <class T, unsigned Dim>
1683 return stepsPerTurn_m;
1684}
1685
1686
1687template <class T, unsigned Dim>
1689 globalTrackStep_m = n;
1690}
1691
1692
1693template <class T, unsigned Dim>
1695 return globalTrackStep_m;
1696}
1697
1698
1699template <class T, unsigned Dim>
1701 localTrackStep_m = n;
1702}
1703
1704
1705template <class T, unsigned Dim>
1707 globalTrackStep_m++; localTrackStep_m++;
1708}
1709
1710
1711template <class T, unsigned Dim>
1713 return localTrackStep_m;
1714}
1715
1716
1717template <class T, unsigned Dim>
1719 numBunch_m = n;
1720 bunchTotalNum_m.resize(n);
1721 bunchLocalNum_m.resize(n);
1722}
1723
1724
1725template <class T, unsigned Dim>
1727 return numBunch_m;
1728}
1729
1730
1731template <class T, unsigned Dim>
1732void PartBunchBase<T, Dim>::setTotalNumPerBunch(size_t totalnum, short n) {
1733 PAssert_LT(n, (short)bunchTotalNum_m.size());
1734 bunchTotalNum_m[n] = totalnum;
1735}
1736
1737
1738template <class T, unsigned Dim>
1740 PAssert_LT(n, (short)bunchTotalNum_m.size());
1741 return bunchTotalNum_m[n];
1742}
1743
1744
1745template <class T, unsigned Dim>
1746void PartBunchBase<T, Dim>::setLocalNumPerBunch(size_t localnum, short n) {
1747 PAssert_LT(n, (short)bunchLocalNum_m.size());
1748 bunchLocalNum_m[n] = localnum;
1749}
1750
1751
1752template <class T, unsigned Dim>
1754 PAssert_LT(n, (short)bunchLocalNum_m.size());
1755 return bunchLocalNum_m[n];
1756}
1757
1758
1759template <class T, unsigned Dim>
1761 bunchTotalNum_m.clear();
1762 bunchTotalNum_m.resize(numBunch_m);
1763 bunchLocalNum_m.clear();
1764 bunchLocalNum_m.resize(numBunch_m);
1765
1766 for (size_t i = 0; i < this->getLocalNum(); ++i) {
1767 PAssert_LT(this->bunchNum[i], numBunch_m);
1768 ++bunchLocalNum_m[this->bunchNum[i]];
1769 }
1770
1771 allreduce(bunchLocalNum_m.data(), bunchTotalNum_m.data(),
1772 bunchLocalNum_m.size(), std::plus<size_t>());
1773
1774 size_t totalnum = std::accumulate(bunchTotalNum_m.begin(),
1775 bunchTotalNum_m.end(), 0);
1776
1777 if ( totalnum != this->getTotalNum() )
1778 throw OpalException("PartBunchBase::countTotalNumPerBunch()",
1779 "Sum of total number of particles per bunch (" +
1780 std::to_string(totalnum) + ") != total number of particles (" +
1781 std::to_string(this->getTotalNum()) + ")");
1782}
1783
1784
1785template <class T, unsigned Dim>
1787 globalMeanR_m = globalMeanR;
1788}
1789
1790
1791template <class T, unsigned Dim>
1793 return globalMeanR_m;
1794}
1795
1796
1797template <class T, unsigned Dim>
1799
1800 globalToLocalQuaternion_m = globalToLocalQuaternion;
1801}
1802
1803
1804template <class T, unsigned Dim>
1806 return globalToLocalQuaternion_m;
1807}
1808
1809
1810template <class T, unsigned Dim>
1812 SteptoLastInj_m = n;
1813}
1814
1815
1816template <class T, unsigned Dim>
1818 return SteptoLastInj_m;
1819}
1820
1821
1822template <class T, unsigned Dim>
1824
1825 const int emittedBins = pbin_m->getLastemittedBin();
1826 std::vector<double> phi(emittedBins);
1827 std::vector<double> px(emittedBins);
1828 std::vector<double> py(emittedBins);
1829 double meanPhi = 0.0;
1830
1831 for (int ii = 0; ii < emittedBins; ii++) {
1832 phi[ii] = 0.0;
1833 px[ii] = 0.0;
1834 py[ii] = 0.0;
1835 }
1836
1837 for (unsigned int ii = 0; ii < getLocalNum(); ii++) {
1838 px[Bin[ii]] += P[ii](0);
1839 py[Bin[ii]] += P[ii](1);
1840 }
1841
1842 ::reduce(px.begin(), px.end(), px.begin(), OpAddAssign());
1843 ::reduce(py.begin(), py.end(), py.begin(), OpAddAssign());
1844 for (int ii = 0; ii < emittedBins; ii++) {
1845 phi[ii] = calculateAngle(px[ii], py[ii]);
1846 meanPhi += phi[ii];
1847 INFOMSG("Bin " << ii << " mean phi = " << phi[ii] * Units::rad2deg - 90.0 << "[degree]" << endl);
1848 }
1849
1850 meanPhi /= emittedBins;
1851
1852 INFOMSG("mean phi of all particles " << meanPhi * Units::rad2deg - 90.0 << "[degree]" << endl);
1853
1854 return meanPhi;
1855}
1856
1857// this function reset the BinID for each particles according to its current beta*gamma
1858// it is for multi-turn extraction cyclotron with small energy gain
1859// the bin number can be different with the bunch number
1860
1861template <class T, unsigned Dim>
1863
1864
1865 INFOMSG("Before reset Bin: " << endl);
1866 calcGammas_cycl();
1867 int maxbin = pbin_m->getNBins();
1868 std::vector<size_t> partInBin(maxbin);
1869 for (int ii = 0; ii < maxbin; ii++) partInBin[ii] = 0;
1870
1871 double pMin0 = 1.0e9;
1872 double pMin = 0.0;
1873 double maxbinIndex = 0;
1874
1875 for (unsigned long int n = 0; n < getLocalNum(); n++) {
1876 double temp_betagamma = std::sqrt(std::pow(P[n](0), 2) + std::pow(P[n](1), 2));
1877 if (pMin0 > temp_betagamma)
1878 pMin0 = temp_betagamma;
1879 }
1880 reduce(pMin0, pMin, OpMinAssign());
1881 INFOMSG("minimal beta*gamma = " << pMin << endl);
1882
1883 double asinh0 = std::asinh(pMin);
1884 for (unsigned long int n = 0; n < getLocalNum(); n++) {
1885
1886 double temp_betagamma = std::sqrt(std::pow(P[n](0), 2) + std::pow(P[n](1), 2));
1887 int itsBinID = std::floor((std::asinh(temp_betagamma) - asinh0) / eta + 1.0E-6);
1888 Bin[n] = itsBinID;
1889 if (maxbinIndex < itsBinID) {
1890 maxbinIndex = itsBinID;
1891 }
1892
1893 if (itsBinID >= maxbin) {
1894 ERRORMSG("The bin number limit is " << maxbin << ", please increase the energy interval and try again" << endl);
1895 return false;
1896 } else
1897 partInBin[itsBinID]++;
1898
1899 }
1900
1901 // partInBin only count particle on the local node.
1902 pbin_m->resetPartInBin_cyc(partInBin.data(), maxbinIndex);
1903
1904 // after reset Particle Bin ID, update mass gamma of each bin again
1905 INFOMSG("After reset Bin: " << endl);
1906 calcGammas_cycl();
1907
1908 return true;
1909}
1910
1911
1912template <class T, unsigned Dim>
1914 int maxbin = pbin_m->getNBins();
1915 std::vector<size_t> partInBin(maxbin);
1916 for (int i = 0; i < maxbin; ++i) {
1917 partInBin[i] = 0;
1918 }
1919
1920 for (std::size_t i = 0; i < getLocalNum(); ++i) {
1921 partInBin[Bin[i]]++;
1922 }
1923
1924 // partInBin only count particle on the local node.
1925 pbin_m->resetPartInBin_cyc(partInBin.data(), numBunch_m - 1);
1926
1927 // after reset Particle Bin ID, update mass gamma of each bin again
1928 calcGammas_cycl();
1929
1930 return true;
1931}
1932
1933
1934template <class T, unsigned Dim>
1936 return reference->getQ();
1937}
1938
1939
1940template <class T, unsigned Dim>
1942 return reference->getM();
1943}
1944
1945
1946template <class T, unsigned Dim>
1948 return reference->getP();
1949}
1950
1951
1952template <class T, unsigned Dim>
1954 return reference->getE();
1955}
1956
1957
1958template <class T, unsigned Dim>
1960 return refPOrigin_m;
1961}
1962
1963template <class T, unsigned Dim>
1965 refPOrigin_m = origin;
1966}
1967
1968
1969template <class T, unsigned Dim>
1971 return refPType_m;
1972}
1973
1974template <class T, unsigned Dim>
1975void PartBunchBase<T, Dim>::setPType(const std::string& type) {
1976 refPType_m = ParticleProperties::getParticleType(type);
1977}
1978
1979
1980template <class T, unsigned Dim>
1982 return dist_m->getType();
1983}
1984
1985
1986template <class T, unsigned Dim>
1988 return reference->getMomentumTolerance();
1989}
1990
1991
1992template <class T, unsigned Dim>
1994 const_cast<PartData *>(reference)->setQ(q);
1995}
1996
1997
1998template <class T, unsigned Dim>
2000 const_cast<PartData *>(reference)->setM(m);
2001}
2002
2003
2004template <class T, unsigned Dim>
2006 return momentsComputer_m.getStdKineticEnergy();
2007}
2008
2009
2010template <class T, unsigned Dim>
2012 return reference->getBeta();
2013}
2014
2015
2016template <class T, unsigned Dim>
2018 return reference->getGamma();
2019}
2020
2021
2022template <class T, unsigned Dim>
2024 return 0;
2025}
2026
2027
2028template <class T, unsigned Dim>
2030 return 0;
2031}
2032
2033
2034template <class T, unsigned Dim>
2036 // do nothing here
2037};
2038
2039
2040template <class T, unsigned Dim>
2042 return reference;
2043}
2044
2045
2046template <class T, unsigned Dim>
2048 return dist_m->getEmissionDeltaT();
2049}
2050
2051
2052template <class T, unsigned Dim>
2054 binemitted_m[binNumber]++;
2055}
2056
2057
2058template <class T, unsigned Dim>
2060 momentsComputer_m.computeMeanKineticEnergy(*this);
2061}
2062
2063template <class T, unsigned Dim>
2065
2066 if (getTotalNum() != 0) { // to suppress Nans
2067 Inform::FmtFlags_t ff = os.flags();
2068
2069 double pathLength = get_sPos();
2070
2071 os << std::scientific;
2072 os << level1 << "\n";
2073 os << "* ************** B U N C H ********************************************************* \n";
2074 os << "* NP = " << getTotalNum() << "\n";
2075 os << "* Qtot = " << std::setw(17) << Util::getChargeString(std::abs(sum(Q))) << " "
2076 << "Qi = " << std::setw(17) << Util::getChargeString(std::abs(qi_m)) << "\n";
2077 os << "* Ekin = " << std::setw(17) << Util::getEnergyString(get_meanKineticEnergy()) << " "
2078 << "dEkin = " << std::setw(17) << Util::getEnergyString(getdE()) << "\n";
2079 os << "* rmax = " << Util::getLengthString(rmax_m, 5) << "\n";
2080 os << "* rmin = " << Util::getLengthString(rmin_m, 5) << "\n";
2081 if (getTotalNum() >= 2) { // to suppress Nans
2082 os << "* rms beam size = " << Util::getLengthString(get_rrms(), 5) << "\n";
2083 os << "* rms momenta = " << std::setw(12) << std::setprecision(5) << get_prms() << " [beta gamma]\n";
2084 os << "* mean position = " << Util::getLengthString(get_rmean(), 5) << "\n";
2085 os << "* mean momenta = " << std::setw(12) << std::setprecision(5) << get_pmean() << " [beta gamma]\n";
2086 os << "* rms emittance = " << std::setw(12) << std::setprecision(5) << get_emit() << " (not normalized)\n";
2087 os << "* rms correlation = " << std::setw(12) << std::setprecision(5) << get_rprms() << "\n";
2088 }
2089 os << "* hr = " << Util::getLengthString(get_hr(), 5) << "\n";
2090 os << "* dh = " << std::setw(13) << std::setprecision(5) << dh_m * 100 << " [%]\n";
2091 os << "* t = " << std::setw(17) << Util::getTimeString(getT()) << " "
2092 << "dT = " << std::setw(17) << Util::getTimeString(getdT()) << "\n";
2093 os << "* spos = " << std::setw(17) << Util::getLengthString(pathLength) << "\n";
2094 os << "* ********************************************************************************** " << endl;
2095 os.flags(ff);
2096 }
2097 return os;
2098}
2099
2100// angle range [0~2PI) degree
2101template <class T, unsigned Dim>
2102double PartBunchBase<T, Dim>::calculateAngle(double x, double y) {
2103 double thetaXY = std::atan2(y, x);
2104
2105 return thetaXY >= 0 ? thetaXY : thetaXY + Physics::two_pi;
2106}
2107
2108
2109template <class T, unsigned Dim>
2111 return p.print(os);
2112}
2113
2114
2115/*
2116 * Virtual member functions
2117 */
2118
2119template <class T, unsigned Dim>
2121 throw OpalException("PartBunchBase<T, Dim>::runTests() ", "No test supported.");
2122}
2123
2124
2125template <class T, unsigned Dim>
2127
2128}
2129
2130template <class T, unsigned Dim>
2131void PartBunchBase<T, Dim>::swap(unsigned int i, unsigned int j) {
2132 if (i >= getLocalNum() || j >= getLocalNum() || i == j) return;
2133
2134 std::swap(R[i], R[j]);
2135 std::swap(P[i], P[j]);
2136 std::swap(Q[i], Q[j]);
2137 std::swap(M[i], M[j]);
2138 std::swap(Phi[i], Phi[j]);
2139 std::swap(Ef[i], Ef[j]);
2140 std::swap(Eftmp[i], Eftmp[j]);
2141 std::swap(Bf[i], Bf[j]);
2142 std::swap(Bin[i], Bin[j]);
2143 std::swap(dt[i], dt[j]);
2144 std::swap(PType[i], PType[j]);
2145 std::swap(POrigin[i], POrigin[j]);
2146 std::swap(TriID[i], TriID[j]);
2147 std::swap(cavityGapCrossed[i], cavityGapCrossed[j]);
2148 std::swap(bunchNum[i], bunchNum[j]);
2149}
2150
2151
2152template <class T, unsigned Dim>
2154 throw OpalException("PartBunchBase<T, Dim>::setBCAllPeriodic() ", "Not supported BC.");
2155}
2156
2157
2158template <class T, unsigned Dim>
2160 throw OpalException("PartBunchBase<T, Dim>::setBCAllOpen() ", "Not supported BC.");
2161}
2162
2163
2164template <class T, unsigned Dim>
2166 throw OpalException("PartBunchBase<T, Dim>::setBCForDCBeam() ", "Not supported BC.");
2167}
2168
2169
2170template <class T, unsigned Dim>
2171void PartBunchBase<T, Dim>::updateFields(const Vector_t& /*hr*/, const Vector_t& /*origin*/) {
2172}
2173
2174
2175template <class T, unsigned Dim>
2177
2178 pb->addAttribute(P);
2179 pb->addAttribute(Q);
2180 pb->addAttribute(M);
2181 pb->addAttribute(Phi);
2182 pb->addAttribute(Ef);
2183 pb->addAttribute(Eftmp);
2184 pb->addAttribute(Bf);
2185 pb->addAttribute(Bin);
2186 pb->addAttribute(dt);
2187 pb->addAttribute(PType);
2188 pb->addAttribute(POrigin);
2189 pb->addAttribute(TriID);
2190 pb->addAttribute(cavityGapCrossed);
2191 pb->addAttribute(bunchNum);
2192
2193 boundpTimer_m = IpplTimings::getTimer("Boundingbox");
2194 boundpBoundsTimer_m = IpplTimings::getTimer("Boundingbox-bounds");
2195 boundpUpdateTimer_m = IpplTimings::getTimer("Boundingbox-update");
2196 statParamTimer_m = IpplTimings::getTimer("Compute Statistics");
2197 selfFieldTimer_m = IpplTimings::getTimer("SelfField total");
2198
2199 histoTimer_m = IpplTimings::getTimer("Histogram");
2200
2201 distrCreate_m = IpplTimings::getTimer("Create Distr");
2202 distrReload_m = IpplTimings::getTimer("Load Distr");
2203
2204 globalPartPerNode_m = std::unique_ptr<size_t[]>(new size_t[Ippl::getNodes()]);
2205
2206 pmsg_m.release();
2207}
2208
2209
2210template <class T, unsigned Dim>
2212 return pbase_m->getTotalNum();
2213}
2214
2215template <class T, unsigned Dim>
2217 return pbase_m->getLocalNum();
2218}
2219
2220
2221template <class T, unsigned Dim>
2223 return pbase_m->getDestroyNum();
2224}
2225
2226template <class T, unsigned Dim>
2228 return pbase_m->getGhostNum();
2229}
2230
2231template <class T, unsigned Dim>
2233 pbase_m->setTotalNum(n);
2234}
2235
2236template <class T, unsigned Dim>
2238 pbase_m->setLocalNum(n);
2239}
2240
2241template <class T, unsigned Dim>
2243 return pbase_m->getLayout();
2244}
2245
2246template <class T, unsigned Dim>
2248 return pbase_m->getLayout();
2249}
2250
2251template <class T, unsigned Dim>
2253 return pbase_m->getUpdateFlag(f);
2254}
2255
2256template <class T, unsigned Dim>
2258 pbase_m->setUpdateFlag(f, val);
2259}
2260
2261template <class T, unsigned Dim>
2263 return pbase_m->singleInitNode();
2264}
2265
2266template <class T, unsigned Dim>
2268 pbase_m->resetID();
2269}
2270
2271template <class T, unsigned Dim>
2273 try {
2274 pbase_m->update();
2275 } catch (const IpplException& ex) {
2276 throw OpalException(ex.where(), ex.what());
2277 }
2278 checkMeshFitOutside();
2279}
2280
2281template <class T, unsigned Dim>
2283 try {
2284 pbase_m->update(canSwap);
2285 } catch (const IpplException& ex) {
2286 throw OpalException(ex.where(), ex.what());
2287 }
2288 checkMeshFitOutside();
2289}
2290
2291template <class T, unsigned Dim>
2293 pbase_m->createWithID(id);
2294}
2295
2296template <class T, unsigned Dim>
2298 pbase_m->create(M);
2299}
2300
2301template <class T, unsigned Dim>
2303 pbase_m->globalCreate(np);
2304}
2305
2306template <class T, unsigned Dim>
2307void PartBunchBase<T, Dim>::destroy(size_t M, size_t I, bool doNow) {
2308 pbase_m->destroy(M, I, doNow);
2309}
2310
2311template <class T, unsigned Dim>
2312void PartBunchBase<T, Dim>::performDestroy(bool updateLocalNum) {
2313 pbase_m->performDestroy(updateLocalNum);
2314}
2315
2316template <class T, unsigned Dim>
2317void PartBunchBase<T, Dim>::ghostDestroy(size_t M, size_t I) {
2318 pbase_m->ghostDestroy(M, I);
2319}
2320
2321template <class T, unsigned Dim>
2323 periodLength_m = Physics::c / f;
2324}
2325
2326template <class T, unsigned Dim>
2328 //const double N = static_cast<double>(this->getTotalNum());
2329
2330 Vektor<double, 2*Dim> rpmean;
2331 for (unsigned int i = 0; i < Dim; i++) {
2332 rpmean(2*i)= get_rmean()(i);
2333 rpmean((2*i)+1)= get_pmean()(i);
2334 }
2335
2337 for (unsigned int i = 0; i < 2 * Dim; i++) {
2338 for (unsigned int j = 0; j <= i; j++) {
2339 sigmaMatrix[i][j] = momentsComputer_m.getMoments6x6()[i][j] - rpmean(i) * rpmean(j);
2340 sigmaMatrix[j][i] = sigmaMatrix[i][j];
2341 }
2342 }
2343 return sigmaMatrix;
2344}
2345
2346#endif
FieldSolverType
Definition FieldSolver.h:38
const unsigned Dim
DistributionType
ParticleOrigin
double dot(const Vector3D &lhs, const Vector3D &rhs)
Vector dot product.
Definition Vector3D.cpp:118
Inform & operator<<(Inform &os, PartBunchBase< T, Dim > &p)
Inform * gmsg
Definition Main.cpp:70
Quaternion Quaternion_t
Definition Quaternion.h:42
T::PETE_Expr_t::PETE_Return_t max(const PETE_Expr< T > &expr, NDIndex< D > &loc)
T::PETE_Expr_t::PETE_Return_t min(const PETE_Expr< T > &expr, NDIndex< D > &loc)
T::PETE_Expr_t::PETE_Return_t sum(const PETE_Expr< T > &expr)
Definition PETE.h:1111
PETE_TTTree< OpWhere, typename Cond_t::PETE_Expr_t, typename True_t::PETE_Expr_t, PETE_Scalar< Vektor< T, Dim > > > where(const PETE_Expr< Cond_t > &c, const PETE_Expr< True_t > &t, const Vektor< T, Dim > &f)
void bounds(const PETE_Expr< T1 > &expr, Vektor< T2, D > &minval, Vektor< T2, D > &maxval)
void allreduce(const T *input, T *output, int count, Op op)
bool reduce(Communicate &, InputIterator, InputIterator, OutputIterator, const ReduceOp &, bool *IncludeVal=0)
void gather(const T *input, T *output, int count, int root=0)
PETE_TBTree< OpNE, Index::PETE_Expr_t, PETE_Scalar< double > > ne(const Index &idx, double x)
PETE_TBTree< OpEQ, Index::PETE_Expr_t, PETE_Scalar< double > > eq(const Index &idx, double x)
#define ERRORMSG(msg)
Definition IpplInfo.h:350
#define INFOMSG(msg)
Definition IpplInfo.h:348
#define WARNMSG(msg)
Definition IpplInfo.h:349
Inform & level2(Inform &inf)
Definition Inform.cpp:46
Inform & endl(Inform &inf)
Definition Inform.cpp:42
Inform & level1(Inform &inf)
Definition Inform.cpp:45
#define INFORM_ALL_NODES
Definition Inform.h:39
#define PAssert_LT(a, b)
Definition PAssert.h:106
CoreSelection selectCore(const Vector_t *R, const double *Q, const int *bin, std::size_t localNum, double nSigma, double clip, const Reducer &reducer)
Definition CoreFitSC.cpp:89
constexpr double warnFarFraction
The solve warns when the far charge fraction exceeds this.
Definition CoreFitSC.h:77
ModeState decideMode(const ModeState &previous, std::size_t numCore, std::size_t numLive, double farChargeFraction, double maxFarFraction, unsigned int minDwell)
void getMeshBox(const Vector_t *R, const int *bin, std::size_t localNum, const CoreSelection &selection, double nSigma, const Reducer &reducer, Vector_t &boxMin, Vector_t &boxMax)
constexpr double two_pi
The value of.
Definition Physics.h:33
constexpr double e
The value of.
Definition Physics.h:39
constexpr double c
The velocity of light in m/s.
Definition Physics.h:45
constexpr double rad2deg
Definition Units.h:146
double remotePartDel
Definition Options.cpp:59
int repartFreq
The frequency to do particles repartition for better load balance between nodes.
Definition Options.cpp:47
std::string getChargeString(double charge, unsigned int precision=3)
Definition Util.h:173
std::string getEnergyString(double energyInMeV, unsigned int precision=3)
Definition Util.h:150
std::string getTimeString(double time, unsigned int precision=3)
Definition Util.h:77
std::string getLengthString(double spos, unsigned int precision=3)
Definition Util.h:100
void update(PyOpalObjectNS::PyOpalObject< C > pyelement)
ParticleLayout< T, Dim > & getLayout()
double get_Dx() const
double getP() const
void setEnergyBins(int numberOfEnergyBins)
double get_meanKineticEnergy() const
void setDistribution(Distribution *d, std::vector< Distribution * > addedDistributions, size_t &np)
virtual void resetInterpolationCache(bool clearCache=false)
void getMeshFitFullBounds(Vector_t &rmin, Vector_t &rmax) const
MESHFIT=CORE: the bounds of all particles of the same fit.
void setPType(const std::string &type)
const PartData * getReference() const
ParticleOrigin getPOrigin() const
void setMass(double mass)
void setCharge(double q)
int getSteptoLastInj() const
Vector_t get_99Percentile() const
void boundp_destroyCycl()
void get_bounds(Vector_t &rmin, Vector_t &rmax) const
bool resetPartBinID2(const double eta)
reset Bin[] for each particle according to the method given in paper PAST-AB(064402) by G....
void setNumBunch(short n)
const MeshFitParameters & getMeshFit() const
double getMassPerParticle() const
double getQ() const
Access to reference data.
double getCouplingConstant() const
Vector_t get_normalizedEps_99Percentile() const
double getChargePerParticle() const
get the macro particle charge
virtual void set_meshEnlargement(double dh)
void resetM(double m)
void getSolverMeshBounds(Vector_t &rmin, Vector_t &rmax)
virtual double getBeta(int i)
virtual double getPx0(int i)
size_t getLocalNum() const
FMatrix< double, 2 *Dim, 2 *Dim > getSigmaMatrix() const
void setMeshFit(const MeshFitParameters &meshFit)
FIELDSOLVER, MESHFIT: the particles the space-charge mesh is fitted to.
void set_sPos(double s)
void setLocalTrackStep(long long n)
step in a TRACK command
void setLocalBinCount(size_t num, int bin)
double get_debyeLength() const
bool getUpdateFlag(UpdateFlags_t f) const
void setParticle(FVector< double, 6 > z, int ii)
size_t emitParticles(double eZ)
Emit particles in the given bin i.e. copy the particles from the bin structure into the particle cont...
void maximumAmplitudes(const FMatrix< double, 6, 6 > &D, double &axmax, double &aymax)
Return maximum amplitudes.
double get_plasmaParameter() const
void setMassZeroPart(double mass)
size_t getTotalNum() const
double get_DDy() const
virtual void updateFields(const Vector_t &hr, const Vector_t &origin)
Vector_t get_95Percentile() const
virtual void setZ(int i, double zcoo)
bool isMeshFitToCore() const
double calcMeanPhi()
calculate average angle of longitudinal direction of bins
Quaternion_t getGlobalToLocalQuaternion()
size_t boundp_destroyT()
void setBeamFrequency(double v)
Vector_t get_normalizedEps_68Percentile() const
double get_gamma() const
void switchToUnitlessPositions(bool use_dt_per_particle=false)
size_t calcNumPartsOutside(Vector_t x)
returns the number of particles outside of a box defined by x
double getTEmission()
double getdT() const
Inform & print(Inform &os)
FieldSolverType getFieldSolverType() const
Return the fieldsolver type if we have a fieldsolver.
double getEmissionDeltaT()
void setLocalNumPerBunch(size_t numpart, short n)
size_t getLocalNumPerBunch(short n) const
void setGlobalToLocalQuaternion(Quaternion_t globalToLocalQuaternion)
Vector_t get_rrms() const
bool getIfBeamEmitting()
void setMeshFitMode(const CoreFitSC::ModeState &mode)
MESHFIT=CORE: restores the mode, from the step attributes of an H5 restart.
bool weHaveBins() const
double get_rmsDensity() const
virtual double getPy(int i)
double getBinGamma(int bin)
Get gamma of one bin.
double getInitialBeta() const
int getLastEmittedEnergyBin()
void getLocalBounds(Vector_t &rmin, Vector_t &rmax) const
void setSteptoLastInj(int n)
virtual double getX0(int i)
double getInitialGamma() const
virtual void setBCAllPeriodic()
virtual void runTests()
void setChargeZeroPart(double q)
virtual double getY0(int i)
ParticleType getPType() const
Vector_t get_origin() const
Vector_t get_prms() const
double getdE() const
void createWithID(unsigned id)
const CoreFitSC::CoreSelection & getMeshFitCore() const
PartBunchBase(AbstractParticle< T, Dim > *pb, const PartData *ref)
double getCharge() const
get the total charge per simulation particle
virtual double getPy0(int i)
double get_temperature() const
size_t getTotalNumPerBunch(short n) const
virtual double getPx(int i)
Vector_t get_pmean_Distribution() const
size_t getNumberOfEmissionSteps()
void calcLineDensity(unsigned int nBins, std::vector< double > &lineDensity, std::pair< double, double > &meshInfo)
calculates the 1d line density (not normalized) and append it to a file.
Vector_t get_68Percentile() const
void setup(AbstractParticle< T, Dim > *pb)
virtual void setBCAllOpen()
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 warnMeshFitOnce(MeshFitWarning warning, const std::string &message)
void setGlobalMeanR(Vector_t globalMeanR)
void setCouplingConstant(double c)
short getNumBunch() const
double get_DDx() const
virtual void do_binaryRepart()
Vector_t get_norm_emit() const
void calcGammas()
Compute the gammas of all bins.
int getStepsPerTurn() const
void setdT(double dt)
double get_Dy() const
Vector_t get_rprms() const
void setPOrigin(ParticleOrigin)
bool isMeshFitRepartitionDue() const
Vector_t get_maxExtent() const
Vector_t get_normalizedEps_95Percentile() const
void gatherLoadBalanceStatistics()
void countTotalNumPerBunch()
DistributionType getDistType() const
void get_PBounds(Vector_t &min, Vector_t &max) const
virtual void setBinCharge(int bin, double q)
Set the charge of one bin to the value of q and all other to zero.
bool isGridFixed() const
Vector_t get_halo() const
void performDestroy(bool updateLocalNum=false)
Vector_t getGlobalMeanR()
void ghostDestroy(size_t M, size_t I)
int getNumberOfEnergyBins()
void setGlobalTrackStep(long long n)
step in multiple TRACK commands
std::pair< Vector_t, double > getBoundingSphere()
void setMeshFitSolveStep(bool solveStep)
Vector_t get_centroid() const
Vector_t get_99_99Percentile() const
void push_back(OpalParticle const &p)
virtual double getX(int i)
virtual double getPz(int i)
void setLocalNum(size_t n)
Vector_t get_pmean() const
void setTotalNumPerBunch(size_t numpart, short n)
virtual void setBCForDCBeam()
bool hasBinning() const
void destroy(size_t M, size_t I, bool doNow=false)
void globalCreate(size_t np)
Vector_t get_normalizedEps_99_99Percentile() const
double getMomentumTolerance() const
const CoreFitSC::ModeState & getMeshFitMode() const
OpalParticle getParticle(int ii)
virtual void swap(unsigned int i, unsigned int j)
virtual void actT()
void setPBins(PartBins *pbin)
virtual void boundp()
void create(size_t M)
size_t getDestroyNum() const
virtual double getGamma(int i)
void resetQ(double q)
virtual void setSolver(FieldSolver *fs)
long long getGlobalTrackStep() const
void setT(double t)
size_t getGhostNum() const
void setTEmission(double t)
size_t getLoadBalance(int p) const
std::pair< Vector_t, double > getLocalBoundingSphere()
virtual Vector_t get_hr() const
Vector_t get_emit() const
double calculateAngle(double x, double y)
angle range [0~2PI) degree
void calcDebyeLength()
Compute the (global) Debye length for the beam.
double get_sPos() const
void iterateEmittedBin(int binNumber)
MeshFitWarning
MESHFIT=CORE: the warnings of the solve, each given at most once per turn.
bool singleInitNode() const
double getM() const
void setUpdateFlag(UpdateFlags_t f, bool val)
virtual double getY(int i)
double getT() const
double getE() const
void switchOffUnitlessPositions(bool use_dt_per_particle=false)
void setStepsPerTurn(int n)
const MeshFitStatistics & getMeshFitStatistics() const
virtual double getZ(int i)
Vector_t get_rmean() const
static OpalData * getInstance()
Definition OpalData.cpp:196
All IPPL nodes, through allreduce().
Definition CoreFitSC.h:110
Result of selectCore(), the same on every rank.
Definition CoreFitSC.h:117
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
Vector_t boundsMin
minimum over the core particles [m]
Definition CoreFitSC.h:120
std::size_t numFar
the other live particles
Definition CoreFitSC.h:125
std::size_t numCore
live particles within nSigma * sigma in every axis
Definition CoreFitSC.h:124
double getPy() const
Get vertical momentum (no dimension).
const Vector_t & getR() const
Get position in m.
const Vector_t & getP() const
Get momentum.
double getPz() const
Get relative momentum error (no dimension).
double getY() const
Get vertical displacement in m.
double getZ() const
Get longitudinal displacement c*t in m.
double getPx() const
Get horizontal momentum (no dimension).
double getX() const
Get horizontal position in m.
MESHFIT=CORE: statistics of the solves of this TRACK/RUN, for the stat file and the log.
size_t turnSolves
solves in this turn
double getBeta() const
The relativistic beta per particle.
Definition PartData.h:134
An abstract sequence of beam line components.
Definition Beamline.h:34
A templated representation for matrices.
Definition FMatrix.h:39
A templated representation for vectors.
Definition FVector.h:38
static ParticleType getParticleType(std::string_view str) noexcept
void createOpalCycl(PartBunchBase< double, 3 > *beam, size_t numberOfParticles, double current, const Beamline &bl)
void createOpalT(PartBunchBase< double, 3 > *beam, std::vector< Distribution * > addedDistributions, size_t &numberOfParticles)
Parameters of the mesh fit, passed to the bunch (PartBunchBase::setMeshFit())
Definition FieldSolver.h:66
MeshFitType type
Definition FieldSolver.h:67
The base class for all OPAL exceptions.
virtual void addAttribute(ParticleAttribBase &pa)=0
void setOutsideToNearest(bool outsideToNearest)
void setCacheDimension(int d, T length)
bool getUpdateFlag(UpdateFlags f) const
std::ios_base::fmtflags FmtFlags_t
Definition Inform.h:99
FmtFlags_t flags() const
Definition Inform.h:106
virtual const char * what() const
virtual const std::string & where() const
static int getNodes()
Definition IpplInfo.cpp:689
static TimerRef getTimer(const char *nm)
static void stopTimer(TimerRef t)
static void startTimer(TimerRef t)
Definition Vec.h:22
Vektor< double, 3 > Vector_t
Definition Vektor.h:6