PartBunch.cpp 83.4 KB
Newer Older
gsell's avatar
gsell committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
// ------------------------------------------------------------------------
// $RCSfile: PartBunch.cpp,v $
// ------------------------------------------------------------------------
// $Revision: 1.1.1.1.2.1 $
// ------------------------------------------------------------------------
// Copyright: see Copyright.readme
// ------------------------------------------------------------------------
//
// Class PartBunch
//   Interface to a particle bunch.
//   Can be used to avoid use of a template in user code.
//
// ------------------------------------------------------------------------
// Class category: Algorithms
// ------------------------------------------------------------------------
//
// $Date: 2004/11/12 18:57:53 $
// $Author: adelmann $
//
// ------------------------------------------------------------------------

#include "Algorithms/PartBunch.h"
#include "FixedAlgebra/FMatrix.h"
#include "FixedAlgebra/FVector.h"
#include <iostream>
#include <cfloat>
#include <fstream>
#include <iomanip>
adelmann's avatar
adelmann committed
29
#include <memory>
30
#include <utility>
gsell's avatar
gsell committed
31

32 33 34
#include "AbstractObjects/OpalData.h"   // OPAL file
#include "Distribution/Distribution.h"  // OPAL file
#include "Structure/FieldSolver.h"      // OPAL file
kraus's avatar
kraus committed
35 36
#include "Structure/LossDataSink.h"
#include "Utilities/Options.h"
adelmann's avatar
adelmann committed
37
#include "Utilities/GeneralClassicException.h"
38
#include "Utilities/Util.h"
gsell's avatar
gsell committed
39

kraus's avatar
kraus committed
40
#include "Algorithms/ListElem.h"
gsell's avatar
gsell committed
41 42 43 44 45 46 47 48

#include <gsl/gsl_rng.h>
#include <gsl/gsl_histogram.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_sf_erf.h>
#include <gsl/gsl_qrng.h>

49 50 51 52
#ifdef OPAL_NOCPLUSPLUS11_NULLPTR
#define nullptr NULL
#endif

53
//#define DBG_SCALARFIELD
adelmann's avatar
adelmann committed
54
//#define FIELDSTDOUT
55

gsell's avatar
gsell committed
56 57
using Physics::pi;

58 59
using namespace std;

gsell's avatar
gsell committed
60 61 62 63 64 65 66 67 68
extern Inform *gmsg;

// Class PartBunch
// ------------------------------------------------------------------------

PartBunch::PartBunch(const PartData *ref):
    myNode_m(Ippl::myNode()),
    nodes_m(Ippl::getNodes()),
    fixed_grid(false),
69
    pbin_m(nullptr),
70 71 72
    lossDs_m(nullptr),
    pmsg_m(nullptr),
    f_stream(nullptr),
gsell's avatar
gsell committed
73
    reference(ref),
74 75
    unit_state_(units),
    stateOfLastBoundP_(unitless),
gsell's avatar
gsell committed
76 77 78 79 80
    moments_m(),
    dt_m(0.0),
    t_m(0.0),
    eKin_m(0.0),
    dE_m(0.0),
81
    spos_m(0.0),
gsell's avatar
gsell committed
82 83 84 85 86 87 88 89 90 91 92 93 94
    rmax_m(0.0),
    rmin_m(0.0),
    rrms_m(0.0),
    prms_m(0.0),
    rmean_m(0.0),
    pmean_m(0.0),
    eps_m(0.0),
    eps_norm_m(0.0),
    rprms_m(0.0),
    Dx_m(0.0),
    Dy_m(0.0),
    DDx_m(0.0),
    DDy_m(0.0),
95
    hr_m(-1.0),
gsell's avatar
gsell committed
96
    nr_m(0),
97
    fs_m(nullptr),
gsell's avatar
gsell committed
98 99
    couplingConstant_m(0.0),
    qi_m(0.0),
100
    interpolationCacheSet_m(false),
gsell's avatar
gsell committed
101 102
    distDump_m(0),
    fieldDBGStep_m(0),
103
    dh_m(1e-12),
gsell's avatar
gsell committed
104
    tEmission_m(0.0),
105 106
    bingamma_m(nullptr),
    binemitted_m(nullptr),
gsell's avatar
gsell committed
107 108
    lPath_m(0.0),
    stepsPerTurn_m(0),
109 110
    localTrackStep_m(0),
    globalTrackStep_m(0),
gsell's avatar
gsell committed
111 112
    numBunch_m(1),
    SteptoLastInj_m(0),
113 114
    partPerNode_m(nullptr),
    globalPartPerNode_m(nullptr),
115
    dist_m(nullptr),
adelmann's avatar
adelmann committed
116 117
    globalMeanR_m(Vector_t(0.0, 0.0, 0.0)),
    globalToLocalQuaternion_m(Quaternion_t(1.0, 0.0, 0.0, 0.0)),
118
    lowParticleCount_m(false),
119 120
    dcBeam_m(false),
    minLocNum_m(0) {
gsell's avatar
gsell committed
121 122 123
    addAttribute(P);
    addAttribute(Q);
    addAttribute(M);
124
    addAttribute(Phi);
gsell's avatar
gsell committed
125 126 127 128 129 130 131 132 133 134
    addAttribute(Ef);
    addAttribute(Eftmp);

    addAttribute(Bf);
    addAttribute(Bin);
    addAttribute(dt);
    addAttribute(PType);
    addAttribute(TriID);

    boundpTimer_m = IpplTimings::getTimer("Boundingbox");
135
    statParamTimer_m = IpplTimings::getTimer("Compute Statistics");
kraus's avatar
kraus committed
136 137
    selfFieldTimer_m = IpplTimings::getTimer("SelfField total");
    compPotenTimer_m  = IpplTimings::getTimer("SF: Potential");
gsell's avatar
gsell committed
138 139 140

    histoTimer_m = IpplTimings::getTimer("Histogram");

kraus's avatar
kraus committed
141 142
    distrCreate_m = IpplTimings::getTimer("Create Distr");
    distrReload_m = IpplTimings::getTimer("Load Distr");
gsell's avatar
gsell committed
143 144


145 146
    partPerNode_m = std::unique_ptr<size_t[]>(new size_t[Ippl::getNodes()]);
    globalPartPerNode_m = std::unique_ptr<size_t[]>(new size_t[Ippl::getNodes()]);
gsell's avatar
gsell committed
147

adelmann's avatar
adelmann committed
148
    lossDs_m = std::unique_ptr<LossDataSink>(new LossDataSink(std::string("GlobalLosses"), !Options::asciidump));
gsell's avatar
gsell committed
149

150
    pmsg_m.release();
151 152
    //    f_stream.release();
    /*
153 154 155 156 157
      if(Ippl::getNodes() == 1) {
          f_stream = std::unique_ptr<ofstream>(new ofstream);
          f_stream->open("data/dist.dat", ios::out);
          pmsg_m = std::unique_ptr<Inform>(new Inform(0, *f_stream, 0));
      }
158
    */
159 160

    // set the default IPPL behaviour
161
    setMinimumNumberOfParticlesPerCore(0);
gsell's avatar
gsell committed
162 163 164
}

PartBunch::PartBunch(const PartBunch &rhs):
165
    IpplParticleBase<ParticleSpatialLayout<double, 3u> >(rhs),
gsell's avatar
gsell committed
166 167 168
    myNode_m(Ippl::myNode()),
    nodes_m(Ippl::getNodes()),
    fixed_grid(rhs.fixed_grid),
169
    pbin_m(nullptr),
170 171 172
    lossDs_m(nullptr),
    pmsg_m(nullptr),
    f_stream(nullptr),
gsell's avatar
gsell committed
173
    reference(rhs.reference),
174 175
    unit_state_(rhs.unit_state_),
    stateOfLastBoundP_(rhs.stateOfLastBoundP_),
gsell's avatar
gsell committed
176 177 178 179 180
    moments_m(rhs.moments_m),
    dt_m(rhs.dt_m),
    t_m(rhs.t_m),
    eKin_m(rhs.eKin_m),
    dE_m(rhs.dE_m),
181
    spos_m(0.0),
gsell's avatar
gsell committed
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
    rmax_m(rhs.rmax_m),
    rmin_m(rhs.rmin_m),
    rrms_m(rhs.rrms_m),
    prms_m(rhs.prms_m),
    rmean_m(rhs.rmean_m),
    pmean_m(rhs.pmean_m),
    eps_m(rhs.eps_m),
    eps_norm_m(rhs.eps_norm_m),
    rprms_m(rhs.rprms_m),
    Dx_m(rhs.Dx_m),
    Dy_m(rhs.Dy_m),
    DDx_m(rhs.DDx_m),
    DDy_m(rhs.DDy_m),
    hr_m(rhs.hr_m),
    nr_m(rhs.nr_m),
197
    fs_m(nullptr),
gsell's avatar
gsell committed
198 199
    couplingConstant_m(rhs.couplingConstant_m),
    qi_m(rhs.qi_m),
200
    interpolationCacheSet_m(rhs.interpolationCacheSet_m),
gsell's avatar
gsell committed
201 202 203 204
    distDump_m(rhs.distDump_m),
    fieldDBGStep_m(rhs.fieldDBGStep_m),
    dh_m(rhs.dh_m),
    tEmission_m(rhs.tEmission_m),
205 206
    bingamma_m(nullptr),
    binemitted_m(nullptr),
gsell's avatar
gsell committed
207 208
    lPath_m(rhs.lPath_m),
    stepsPerTurn_m(rhs.stepsPerTurn_m),
209 210
    localTrackStep_m(rhs.localTrackStep_m),
    globalTrackStep_m(rhs.globalTrackStep_m),
gsell's avatar
gsell committed
211 212
    numBunch_m(rhs.numBunch_m),
    SteptoLastInj_m(rhs.SteptoLastInj_m),
213 214
    partPerNode_m(nullptr),
    globalPartPerNode_m(nullptr),
215
    dist_m(nullptr),
adelmann's avatar
adelmann committed
216 217
    globalMeanR_m(Vector_t(0.0, 0.0, 0.0)),
    globalToLocalQuaternion_m(Quaternion_t(1.0, 0.0, 0.0, 0.0)),
218
    lowParticleCount_m(rhs.lowParticleCount_m),
219 220
    dcBeam_m(rhs.dcBeam_m),
    minLocNum_m(rhs.minLocNum_m) {
gsell's avatar
gsell committed
221
    ERRORMSG("should not be here: PartBunch::PartBunch(const PartBunch &rhs):" << endl);
222
    std::exit(0);
gsell's avatar
gsell committed
223 224 225 226 227 228
}

PartBunch::PartBunch(const std::vector<Particle> &rhs, const PartData *ref):
    myNode_m(Ippl::myNode()),
    nodes_m(Ippl::getNodes()),
    fixed_grid(false),
229
    pbin_m(nullptr),
230 231 232
    lossDs_m(nullptr),
    pmsg_m(nullptr),
    f_stream(nullptr),
gsell's avatar
gsell committed
233
    reference(ref),
234 235
    unit_state_(units),
    stateOfLastBoundP_(unitless),
gsell's avatar
gsell committed
236 237 238 239 240
    moments_m(),
    dt_m(0.0),
    t_m(0.0),
    eKin_m(0.0),
    dE_m(0.0),
241
    spos_m(0.0),
gsell's avatar
gsell committed
242 243 244 245 246 247 248 249 250 251 252 253 254
    rmax_m(0.0),
    rmin_m(0.0),
    rrms_m(0.0),
    prms_m(0.0),
    rmean_m(0.0),
    pmean_m(0.0),
    eps_m(0.0),
    eps_norm_m(0.0),
    rprms_m(0.0),
    Dx_m(0.0),
    Dy_m(0.0),
    DDx_m(0.0),
    DDy_m(0.0),
255
    hr_m(-1.0),
gsell's avatar
gsell committed
256
    nr_m(0),
257
    fs_m(nullptr),
gsell's avatar
gsell committed
258 259
    couplingConstant_m(0.0),
    qi_m(0.0),
260
    interpolationCacheSet_m(false),
gsell's avatar
gsell committed
261 262
    distDump_m(0),
    fieldDBGStep_m(0),
263
    dh_m(1e-12),
gsell's avatar
gsell committed
264
    tEmission_m(0.0),
265 266
    bingamma_m(nullptr),
    binemitted_m(nullptr),
gsell's avatar
gsell committed
267 268
    lPath_m(0.0),
    stepsPerTurn_m(0),
269 270
    localTrackStep_m(0),
    globalTrackStep_m(0),
gsell's avatar
gsell committed
271 272
    numBunch_m(1),
    SteptoLastInj_m(0),
273 274
    partPerNode_m(nullptr),
    globalPartPerNode_m(nullptr),
275
    dist_m(nullptr),
adelmann's avatar
adelmann committed
276 277
    globalMeanR_m(Vector_t(0.0, 0.0, 0.0)),
    globalToLocalQuaternion_m(Quaternion_t(1.0, 0.0, 0.0, 0.0)),
278
    dcBeam_m(false),
279 280
    lowParticleCount_m(false),
    minLocNum_m(0) {
gsell's avatar
gsell committed
281 282 283
    ERRORMSG("should not be here: PartBunch::PartBunch(const std::vector<Particle> &rhs, const PartData *ref):" << endl);
}

284 285 286 287
PartBunch::~PartBunch() {

}

gsell's avatar
gsell committed
288 289 290
/// \brief Need Ek for the Schottky effect calculation (eV)
double PartBunch::getEkin() const {
    if(dist_m)
291
        return dist_m->getEkin();
gsell's avatar
gsell committed
292 293 294 295 296 297 298
    else
        return 0.0;
}

/// \brief Need the work function for the Schottky effect calculation (eV)
double PartBunch::getWorkFunctionRf() const {
    if(dist_m)
299
        return dist_m->getWorkFunctionRf();
gsell's avatar
gsell committed
300 301 302 303 304 305
    else
        return 0.0;
}
/// \brief Need the laser energy for the Schottky effect calculation (eV)
double PartBunch::getLaserEnergy() const {
    if(dist_m)
306
        return dist_m->getLaserEnergy();
gsell's avatar
gsell committed
307 308 309 310
    else
        return 0.0;
}

311 312 313
/// \brief Return the fieldsolver type if we have a fieldsolver
std::string PartBunch::getFieldSolverType() const {
    if(fs_m)
kraus's avatar
kraus committed
314
        return fs_m->getFieldSolverType();
315 316 317
    else
        return "";
}
gsell's avatar
gsell committed
318

319
void PartBunch::runTests() {
320

321 322 323
    Vector_t ll(-0.005);
    Vector_t ur(0.005);

324 325
    setBCAllPeriodic();

326 327 328
    NDIndex<3> domain = getFieldLayout().getDomain();
    for(int i = 0; i < Dim; i++)
        nr_m[i] = domain[i].length();
329

330 331
    for(int i = 0; i < 3; i++)
        hr_m[i] = (ur[i] - ll[i]) / nr_m[i];
332

333 334
    getMesh().set_meshSpacing(&(hr_m[0]));
    getMesh().set_origin(ll);
335

336 337 338 339 340 341 342 343 344 345 346 347 348
    rho_m.initialize(getMesh(),
                     getFieldLayout(),
                     GuardCellSizes<Dim>(1),
                     bc_m);
    eg_m.initialize(getMesh(),
                    getFieldLayout(),
                    GuardCellSizes<Dim>(1),
                    vbc_m);

    fs_m->solver_m->test(*this);
}


gsell's avatar
gsell committed
349 350 351 352 353 354 355 356 357 358
/** \brief After each Schottky scan we delete all the particles.

 */
void PartBunch::cleanUpParticles() {

    size_t np = getTotalNum();
    bool scan = false;

    destroy(getLocalNum(), 0, true);

359
    dist_m->createOpalT(*this, np, scan);
gsell's avatar
gsell committed
360 361 362 363

    update();
}

364 365 366 367 368
void PartBunch::setDistribution(Distribution *d,
                                std::vector<Distribution *> addedDistributions,
                                size_t &np,
                                bool scan) {
    Inform m("setDistribution " );
gsell's avatar
gsell committed
369
    dist_m = d;
370

371
    dist_m->createOpalT(*this, addedDistributions, np, scan);
372

373
//    if (Options::cZero)
374
//        dist_m->create(*this, addedDistributions, np / 2, scan);
375
//    else
376
//        dist_m->create(*this, addedDistributions, np, scan);
gsell's avatar
gsell committed
377 378 379 380 381 382 383 384 385
}

void PartBunch::resetIfScan()
/*
  In case of a scan we have
  to reset some variables
 */
{
    dt = 0.0;
386
    localTrackStep_m = 0;
gsell's avatar
gsell committed
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
}



bool PartBunch::hasFieldSolver() {
    if(fs_m)
        return fs_m->hasValidSolver();
    else
        return false;
}

double PartBunch::getPx(int i) {
    return 0.0;
}

double PartBunch::getPy(int i) {
    return 0.0;
}

double PartBunch::getPz(int i) {
    return 0.0;
}

//ff
double PartBunch::getX(int i) {
    return this->R[i](0);
}

//ff
double PartBunch::getY(int i) {
    return this->R[i](1);
}

//ff
double PartBunch::getX0(int i) {
    return 0.0;
}

//ff
double PartBunch::getY0(int i) {
    return 0.0;
}

//ff
double PartBunch::getZ(int i) {
    return this->R[i](2);
}

435 436 437 438 439 440 441 442 443 444

/**
 * \method calcLineDensity()
 * \brief calculates the 1d line density (not normalized) and append it to a file.
 * \see ParallelTTracker
 * \warning none yet
 *
 * DETAILED TODO
 *
 */
445 446 447 448 449 450 451
void PartBunch::calcLineDensity(unsigned int nBins, std::vector<double> &lineDensity, std::pair<double, double> &meshInfo) {
    Vector_t rmin, rmax;
    get_bounds(rmin, rmax);

    if (nBins < 2) {
        NDIndex<3> grid = getFieldLayout().getDomain();
        nBins = grid[2].length();
gsell's avatar
gsell committed
452 453
    }

454 455 456 457 458
    double length = rmax(2) - rmin(2);
    double zmin = rmin(2) - dh_m * length, zmax = rmax(2) + dh_m * length;
    double hz = (zmax - zmin) / (nBins - 2);
    double perMeter = 1.0 / hz;//(zmax - zmin);
    zmin -= hz;
gsell's avatar
gsell committed
459

460 461
    lineDensity.resize(nBins, 0.0);
    std::fill(lineDensity.begin(), lineDensity.end(), 0.0);
gsell's avatar
gsell committed
462

463 464 465 466 467
    const unsigned int lN = getLocalNum();
    for (unsigned int i = 0; i < lN; ++ i) {
        const double z = R[i](2) - 0.5 * hz;
        unsigned int idx = (z - zmin) / hz;
        double tau = z - (zmin + idx * hz);
gsell's avatar
gsell committed
468

469 470
        lineDensity[idx] += Q[i] * (1.0 - tau) * perMeter;
        lineDensity[idx + 1] += Q[i] * tau * perMeter;
gsell's avatar
gsell committed
471 472
    }

473 474 475 476
    reduce(&(lineDensity[0]), &(lineDensity[0]) + nBins, &(lineDensity[0]), OpAddAssign());

    meshInfo.first = zmin;
    meshInfo.second = hz;
gsell's avatar
gsell committed
477 478 479 480
}

void PartBunch::calcGammas() {

481
    const int emittedBins = dist_m->getNumberOfEnergyBins();
482

gsell's avatar
gsell committed
483 484 485 486 487 488 489 490
    size_t s = 0;

    for(int i = 0; i < emittedBins; i++)
        bingamma_m[i] = 0.0;

    for(unsigned int n = 0; n < getLocalNum(); n++)
        bingamma_m[this->Bin[n]] += sqrt(1.0 + dot(this->P[n], this->P[n]));

491 492 493
    std::unique_ptr<size_t[]> particlesInBin(new size_t[emittedBins]);
    reduce(bingamma_m.get(), bingamma_m.get() + emittedBins, bingamma_m.get(), OpAddAssign());
    reduce(binemitted_m.get(), binemitted_m.get() + emittedBins, particlesInBin.get(), OpAddAssign());
gsell's avatar
gsell committed
494
    for(int i = 0; i < emittedBins; i++) {
495
        size_t &pInBin = particlesInBin[i];
gsell's avatar
gsell committed
496 497
        if(pInBin != 0) {
            bingamma_m[i] /= pInBin;
498
            INFOMSG(level2 << "Bin " << std::setw(3) << i << " gamma = " << std::setw(8) << std::scientific << std::setprecision(5) << bingamma_m[i] << "; NpInBin= " << std::setw(8) << std::setfill(' ') << pInBin << endl);
gsell's avatar
gsell committed
499 500
        } else {
            bingamma_m[i] = 1.0;
501
            INFOMSG(level2 << "Bin " << std::setw(3) << i << " has no particles " << endl);
gsell's avatar
gsell committed
502 503 504
        }
        s += pInBin;
    }
505
    particlesInBin.reset();
kraus's avatar
kraus committed
506 507


508
    if(s != getTotalNum() && !OpalData::getInstance()->hasGlobalGeometry())
gsell's avatar
gsell committed
509 510 511 512 513
        ERRORMSG("sum(Bins)= " << s << " != sum(R)= " << getTotalNum() << endl;);

    if(emittedBins >= 2) {
        for(int i = 1; i < emittedBins; i++) {
            if(binemitted_m[i - 1] != 0 && binemitted_m[i] != 0)
kraus's avatar
kraus committed
514 515
                INFOMSG(level2 << "d(gamma)= " << 100.0 * std::abs(bingamma_m[i - 1] - bingamma_m[i]) / bingamma_m[i] << " [%] "
                        << "between bin " << i - 1 << " and " << i << endl);
gsell's avatar
gsell committed
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
        }
    }
}


void PartBunch::calcGammas_cycl() {

    const int emittedBins = pbin_m->getLastemittedBin();

    for(int i = 0; i < emittedBins; i++)
        bingamma_m[i] = 0.0;
    for(unsigned int n = 0; n < getLocalNum(); n++)
        bingamma_m[this->Bin[n]] += sqrt(1.0 + dot(this->P[n], this->P[n]));
    for(int i = 0; i < emittedBins; i++) {
        reduce(bingamma_m[i], bingamma_m[i], OpAddAssign());
        if(pbin_m->getTotalNumPerBin(i) > 0)
            bingamma_m[i] /= pbin_m->getTotalNumPerBin(i);
        else
            bingamma_m[i] = 0.0;
535
        INFOMSG("Bin " << i << " : particle number = " << pbin_m->getTotalNumPerBin(i) << " gamma = " << bingamma_m[i] << endl);
gsell's avatar
gsell committed
536 537 538 539
    }

}

540
size_t PartBunch::calcNumPartsOutside(Vector_t x) {
kraus's avatar
kraus committed
541

542
    partPerNode_m[Ippl::myNode()] = 0;
kraus's avatar
kraus committed
543 544
    const Vector_t meanR = get_rmean();

545
    for(unsigned long k = 0; k < getLocalNum(); ++ k)
kraus's avatar
kraus committed
546 547 548 549 550 551 552
        if (abs(R[k](0) - meanR(0)) > x(0) ||
            abs(R[k](1) - meanR(1)) > x(1) ||
            abs(R[k](2) - meanR(2)) > x(2)) {

            ++ partPerNode_m[Ippl::myNode()];
        }

553 554
    reduce(partPerNode_m.get(), partPerNode_m.get() + Ippl::getNodes(), globalPartPerNode_m.get(), OpAddAssign());

kraus's avatar
kraus committed
555
    return *globalPartPerNode_m.get();
556
}
gsell's avatar
gsell committed
557 558 559 560 561 562 563 564 565 566 567 568 569

void PartBunch::computeSelfFields(int binNumber) {
    IpplTimings::startTimer(selfFieldTimer_m);

    /// Set initial charge density to zero. Create image charge
    /// potential field.
    rho_m = 0.0;
    Field_t imagePotential = rho_m;

    /// Set initial E field to zero.
    eg_m = Vector_t(0.0);

    if(fs_m->hasValidSolver()) {
570 571 572
        /// Mesh the whole domain
        if(fs_m->getFieldSolverType() == "SAAMG")
            resizeMesh();
573

gsell's avatar
gsell committed
574 575
        /// Scatter charge onto space charge grid.
        this->Q *= this->dt;
576 577
        if(!interpolationCacheSet_m) {
            if(interpolationCache_m.size() < getLocalNum()) {
578 579 580
                interpolationCache_m.create(getLocalNum() - interpolationCache_m.size());
            } else {
                interpolationCache_m.destroy(interpolationCache_m.size() - getLocalNum(),
581 582
                                             getLocalNum(),
                                             true);
583 584 585 586 587 588 589
            }
            interpolationCacheSet_m = true;

            this->Q.scatter(this->rho_m, this->R, IntrplCIC_t(), interpolationCache_m);
        } else {
            this->Q.scatter(this->rho_m, IntrplCIC_t(), interpolationCache_m);
        }
gsell's avatar
gsell committed
590 591 592 593
        this->Q /= this->dt;
        this->rho_m /= getdT();

        /// Calculate mesh-scale factor and get gamma for this specific slice (bin).
594 595
        double scaleFactor = 1;
        // double scaleFactor = Physics::c * getdT();
gsell's avatar
gsell committed
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
        double gammaz = getBinGamma(binNumber);

        /// Scale charge density to get charge density in real units. Account for
        /// Lorentz transformation in longitudinal direction.
        double tmp2 = 1 / hr_m[0] * 1 / hr_m[1] * 1 / hr_m[2] / (scaleFactor * scaleFactor * scaleFactor) / gammaz;
        rho_m *= tmp2;

        /// Scale mesh spacing to real units (meters). Lorentz transform the
        /// longitudinal direction.
        Vector_t hr_scaled = hr_m * Vector_t(scaleFactor);
        hr_scaled[2] *= gammaz;

        /// Find potential from charge in this bin (no image yet) using Poisson's
        /// equation (without coefficient: -1/(eps)).
        IpplTimings::startTimer(compPotenTimer_m);
        imagePotential = rho_m;
612

gsell's avatar
gsell committed
613
        fs_m->solver_m->computePotential(rho_m, hr_scaled);
614

gsell's avatar
gsell committed
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
        IpplTimings::stopTimer(compPotenTimer_m);

        /// Scale mesh back (to same units as particle locations.)
        rho_m *= hr_scaled[0] * hr_scaled[1] * hr_scaled[2];

        /// The scalar potential is given back in rho_m
        /// and must be converted to the right units.
        rho_m *= getCouplingConstant();

        /// IPPL Grad numerical computes gradient to find the
        /// electric field (in bin rest frame).
        eg_m = -Grad(rho_m, eg_m);

        /// Scale field. Combine Lorentz transform with conversion to proper field
        /// units.
        eg_m *= Vector_t(gammaz / (scaleFactor), gammaz / (scaleFactor), 1.0 / (scaleFactor * gammaz));

632 633 634 635 636 637 638 639 640 641 642 643
        // If desired write E-field and potential to terminal
#ifdef FIELDSTDOUT
        // Immediate debug output:
        // Output potential and e-field along the x-, y-, and z-axes
        int mx = (int)nr_m[0];
        int mx2 = (int)nr_m[0] / 2;
        int my = (int)nr_m[1];
        int my2 = (int)nr_m[1] / 2;
        int mz = (int)nr_m[2];
        int mz2 = (int)nr_m[2] / 2;

        for (int i=0; i<mx; i++ )
644 645
	    *gmsg << "Bin " << binNumber
                  << ", Self Field along x axis E = " << eg_m[i][my2][mz2]
646 647 648
                  << ", Pot = " << rho_m[i][my2][mz2]  << endl;

        for (int i=0; i<my; i++ )
649 650
            *gmsg << "Bin " << binNumber
                  << ", Self Field along y axis E = " << eg_m[mx2][i][mz2]
651 652 653
                  << ", Pot = " << rho_m[mx2][i][mz2]  << endl;

        for (int i=0; i<mz; i++ )
654 655
            *gmsg << "Bin " << binNumber
                  << ", Self Field along z axis E = " << eg_m[mx2][my2][i]
656 657 658
                  << ", Pot = " << rho_m[mx2][my2][i]  << endl;
#endif

gsell's avatar
gsell committed
659 660 661 662
        /// Interpolate electric field at particle positions.  We reuse the
        /// cached information about where the particles are relative to the
        /// field, since the particles have not moved since this the most recent
        /// scatter operation.
663 664
        Eftmp.gather(eg_m, IntrplCIC_t(), interpolationCache_m);
        //Eftmp.gather(eg_m, this->R, IntrplCIC_t());
gsell's avatar
gsell committed
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683

        /** Magnetic field in x and y direction induced by the electric field.
         *
         *  \f[ B_x = \gamma(B_x^{'} - \frac{beta}{c}E_y^{'}) = -\gamma \frac{beta}{c}E_y^{'} = -\frac{beta}{c}E_y \f]
         *  \f[ B_y = \gamma(B_y^{'} - \frac{beta}{c}E_x^{'}) = +\gamma \frac{beta}{c}E_x^{'} = +\frac{beta}{c}E_x \f]
         *  \f[ B_z = B_z^{'} = 0 \f]
         *
         */
        double betaC = sqrt(gammaz * gammaz - 1.0) / gammaz / Physics::c;

        Bf(0) = Bf(0) - betaC * Eftmp(1);
        Bf(1) = Bf(1) + betaC * Eftmp(0);

        Ef += Eftmp;

        /// Now compute field due to image charge. This is done separately as the image charge
        /// is moving to -infinity (instead of +infinity) so the Lorentz transform is different.

        /// Find z shift for shifted Green's function.
684 685 686 687
        NDIndex<3> domain = getFieldLayout().getDomain();
        Vector_t origin = rho_m.get_mesh().get_origin();
        double hz = rho_m.get_mesh().get_meshSpacing(2);
        double zshift = -(2 * origin(2) + (domain[2].first() + domain[2].last() + 1) * hz) * gammaz * scaleFactor;
gsell's avatar
gsell committed
688 689 690 691 692 693 694 695 696 697 698 699 700 701

        /// Find potential from image charge in this bin using Poisson's
        /// equation (without coefficient: -1/(eps)).
        IpplTimings::startTimer(compPotenTimer_m);
        fs_m->solver_m->computePotential(imagePotential, hr_scaled, zshift);
        IpplTimings::stopTimer(compPotenTimer_m);

        /// Scale mesh back (to same units as particle locations.)
        imagePotential *= hr_scaled[0] * hr_scaled[1] * hr_scaled[2];

        /// The scalar potential is given back in rho_m
        /// and must be converted to the right units.
        imagePotential *= getCouplingConstant();

702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
#ifdef DBG_SCALARFIELD
        int dumpFreq = 100;
        if ((fieldDBGStep_m + 1) % dumpFreq == 0) {
            INFOMSG("*** START DUMPING SCALAR FIELD ***" << endl);

            ofstream fstr2;
            fstr2.precision(9);

            std::string SfileName = OpalData::getInstance()->getInputBasename();

            std::string phi_fn = std::string("data/") + SfileName + std::string("-phi_scalar-") + std::to_string(fieldDBGStep_m / dumpFreq);
            fstr2.open(phi_fn.c_str(), ios::out);
            NDIndex<3> myidx = getFieldLayout().getLocalNDIndex();
            Vector_t origin = rho_m.get_mesh().get_origin();
            Vector_t spacing(rho_m.get_mesh().get_meshSpacing(0),
                             rho_m.get_mesh().get_meshSpacing(1),
                             rho_m.get_mesh().get_meshSpacing(2));
            *gmsg << (rmin(0) - origin(0)) / spacing(0) << "\t"
                  << (rmin(1)  - origin(1)) / spacing(1) << "\t"
                  << (rmin(2)  - origin(2)) / spacing(2) << "\t"
                  << rmin(2) << endl;
            for(int x = myidx[0].first(); x <= myidx[0].last(); x++) {
                for(int y = myidx[1].first(); y <= myidx[1].last(); y++) {
                    for(int z = myidx[2].first(); z <= myidx[2].last(); z++) {
                        fstr2 << std::setw(5) << x + 1
                              << std::setw(5) << y + 1
                              << std::setw(5) << z + 1
                              << std::setw(17) << origin(2) + z * spacing(2)
                              << std::setw(17) << rho_m[x][y][z].get()
                              << std::setw(17) << imagePotential[x][y][z].get() << endl;
                    }
                }
            }
            fstr2.close();

            INFOMSG("*** FINISHED DUMPING SCALAR FIELD ***" << endl);
        }

        auto tmp_eg = eg_m;
#endif

gsell's avatar
gsell committed
743 744 745 746 747 748 749 750 751
        /// IPPL Grad numerical computes gradient to find the
        /// electric field (in rest frame of this bin's image
        /// charge).
        eg_m = -Grad(imagePotential, eg_m);

        /// Scale field. Combine Lorentz transform with conversion to proper field
        /// units.
        eg_m *= Vector_t(gammaz / (scaleFactor), gammaz / (scaleFactor), 1.0 / (scaleFactor * gammaz));

752 753 754 755
        // If desired write E-field and potential to terminal
#ifdef FIELDSTDOUT
        // Immediate debug output:
        // Output potential and e-field along the x-, y-, and z-axes
756 757 758 759 760 761
        //int mx = (int)nr_m[0];
        //int mx2 = (int)nr_m[0] / 2;
        //int my = (int)nr_m[1];
        //int my2 = (int)nr_m[1] / 2;
        //int mz = (int)nr_m[2];
        //int mz2 = (int)nr_m[2] / 2;
762 763

        for (int i=0; i<mx; i++ )
764 765
	    *gmsg << "Bin " << binNumber
                  << ", Image Field along x axis E = " << eg_m[i][my2][mz2]
766 767 768
                  << ", Pot = " << rho_m[i][my2][mz2]  << endl;

        for (int i=0; i<my; i++ )
769 770
            *gmsg << "Bin " << binNumber
                  << ", Image Field along y axis E = " << eg_m[mx2][i][mz2]
771 772 773
                  << ", Pot = " << rho_m[mx2][i][mz2]  << endl;

        for (int i=0; i<mz; i++ )
774 775
            *gmsg << "Bin " << binNumber
                  << ", Image Field along z axis E = " << eg_m[mx2][my2][i]
776 777 778
                  << ", Pot = " << rho_m[mx2][my2][i]  << endl;
#endif

779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
#ifdef DBG_SCALARFIELD
        if ((fieldDBGStep_m + 1) % dumpFreq == 0) {
            INFOMSG("*** START DUMPING E FIELD ***" << endl);

            std::string SfileName = OpalData::getInstance()->getInputBasename();

            ofstream fstr2;
            fstr2.precision(9);

            std::string e_field = std::string("data/") + SfileName + std::string("-e_field-") + std::to_string(fieldDBGStep_m / dumpFreq);
            Vector_t origin = eg_m.get_mesh().get_origin();
            Vector_t spacing(eg_m.get_mesh().get_meshSpacing(0),
                             eg_m.get_mesh().get_meshSpacing(1),
                             eg_m.get_mesh().get_meshSpacing(2));
            fstr2.open(e_field.c_str(), ios::out);
            NDIndex<3> myidxx = getFieldLayout().getLocalNDIndex();
            for(int x = myidxx[0].first(); x <= myidxx[0].last(); x++) {
                for(int y = myidxx[1].first(); y <= myidxx[1].last(); y++) {
                    for(int z = myidxx[2].first(); z <= myidxx[2].last(); z++) {
                        Vector_t ef = eg_m[x][y][z].get() + tmp_eg[x][y][z].get();
                        fstr2 << std::setw(5) << x + 1
                              << std::setw(5) << y + 1
                              << std::setw(5) << z + 1
                              << std::setw(17) << origin(2) + z * spacing(2)
                              << std::setw(17) << ef(0)
                              << std::setw(17) << ef(1)
                              << std::setw(17) << ef(2) << endl;
                    }
                }
            }

            fstr2.close();

            //MPI_File_write_shared(file, (char*)oss.str().c_str(), oss.str().length(), MPI_CHAR, &status);
            //MPI_File_close(&file);

            INFOMSG("*** FINISHED DUMPING E FIELD ***" << endl);
        }
817
        fieldDBGStep_m++;
818 819
#endif

gsell's avatar
gsell committed
820 821 822 823
        /// Interpolate electric field at particle positions.  We reuse the
        /// cached information about where the particles are relative to the
        /// field, since the particles have not moved since this the most recent
        /// scatter operation.
824 825
        Eftmp.gather(eg_m, IntrplCIC_t(), interpolationCache_m);
        //Eftmp.gather(eg_m, this->R, IntrplCIC_t());
gsell's avatar
gsell committed
826 827 828 829 830 831 832 833 834 835 836 837 838

        /** Magnetic field in x and y direction induced by the image charge electric field. Note that beta will have
         *  the opposite sign from the bunch charge field, as the image charge is moving in the opposite direction.
         *
         *  \f[ B_x = \gamma(B_x^{'} - \frac{beta}{c}E_y^{'}) = -\gamma \frac{beta}{c}E_y^{'} = -\frac{beta}{c}E_y \f]
         *  \f[ B_y = \gamma(B_y^{'} - \frac{beta}{c}E_x^{'}) = +\gamma \frac{beta}{c}E_x^{'} = +\frac{beta}{c}E_x \f]
         *  \f[ B_z = B_z^{'} = 0 \f]
         *
         */
        Bf(0) = Bf(0) + betaC * Eftmp(1);
        Bf(1) = Bf(1) - betaC * Eftmp(0);

        Ef += Eftmp;
839

gsell's avatar
gsell committed
840 841 842 843 844
    }
    IpplTimings::stopTimer(selfFieldTimer_m);
}

void PartBunch::resizeMesh() {
845 846 847 848
    double xmin = fs_m->solver_m->getXRangeMin();
    double xmax = fs_m->solver_m->getXRangeMax();
    double ymin = fs_m->solver_m->getYRangeMin();
    double ymax = fs_m->solver_m->getYRangeMax();
849 850
    double zmin = fs_m->solver_m->getZRangeMin();
    double zmax = fs_m->solver_m->getZRangeMax();
kraus's avatar
kraus committed
851

gsell's avatar
gsell committed
852 853 854 855 856 857 858 859 860
    if(xmin > rmin_m[0] || xmax < rmax_m[0] ||
       ymin > rmin_m[1] || ymax < rmax_m[1]) {

        for(unsigned int n = 0; n < getLocalNum(); n++) {

            if(R[n](0) < xmin || R[n](0) > xmax ||
               R[n](1) < ymin || R[n](1) > ymax) {

                // delete the particle
861
                INFOMSG(level2 << "destroyed particle with id=" << ID[n] << endl;);
gsell's avatar
gsell committed
862 863 864 865 866 867 868 869 870
                destroy(1, n);
            }

        }

        update();
        boundp();
        get_bounds(rmin_m, rmax_m);
    }
871 872
    Vector_t mymin = Vector_t(xmin, ymin , zmin);
    Vector_t mymax = Vector_t(xmax, ymax , zmax);
gsell's avatar
gsell committed
873

kraus's avatar
kraus committed
874
    for(int i = 0; i < 3; i++)
875
        hr_m[i]   = (mymax[i] - mymin[i])/nr_m[i];
gsell's avatar
gsell committed
876 877

    getMesh().set_meshSpacing(&(hr_m[0]));
kraus's avatar
kraus committed
878
    getMesh().set_origin(mymin);
gsell's avatar
gsell committed
879 880 881 882 883 884 885 886 887 888 889

    rho_m.initialize(getMesh(),
                     getFieldLayout(),
                     GuardCellSizes<Dim>(1),
                     bc_m);
    eg_m.initialize(getMesh(),
                    getFieldLayout(),
                    GuardCellSizes<Dim>(1),
                    vbc_m);

    update();
890 891

//    setGridIsFixed();
gsell's avatar
gsell committed
892 893 894 895 896 897 898 899
}

void PartBunch::computeSelfFields() {
    IpplTimings::startTimer(selfFieldTimer_m);
    rho_m = 0.0;
    eg_m = Vector_t(0.0);

    if(fs_m->hasValidSolver()) {
900 901 902
        //mesh the whole domain
        if(fs_m->getFieldSolverType() == "SAAMG")
            resizeMesh();
gsell's avatar
gsell committed
903 904 905 906 907 908 909 910 911 912 913

        //scatter charges onto grid
        this->Q *= this->dt;
        this->Q.scatter(this->rho_m, this->R, IntrplCIC_t());
        this->Q /= this->dt;
        this->rho_m /= getdT();

        //calculating mesh-scale factor
        double gammaz = sum(this->P)[2] / getTotalNum();
        gammaz *= gammaz;
        gammaz = sqrt(gammaz + 1.0);
914 915
        double scaleFactor = 1;
        // double scaleFactor = Physics::c * getdT();
gsell's avatar
gsell committed
916 917 918 919 920 921 922 923 924
        //and get meshspacings in real units [m]
        Vector_t hr_scaled = hr_m * Vector_t(scaleFactor);
        hr_scaled[2] *= gammaz;

        //double tmp2 = 1/hr_m[0] * 1/hr_m[1] * 1/hr_m[2] / (scaleFactor*scaleFactor*scaleFactor) / gammaz;
        double tmp2 = 1 / hr_scaled[0] * 1 / hr_scaled[1] * 1 / hr_scaled[2];
        //divide charge by a 'grid-cube' volume to get [C/m^3]
        rho_m *= tmp2;

925 926 927 928 929
#ifdef DBG_SCALARFIELD
        INFOMSG("*** START DUMPING SCALAR FIELD ***" << endl);
        ofstream fstr1;
        fstr1.precision(9);

930
        std::string SfileName = OpalData::getInstance()->getInputBasename();
931

932
        std::string rho_fn = std::string("data/") + SfileName + std::string("-rho_scalar-") + std::to_string(fieldDBGStep_m);
933 934 935 936 937 938 939 940 941 942 943 944
        fstr1.open(rho_fn.c_str(), ios::out);
        NDIndex<3> myidx1 = getFieldLayout().getLocalNDIndex();
        for(int x = myidx1[0].first(); x <= myidx1[0].last(); x++) {
            for(int y = myidx1[1].first(); y <= myidx1[1].last(); y++) {
                for(int z = myidx1[2].first(); z <= myidx1[2].last(); z++) {
                    fstr1 << x + 1 << " " << y + 1 << " " << z + 1 << " " <<  rho_m[x][y][z].get() << endl;
                }
            }
        }
        fstr1.close();
        INFOMSG("*** FINISHED DUMPING SCALAR FIELD ***" << endl);
#endif
945

gsell's avatar
gsell committed
946
        // charge density is in rho_m
947
        IpplTimings::startTimer(compPotenTimer_m);
948

gsell's avatar
gsell committed
949
        fs_m->solver_m->computePotential(rho_m, hr_scaled);
950

951
        IpplTimings::stopTimer(compPotenTimer_m);
gsell's avatar
gsell committed
952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971

        //do the multiplication of the grid-cube volume coming
        //from the discretization of the convolution integral.
        //this is only necessary for the FFT solver
        //FIXME: later move this scaling into FFTPoissonSolver
        if(fs_m->getFieldSolverType() == "FFT" || fs_m->getFieldSolverType() == "FFTBOX")
            rho_m *= hr_scaled[0] * hr_scaled[1] * hr_scaled[2];

        // the scalar potential is given back in rho_m in units
        // [C/m] = [F*V/m] and must be divided by
        // 4*pi*\epsilon_0 [F/m] resulting in [V]
        rho_m *= getCouplingConstant();

        //write out rho
#ifdef DBG_SCALARFIELD
        INFOMSG("*** START DUMPING SCALAR FIELD ***" << endl);

        ofstream fstr2;
        fstr2.precision(9);

972
        std::string phi_fn = std::string("data/") + SfileName + std::string("-phi_scalar-") + std::to_string(fieldDBGStep_m);
973
        fstr2.open(phi_fn.c_str(), ios::out);
gsell's avatar
gsell committed
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993
        NDIndex<3> myidx = getFieldLayout().getLocalNDIndex();
        for(int x = myidx[0].first(); x <= myidx[0].last(); x++) {
            for(int y = myidx[1].first(); y <= myidx[1].last(); y++) {
                for(int z = myidx[2].first(); z <= myidx[2].last(); z++) {
                    fstr2 << x + 1 << " " << y + 1 << " " << z + 1 << " " <<  rho_m[x][y][z].get() << endl;
                }
            }
        }
        fstr2.close();

        INFOMSG("*** FINISHED DUMPING SCALAR FIELD ***" << endl);
#endif

        // IPPL Grad divides by hr_m [m] resulting in
        // [V/m] for the electric field
        eg_m = -Grad(rho_m, eg_m);

        eg_m *= Vector_t(gammaz / (scaleFactor), gammaz / (scaleFactor), 1.0 / (scaleFactor * gammaz));

        //write out e field
994
#ifdef FIELDSTDOUT
995 996
        // Immediate debug output:
        // Output potential and e-field along the x-, y-, and z-axes
997 998 999 1000 1001 1002
        int mx = (int)nr_m[0];
        int mx2 = (int)nr_m[0] / 2;
        int my = (int)nr_m[1];
        int my2 = (int)nr_m[1] / 2;
        int mz = (int)nr_m[2];
        int mz2 = (int)nr_m[2] / 2;
1003

1004
        for (int i=0; i<mx; i++ )
1005
            *gmsg << "Field along x axis Ex = " << eg_m[i][my2][mz2] << " Pot = " << rho_m[i][my2][mz2]  << endl;
1006

1007
        for (int i=0; i<my; i++ )
1008
            *gmsg << "Field along y axis Ey = " << eg_m[mx2][i][mz2] << " Pot = " << rho_m[mx2][i][mz2]  << endl;
1009

1010
        for (int i=0; i<mz; i++ )
1011
            *gmsg << "Field along z axis Ez = " << eg_m[mx2][my2][i] << " Pot = " << rho_m[mx2][my2][i]  << endl;
1012
#endif
1013

1014
#ifdef DBG_SCALARFIELD
gsell's avatar
gsell committed
1015 1016 1017 1018 1019
        INFOMSG("*** START DUMPING E FIELD ***" << endl);
        //ostringstream oss;
        //MPI_File file;
        //MPI_Status status;
        //MPI_Info fileinfo;
1020
        //MPI_File_open(Ippl::getComm(), "rho_scalar", MPI_MODE_WRONLY | MPI_MODE_CREATE, fileinfo, &file);
gsell's avatar
gsell committed
1021 1022 1023
        ofstream fstr;
        fstr.precision(9);

1024
        std::string e_field = std::string("data/") + SfileName + std::string("-e_field-") + std::to_string(fieldDBGStep_m);
gsell's avatar
gsell committed
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
        fstr.open(e_field.c_str(), ios::out);
        NDIndex<3> myidxx = getFieldLayout().getLocalNDIndex();
        for(int x = myidxx[0].first(); x <= myidxx[0].last(); x++) {
            for(int y = myidxx[1].first(); y <= myidxx[1].last(); y++) {
                for(int z = myidxx[2].first(); z <= myidxx[2].last(); z++) {
                    fstr << x + 1 << " " << y + 1 << " " << z + 1 << " " <<  eg_m[x][y][z].get() << endl;
                }
            }
        }

        fstr.close();
        fieldDBGStep_m++;

        //MPI_File_write_shared(file, (char*)oss.str().c_str(), oss.str().length(), MPI_CHAR, &status);
        //MPI_File_close(&file);

        INFOMSG("*** FINISHED DUMPING E FIELD ***" << endl);
#endif

        // interpolate electric field at particle positions.  We reuse the
        // cached information about where the particles are relative to the
        // field, since the particles have not moved since this the most recent
        // scatter operation.
        Ef.gather(eg_m, this->R,  IntrplCIC_t());

        /** Magnetic field in x and y direction induced by the eletric field
         *
         *  \f[ B_x = \gamma(B_x^{'} - \frac{beta}{c}E_y^{'}) = -\gamma \frac{beta}{c}E_y^{'} = -\frac{beta}{c}E_y \f]
         *  \f[ B_y = \gamma(B_y^{'} - \frac{beta}{c}E_x^{'}) = +\gamma \frac{beta}{c}E_x^{'} = +\frac{beta}{c}E_x \f]
         *  \f[ B_z = B_z^{'} = 0 \f]
         *
         */
        double betaC = sqrt(gammaz * gammaz - 1.0) / gammaz / Physics::c;

        Bf(0) = Bf(0) - betaC * Ef(1);
        Bf(1) = Bf(1) + betaC * Ef(0);
    }
    IpplTimings::stopTimer(selfFieldTimer_m);
}

1065 1066 1067 1068 1069 1070 1071 1072 1073
/**
 * \method computeSelfFields_cycl()
 * \brief Calculates the self electric field from the charge density distribution for use in cyclotrons
 * \see ParallelCyclotronTracker
 * \warning none yet
 *
 * Comments -DW:
 * I have made some changes in here:
 * -) Some refacturing to make more similar to computeSelfFields()
1074
 * -) Added meanR and quaternion to be handed to the function so that SAAMG solver knows how to rotate the boundary geometry correctly.
1075 1076 1077
 * -) Fixed an error where gamma was not taken into account correctly in direction of movement (y in cyclotron)
 * -) Comment: There is no account for image charges in the cyclotron tracker (yet?)!
 */
1078
void PartBunch::computeSelfFields_cycl(double gamma) {
1079

1080 1081 1082 1083 1084 1085 1086 1087
    IpplTimings::startTimer(selfFieldTimer_m);

    /// set initial charge density to zero.
    rho_m = 0.0;

    /// set initial E field to zero
    eg_m = Vector_t(0.0);

kraus's avatar
kraus committed
1088
    if(fs_m->hasValidSolver()) {
1089 1090 1091
        /// mesh the whole domain
        if(fs_m->getFieldSolverType() == "SAAMG")
            resizeMesh();
1092

1093 1094 1095 1096
        /// scatter particles charge onto grid.
        this->Q.scatter(this->rho_m, this->R, IntrplCIC_t());

        /// Lorentz transformation
1097
        /// In particle rest frame, the longitudinal length (y for cyclotron) enlarged
1098 1099 1100
        Vector_t hr_scaled = hr_m ;
        hr_scaled[1] *= gamma;

1101 1102 1103 1104 1105
        /// from charge (C) to charge density (C/m^3).
        double tmp2 = 1.0 / (hr_scaled[0] * hr_scaled[1] * hr_scaled[2]);
        rho_m *= tmp2;

        // If debug flag is set, dump scalar field (charge density 'rho') into file under ./data/
1106 1107 1108 1109 1110
#ifdef DBG_SCALARFIELD
        INFOMSG("*** START DUMPING SCALAR FIELD ***" << endl);
        ofstream fstr1;
        fstr1.precision(9);

1111 1112 1113
        std::ostringstream istr;
        istr << fieldDBGStep_m;

1114
        std::string SfileName = OpalData::getInstance()->getInputBasename();
1115

1116
        std::string rho_fn = std::string("data/") + SfileName + std::string("-rho_scalar-") + std::string(istr.str());
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
        fstr1.open(rho_fn.c_str(), ios::out);
        NDIndex<3> myidx1 = getFieldLayout().getLocalNDIndex();
        for(int x = myidx1[0].first(); x <= myidx1[0].last(); x++) {
            for(int y = myidx1[1].first(); y <= myidx1[1].last(); y++) {
                for(int z = myidx1[2].first(); z <= myidx1[2].last(); z++) {
                    fstr1 << x + 1 << " " << y + 1 << " " << z + 1 << " " <<  rho_m[x][y][z].get() << endl;
                }
            }
        }
        fstr1.close();
        INFOMSG("*** FINISHED DUMPING SCALAR FIELD ***" << endl);
#endif
1129

1130
        /// now charge density is in rho_m
kraus's avatar
kraus committed
1131
        /// calculate Possion equation (without coefficient: -1/(eps))
1132
        IpplTimings::startTimer(compPotenTimer_m);
1133

1134
        fs_m->solver_m->computePotential(rho_m, hr_scaled);