OPAL (Object Oriented Parallel Accelerator Library) 2024.2
OPAL
CoreFitSC.cpp
Go to the documentation of this file.
1//
2// Namespace CoreFitSC
3// Core selection and far-field model for a space-charge mesh fitted to the bunch core
4// (OPAL-cycl, FFT solver).
5//
6// Created by: Daniel Winklehner, MIT (2026)
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//
19
20#include "Message/GlobalComm.h"
21
22#include <algorithm>
23#include <cmath>
24#include <functional>
25#include <limits>
26
27namespace {
30 void accumulateClipped(const Vector_t* R, const double* Q, const int* bin,
31 std::size_t localNum, const Vector_t& centre,
32 const Vector_t& halfWidth, double sums[8]) {
33 std::fill(sums, sums + 8, 0.0);
34 for (std::size_t i = 0; i < localNum; ++i) {
35 if (bin[i] < 0) {
36 continue;
37 }
38 const Vector_t dr = R[i] - centre;
39 if (std::abs(dr[0]) > halfWidth[0] ||
40 std::abs(dr[1]) > halfWidth[1] ||
41 std::abs(dr[2]) > halfWidth[2]) {
42 continue;
43 }
44 sums[0] += 1.0;
45 sums[1] += Q[i];
46 for (unsigned int d = 0; d < 3; ++d) {
47 sums[2 + d] += dr[d];
48 sums[5 + d] += dr[d] * dr[d];
49 }
50 }
51 }
52
54 void meanAndSigma(const double sums[8], const Vector_t& centre,
55 Vector_t& mean, Vector_t& sigma) {
56 for (unsigned int d = 0; d < 3; ++d) {
57 const double shift = sums[2 + d] / sums[0];
58 mean[d] = centre[d] + shift;
59 sigma[d] = std::sqrt(std::max(0.0, sums[5 + d] / sums[0] - shift * shift));
60 }
61 }
62
64 Vector_t getHalfWidth(double k, const Vector_t& sigma) {
65 Vector_t width;
66 for (unsigned int d = 0; d < 3; ++d) {
67 width[d] = std::max(k * sigma[d], CoreFitSC::flatWidth);
68 }
69 return width;
70 }
71}
72
73
74void CoreFitSC::IpplReducer::sum(double* values, unsigned int count) const {
75 allreduce(values, count, std::plus<double>());
76}
77
78
79void CoreFitSC::IpplReducer::min(double* values, unsigned int count) const {
80 allreduce(values, count, std::less<double>());
81}
82
83
85 return chargeLive != 0.0 ? chargeFar / chargeLive : 0.0;
86}
87
88
90 const int* bin, std::size_t localNum,
91 double nSigma, double clip,
92 const Reducer& reducer) {
93 CoreSelection selection;
94 double sums[8];
95
96 // Pass 0: the plain mean and rms of the live particles, in one sum about the origin.
97 // The local space-charge frame is centred on the bunch. In a frame that is not, the
98 // cancellation only blurs the first clip width, as long as the rms exceeds about 1e-8 of
99 // the offset: every later pass is summed about the mean of the pass before. In an axis in
100 // which the bunch is flat away from the origin, this rms is round-off: the first clip
101 // still keeps the plane, and the stop test below does not depend on it.
102 const Vector_t unlimited(std::numeric_limits<double>::infinity());
103 accumulateClipped(R, Q, bin, localNum, Vector_t(0.0), unlimited, sums);
104 reducer.sum(sums, 8);
105 selection.numLive = static_cast<std::size_t>(sums[0]);
106 selection.chargeLive = sums[1];
107
108 Vector_t mean(0.0), sigma(0.0);
109 if (sums[0] > 0.0) {
110 meanAndSigma(sums, Vector_t(0.0), mean, sigma);
111
112 // Passes 1 to maxClipPasses: the particles within clip * sigma of the previous
113 // pass, summed about its mean.
114 double numPrevious = sums[0];
115 for (unsigned int pass = 1; pass <= maxClipPasses; ++pass) {
116 accumulateClipped(R, Q, bin, localNum, mean, getHalfWidth(clip, sigma), sums);
117 reducer.sum(sums, 8);
118 if (sums[0] == 0.0) {
119 break;
120 }
121 Vector_t newMean, newSigma;
122 meanAndSigma(sums, mean, newMean, newSigma);
123
124 // an axis whose new rms is at most flatWidth has settled, whatever its rms
125 // before, which after pass 0 can be round-off above flatWidth
126 bool sigmaSettled = true;
127 for (unsigned int d = 0; d < 3; ++d) {
128 if (newSigma[d] > flatWidth &&
129 !(std::abs(newSigma[d] - sigma[d]) < clipTolerance * newSigma[d])) {
130 sigmaSettled = false;
131 }
132 }
133 mean = newMean;
134 sigma = newSigma;
135 selection.passes = pass;
136 if (sums[0] == numPrevious || sigmaSettled) {
137 selection.converged = true;
138 break;
139 }
140 numPrevious = sums[0];
141 }
142 }
143 selection.mean = mean;
144 selection.sigma = sigma;
145
146 // Final pass: the core within nSigma * sigma in every axis, its exact bounds, the far
147 // particles and the halo proper.
148 const Vector_t coreWidth = getHalfWidth(nSigma, sigma);
149 const Vector_t haloWidth = getHalfWidth(haloSigma, sigma);
150 double extrema[7]; // min x, y, z; -max x, y, z; -(largest far distance)
151 std::fill(extrema, extrema + 7, std::numeric_limits<double>::max());
152 double farSums[3] = {0.0, 0.0, 0.0}; // far count, far charge, halo count
153 for (std::size_t i = 0; i < localNum; ++i) {
154 if (bin[i] < 0) {
155 continue;
156 }
157 const Vector_t dr = R[i] - mean;
158 bool isCore = true;
159 bool isHalo = false;
160 for (unsigned int d = 0; d < 3; ++d) {
161 const double dist = std::abs(dr[d]);
162 if (dist > coreWidth[d]) {
163 isCore = false;
164 }
165 if (dist > haloWidth[d]) {
166 isHalo = true;
167 }
168 }
169 if (isHalo) {
170 farSums[2] += 1.0;
171 }
172 if (isCore) {
173 for (unsigned int d = 0; d < 3; ++d) {
174 extrema[d] = std::min(extrema[d], R[i][d]);
175 extrema[3 + d] = std::min(extrema[3 + d], -R[i][d]);
176 }
177 continue;
178 }
179 farSums[0] += 1.0;
180 farSums[1] += Q[i];
181 double distance = 0.0;
182 for (unsigned int d = 0; d < 3; ++d) {
183 if (sigma[d] > flatWidth) {
184 distance = std::max(distance, std::abs(dr[d]) / sigma[d]);
185 }
186 }
187 extrema[6] = std::min(extrema[6], -distance);
188 }
189 reducer.sum(farSums, 3);
190 reducer.min(extrema, 7);
191
192 selection.numFar = static_cast<std::size_t>(farSums[0]);
193 selection.numCore = selection.numLive - selection.numFar;
194 selection.numHalo = static_cast<std::size_t>(farSums[2]);
195 selection.chargeFar = farSums[1];
196 for (unsigned int d = 0; d < 3; ++d) {
197 selection.boundsMin[d] = extrema[d];
198 selection.boundsMax[d] = -extrema[3 + d];
199 }
200 selection.farMaxDistance = selection.numFar > 0 ? -extrema[6] : 0.0;
201
202 return selection;
203}
204
205
206void CoreFitSC::getMeshBox(const Vector_t* R, const int* bin, std::size_t localNum,
207 const CoreSelection& selection, double nSigma,
208 const Reducer& reducer, Vector_t& boxMin, Vector_t& boxMax) {
209 // the core test of the final pass of selectCore(), here for the particles flagged lost
210 const Vector_t coreWidth = getHalfWidth(nSigma, selection.sigma);
211 double extrema[6]; // min x, y, z; -max x, y, z
212 for (unsigned int d = 0; d < 3; ++d) {
213 extrema[d] = selection.boundsMin[d];
214 extrema[3 + d] = -selection.boundsMax[d];
215 }
216 for (std::size_t i = 0; i < localNum; ++i) {
217 if (bin[i] >= 0) {
218 continue;
219 }
220 const Vector_t dr = R[i] - selection.mean;
221 if (std::abs(dr[0]) > coreWidth[0] ||
222 std::abs(dr[1]) > coreWidth[1] ||
223 std::abs(dr[2]) > coreWidth[2]) {
224 continue;
225 }
226 for (unsigned int d = 0; d < 3; ++d) {
227 extrema[d] = std::min(extrema[d], R[i][d]);
228 extrema[3 + d] = std::min(extrema[3 + d], -R[i][d]);
229 }
230 }
231 reducer.min(extrema, 6);
232
233 for (unsigned int d = 0; d < 3; ++d) {
234 boxMin[d] = extrema[d];
235 boxMax[d] = -extrema[3 + d];
236 }
237}
238
239
241 const Vector_t& boundsMin,
242 const Vector_t& boundsMax,
243 const Vector_t& meshMin,
244 const Vector_t& meshMax) {
245 if (isInside(r, boundsMin, boundsMax)) {
246 return bin >= 0 ? ParticleClass::CORE : ParticleClass::INSIDE;
247 }
248 return isInside(r, meshMin, meshMax) ? ParticleClass::MESH : ParticleClass::FAR;
249}
250
251
252CoreFitSC::MomentSums::MomentSums(const Vector_t& centre, double gamma):
253 centre_m(centre),
254 gamma_m(gamma)
255{
256 sums_m.fill(0.0);
257}
258
259
260void CoreFitSC::MomentSums::add(double q, const Vector_t& r) {
261 const Vector_t s = toRestFrame(r, centre_m, gamma_m);
262 sums_m[0] += q;
263 for (unsigned int i = 0; i < 3; ++i) {
264 sums_m[1 + i] += q * s[i];
265 }
266 // q s_i s_j, i <= j: xx, xy, xz, yy, yz, zz
267 unsigned int l = 4;
268 for (unsigned int i = 0; i < 3; ++i) {
269 for (unsigned int j = i; j < 3; ++j, ++l) {
270 sums_m[l] += q * s[i] * s[j];
271 }
272 }
273}
274
275
277 std::array<double, 10> sums = sums_m;
278 reducer.sum(sums.data(), 10);
279
280 CoreMoments moments;
281 moments.charge = sums[0];
282 moments.quadrupole.fill(Vector_t(0.0));
283 if (sums[0] == 0.0) {
284 return moments;
285 }
286 for (unsigned int i = 0; i < 3; ++i) {
287 moments.centroid[i] = sums[1 + i] / sums[0];
288 }
289 // second moments about the centroid (xx, xy, xz, yy, yz, zz), then the traceless
290 // quadrupole; each off-diagonal value is computed once, so the tensor is symmetric
291 double M[6];
292 for (unsigned int i = 0, l = 0; i < 3; ++i) {
293 for (unsigned int j = i; j < 3; ++j, ++l) {
294 M[l] = sums[4 + l] - sums[0] * moments.centroid[i] * moments.centroid[j];
295 }
296 }
297 const double trace = M[0] + M[3] + M[5];
298 for (unsigned int i = 0, l = 0; i < 3; ++i) {
299 for (unsigned int j = i; j < 3; ++j, ++l) {
300 const double Qij = 3.0 * M[l] - (i == j ? trace : 0.0);
301 moments.quadrupole[i][j] = Qij;
302 moments.quadrupole[j][i] = Qij;
303 }
304 }
305 return moments;
306}
307
308
310 const std::vector<Vector_t>& position,
311 std::size_t begin, std::size_t end, bool withQuadrupole,
312 std::vector<Vector_t>& field,
313 std::vector<double>& indicator) {
314 const std::array<Vector_t, 3>& Q = moments.quadrupole;
315 for (std::size_t i = begin; i < end; ++i) {
316 const Vector_t d = position[i] - moments.centroid;
317 const double r2 = dot(d, d);
318 const double r3 = r2 * std::sqrt(r2);
319 const Vector_t Qd({dot(Q[0], d), dot(Q[1], d), dot(Q[2], d)});
320 const double dQd = dot(d, Qd);
321
322 const Vector_t monopole = (moments.charge / r3) * d;
323 const Vector_t quadrupole = (2.5 * dQd / (r2 * r2 * r3)) * d - Qd / (r2 * r3);
324
325 const double monopoleNorm = euclidean_norm(monopole);
326 indicator[i] = monopoleNorm > 0.0 ? euclidean_norm(quadrupole) / monopoleNorm : 0.0;
327 field[i] = withQuadrupole ? monopole + quadrupole : monopole;
328 }
329}
330
331
332void CoreFitSC::addDirectField(const std::vector<Vector_t>& target,
333 std::size_t begin, std::size_t end,
334 const std::vector<Vector_t>& source,
335 const std::vector<double>& charge,
336 double eps, std::vector<Vector_t>& field) {
337 const double eps2 = eps * eps;
338 const std::size_t numSources = source.size();
339 for (std::size_t i = begin; i < end; ++i) {
340 const Vector_t& t = target[i];
341 Vector_t E(0.0);
342 for (std::size_t j = 0; j < numSources; ++j) {
343 const Vector_t d = t - source[j];
344 const double d2 = dot(d, d);
345 if (d2 == 0.0) {
346 continue;
347 }
348 const double r2 = d2 + eps2;
349 E += (charge[j] / (r2 * std::sqrt(r2))) * d;
350 }
351 field[i] += E;
352 }
353}
354
355
356std::pair<std::size_t, std::size_t> CoreFitSC::getTableRange(std::size_t n, int rank,
357 int numRanks) {
358 const std::size_t p = rank;
359 const std::size_t numP = numRanks;
360 return std::make_pair(p * n / numP, (p + 1) * n / numP);
361}
362
363
364std::size_t CoreFitSC::getSampleStride(std::size_t numTargets, std::size_t numSources,
365 double maxPairs) {
366 const double pairs = static_cast<double>(numTargets) * static_cast<double>(numSources);
367 if (pairs <= maxPairs) {
368 return 1;
369 }
370 return static_cast<std::size_t>(std::ceil(pairs / maxPairs));
371}
372
373
374bool CoreFitSC::isInCoreShell(const Vector_t& r, const Vector_t& lower, const Vector_t& upper) {
375 for (unsigned int d = 0; d < 3; ++d) {
376 const double centre = 0.5 * (lower[d] + upper[d]);
377 const double halfWidth = 0.5 * (upper[d] - lower[d]);
378 if (std::abs(r[d] - centre) > (1.0 - coreShellFraction) * halfWidth) {
379 return true;
380 }
381 }
382 return false;
383}
384
385
387 std::size_t numCore, std::size_t numLive,
388 double farChargeFraction, double maxFarFraction,
389 unsigned int minDwell) {
390 const double core = numCore;
391 const double live = numLive;
392 const unsigned int maxDwell = std::max(minDwell, 1u);
393 // dwell 0: the run has not solved yet
394 const unsigned int dwell = (previous.dwell == 0 ? maxDwell : previous.dwell);
395 const bool dwellReached = (dwell >= minDwell);
396 if (previous.mode == Mode::CORE) {
397 // a broken-up core leaves at once, a large far charge only after the dwell
398 if (core < std::max(minCoreParticles, minCoreFraction * live) ||
399 (dwellReached && farChargeFraction > maxFarFraction)) {
400 return ModeState{Mode::FULL, 1};
401 }
402 } else if (dwellReached &&
403 farChargeFraction < returnFarFactor * maxFarFraction &&
404 core > returnCoreFraction * live &&
405 core >= minCoreParticles) {
406 return ModeState{Mode::CORE, 1};
407 }
408 return ModeState{previous.mode, dwell < maxDwell ? dwell + 1 : maxDwell};
409}
T euclidean_norm(const Vector< T > &)
Euclidean norm.
Definition Vector.h:243
double dot(const Vector3D &lhs, const Vector3D &rhs)
Vector dot product.
Definition Vector3D.cpp:118
PartBunchBase< T, Dim >::ConstIterator end(PartBunchBase< T, Dim > const &bunch)
PartBunchBase< T, Dim >::ConstIterator begin(PartBunchBase< T, Dim > const &bunch)
void allreduce(const T *input, T *output, int count, Op op)
T trace(const AntiSymTenzor< T, D > &)
constexpr double returnCoreFraction
Definition CoreFitSC.h:86
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 returnFarFactor
Definition CoreFitSC.h:87
constexpr double coreShellFraction
Definition CoreFitSC.h:75
bool isInside(const Vector_t &r, const Vector_t &lower, const Vector_t &upper)
True if r lies in [lower, upper] in every axis.
Definition CoreFitSC.h:171
constexpr double flatWidth
Definition CoreFitSC.h:59
void addDirectField(const std::vector< Vector_t > &target, std::size_t begin, std::size_t end, const std::vector< Vector_t > &source, const std::vector< double > &charge, double eps, std::vector< Vector_t > &field)
ModeState decideMode(const ModeState &previous, std::size_t numCore, std::size_t numLive, double farChargeFraction, double maxFarFraction, unsigned int minDwell)
constexpr double haloSigma
The halo proper: live particles beyond haloSigma clipped rms widths in any axis.
Definition CoreFitSC.h:54
ParticleClass classify(int bin, const Vector_t &r, const Vector_t &boundsMin, const Vector_t &boundsMax, const Vector_t &meshMin, const Vector_t &meshMax)
constexpr double minCoreFraction
Definition CoreFitSC.h:85
void computeMultipoleField(const CoreMoments &moments, const std::vector< Vector_t > &position, std::size_t begin, std::size_t end, bool withQuadrupole, std::vector< Vector_t > &field, std::vector< double > &indicator)
std::pair< std::size_t, std::size_t > getTableRange(std::size_t n, int rank, int numRanks)
bool isInCoreShell(const Vector_t &r, const Vector_t &lower, const Vector_t &upper)
constexpr unsigned int maxClipPasses
Definition CoreFitSC.h:50
constexpr double minCoreParticles
Definition CoreFitSC.h:84
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)
@ FAR
outside that range: multipole (or exact core) field, plus far-far
@ INSIDE
lost (Bin < 0), inside the core bounds: gathered, not deposited
@ CORE
live, inside the core bounds: deposited, field gathered from the mesh
std::size_t getSampleStride(std::size_t numTargets, std::size_t numSources, double maxPairs)
Vector_t toRestFrame(const Vector_t &r, const Vector_t &r0, double gamma)
Definition CoreFitSC.h:198
constexpr double clipTolerance
The clipped passes stop when |dsigma_d| < clipTolerance * sigma_d in every axis.
Definition CoreFitSC.h:52
virtual void sum(double *values, unsigned int count) const =0
Sums over all ranks.
virtual void min(double *values, unsigned int count) const =0
Minima over all ranks (maxima are the minima of the negated values)
void sum(double *values, unsigned int count) const override
Sums over all ranks.
Definition CoreFitSC.cpp:74
void min(double *values, unsigned int count) const override
Minima over all ranks (maxima are the minima of the negated values)
Definition CoreFitSC.cpp:79
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
bool converged
false if the passes stopped at maxClipPasses
Definition CoreFitSC.h:132
std::size_t numLive
particles with Bin >= 0
Definition CoreFitSC.h:123
double chargeFar
charge of the far live particles [C]
Definition CoreFitSC.h:128
Vector_t boundsMin
minimum over the core particles [m]
Definition CoreFitSC.h:120
Vector_t mean
clipped mean [m]
Definition CoreFitSC.h:118
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
double chargeLive
charge of the live particles [C]
Definition CoreFitSC.h:127
std::size_t numCore
live particles within nSigma * sigma in every axis
Definition CoreFitSC.h:124
Rest-frame moments of the core charge.
Definition CoreFitSC.h:210
Vector_t centroid
c', rest frame, about the centre [m]
Definition CoreFitSC.h:212
double charge
Q_c [C].
Definition CoreFitSC.h:211
std::array< Vector_t, 3 > quadrupole
Definition CoreFitSC.h:213
void add(double q, const Vector_t &r)
Adds a particle of charge q at r (local frame, not rest frame)
std::array< double, 10 > sums_m
Definition CoreFitSC.h:232
CoreMoments reduce(const Reducer &reducer) const
Moments of all ranks' particles: one sum of 10 doubles.
MomentSums(const Vector_t &centre, double gamma)
unsigned int dwell
Definition CoreFitSC.h:313
Vektor< double, 3 > Vector_t
Definition Vektor.h:6