Distribution.cpp 124 KB
Newer Older
gsell's avatar
gsell committed
1 2 3 4 5 6 7 8 9 10 11 12
// ------------------------------------------------------------------------
// $RCSfile: Distribution.cpp,v $
// ------------------------------------------------------------------------
// $Revision: 1.3.4.1 $
// ------------------------------------------------------------------------
// Copyright: see Copyright.readme
// ------------------------------------------------------------------------
//
// Class: Distribution
//   The class for the OPAL Distribution command.
//
// ------------------------------------------------------------------------
13 14 15 16 17 18 19 20 21 22
#include "Distribution/Distribution.h"
#include "AbstractObjects/Expressions.h"
#include "Attributes/Attributes.h"
#include "Utilities/Options.h"
#include "halton1d_sequence.hh"
#include "AbstractObjects/OpalData.h"
#include "Algorithms/PartBunch.h"
#include "Algorithms/PartBins.h"
#include "Algorithms/bet/EnvelopeBunch.h"
#include "Structure/BoundaryGeometry.h"
gsell's avatar
gsell committed
23 24 25
#include "Algorithms/PartBinsCyc.h"
#include "BasicActions/Option.h"
#include "Distribution/LaserProfile.h"
26 27 28 29

#include <gsl/gsl_cdf.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_sf_erf.h>
gsell's avatar
gsell committed
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61

#include <cmath>
#include <cfloat>
#include <iomanip>   // Needed for I/O manipulators
#include <iostream>  // Neeeded for stream I/O
#include <string>
#include <vector>

using namespace std;
using namespace Expressions;
using namespace Physics;
using namespace Attributes;

extern Inform *gmsg;

//
// Class Distribution
// ------------------------------------------------------------------------

// The attributes of class Distribution.

namespace {
    enum {
        // DESCRIPTION OF THE DISTRIBUTION:
        DISTRIBUTION,
        FNAME,
        LASERPROFFN,
        IMAGENAME,
        INTENSITYCUT,
        XMULT,
        YMULT,
        TMULT,
62
        ZMULT,
gsell's avatar
gsell committed
63 64 65
        PXMULT,
        PYMULT,
        PTMULT,
66
        PZMULT,
gsell's avatar
gsell committed
67 68 69 70 71 72 73
        BETAX,
        BETAY,
        ALPHAX,
        ALPHAY,
        MX,
        MY,
        MT,
74
        MZ,
gsell's avatar
gsell committed
75 76 77 78 79 80 81 82 83
        DX,
        DDX,
        DY,
        DDY,
        R51,
        R52,
        R61,
        R62,
        PT,
84
        PZ,
gsell's avatar
gsell committed
85
        T,
86
        Z,
gsell's avatar
gsell committed
87 88 89
        SIGMAX,
        SIGMAY,
        SIGMAT,
90
        SIGMAZ,
gsell's avatar
gsell committed
91 92 93 94
        TRANSVCUTOFF,
        SIGMAPX,
        SIGMAPY,
        SIGMAPT,
95
        SIGMAPZ,
gsell's avatar
gsell committed
96 97 98 99 100 101 102 103 104 105
        TRISE,
        TFALL,
        CUTOFF,
        TPULSEFWHM,
        FTOSCAMPLITUDE,
        FTOSCPERIODS,
        WEIGHT,
        CORRX,
        CORRY,
        CORRT,
106
        CORRZ,
gsell's avatar
gsell committed
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
        OFFSETX,
        OFFSETY,
        TEMISSION,
        NBIN,
        SBIN,
        DEBIN,
        ELASER,
        SIGLASER,
        W,
        FE,
        AG,
        EKIN,
        NPDARKCUR,
        EINITHR,
        INWARDMARGIN,
        FNA,
        FNB,
        FNY,
        FNVYZERO,
        FNVYSECOND,
        FNPHIW,
        FNBETA,
        FNFIELDTHR,
        FNMAXEMI,
        SECONDARYFLAG,
        NEMISSIONMODE,
        VSEYZERO,// sey_0 in Vaughan's model
        VEZERO,// energy related to sey_0 in Vaughan's model
        VSEYMAX,// sey max in Vaughan's model
        VEMAX,// Emax in Vaughan's model
        VKENERGY,// fitting parameter denotes the roughness of surface for impact energy in Vaughan's model
        VKTHETA,// fitting parameter denotes the roughness of surface for impact angle in Vaughan's model
        VVTHERMAL,// thermal velocity of Maxwellian distribution of secondaries in Vaughan's model
        VW,
        SURFMATERIAL, // Add material type, currently 0 for copper and 1 for stainless steel.
        SIZE
    };
}

/**
 * Constructor
 *
 */
Distribution::Distribution():
    Definition(SIZE, "DISTRIBUTION", "The DISTRIBUTION statement defines data for the 6D particle distr."),
    distrTypeT_m(NODIST),
    rn_m(NULL),
    R_m(NULL),
    qrng_m(NULL),
    distributionTable_m(NULL) {
adelmann's avatar
cleanup  
adelmann committed
157 158
    itsAttr[DISTRIBUTION] = makeString("DISTRIBUTION", "Distribution type: GAUSS, BINOMIAL, FROMFILE,"
                                       "GUNGAUSSFLATTOPTH, ASTRAFLATTOPTH, SURFACEEMISSION, SURFACERANDCREATE", "GAUSS");
gsell's avatar
gsell committed
159 160 161 162 163 164 165 166 167 168 169

    itsAttr[FNAME] = makeString("FNAME", "File for reading in 6D particle coordinates");

    itsAttr[LASERPROFFN] = makeString("LASERPROFFN", "File for read in a measured laser profile (x,y)", "");
    itsAttr[IMAGENAME] = makeString("IMAGENAME", "Name of the image");
    itsAttr[INTENSITYCUT] = makeReal("INTENSITYCUT", "For background substraction, in % of max intensity", 0.0);


    itsAttr[XMULT] = makeReal("XMULT", "Multiplier for X", 1.0);
    itsAttr[YMULT] = makeReal("YMULT", "Multiplier for Y", 1.0);
    itsAttr[TMULT] = makeReal("TMULT", "Multiplier for T", 1.0);
170
    itsAttr[ZMULT] = makeReal("TMULT", "Multiplier for T", -99.0);
171
    itsAttr[TRANSVCUTOFF] = makeReal("TRANSVCUTOFF", "Transverse cut-off in units of sigma", -3.0);
gsell's avatar
gsell committed
172 173 174 175

    itsAttr[PXMULT] = makeReal("PXMULT", "Multiplier for PX", 1.0);
    itsAttr[PYMULT] = makeReal("PYMULT", "Multiplier for PY", 1.0);
    itsAttr[PTMULT] = makeReal("PTMULT", "Multiplier for PT", 1.0);
176
    itsAttr[PZMULT] = makeReal("PZMULT", "Multiplier for PZ", -99.0);
gsell's avatar
gsell committed
177 178 179 180 181 182 183 184 185 186

    itsAttr[ALPHAX] = makeReal("ALPHAX", "Courant Synder parameter", 1.0);
    itsAttr[ALPHAY] = makeReal("ALPHAY", "Courant Synder parameter", 1.0);

    itsAttr[BETAX] = makeReal("BETAX", "Courant Synder parameter", -1.0);
    itsAttr[BETAY] = makeReal("BETAY", "Courant Synder parameter", 1.0);

    itsAttr[MX]    = makeReal("MX", "Defines the distribution in x, 0+eps .. inf", 1.0);
    itsAttr[MY]    = makeReal("MY", "Defines the distribution in y, 0+eps .. inf", 1.0);
    itsAttr[MT]    = makeReal("MT", "Defines the distribution in t, 0+eps .. inf", 1.0);
187
    itsAttr[MZ]    = makeReal("MZ", "Defines the distribution in z, 0+eps .. inf", -99.0);
gsell's avatar
gsell committed
188 189 190 191 192 193 194 195 196 197 198 199 200 201

    itsAttr[DX]    = makeReal("DX", "Dispersion in x (R16 in Transport notation)", 0.0);
    itsAttr[DDX]   = makeReal("DDX", "First derivative of Dx", 0.0);

    itsAttr[DY]    = makeReal("DY", "DY", 0.0);
    itsAttr[DDY]   = makeReal("DDY", "DDY", 0.0);

    itsAttr[R51]    = makeReal("R51", "R51", 0.0);
    itsAttr[R52]   = makeReal("R52", "R52", 0.0);

    itsAttr[R61]    = makeReal("R61", "R61", 0.0);
    itsAttr[R62]   = makeReal("R62", "R62", 0.0);

    itsAttr[PT] = makeReal("PT", "average longitudinal momentum", 0.0);
202
    itsAttr[PZ] = makeReal("PZ", "average longitudinal momentum", -99.0);
gsell's avatar
gsell committed
203
    itsAttr[T] = makeReal("T", "average longitudinal position", 0.0);
204
    itsAttr[Z] = makeReal("Z", "average longitudinal position", -99.0);
gsell's avatar
gsell committed
205 206 207 208

    itsAttr[SIGMAX] = makeReal("SIGMAX", "SIGMAx (m)", 1.0e-2);
    itsAttr[SIGMAY] = makeReal("SIGMAY", "SIGMAy (m)", 1.0e-2);
    itsAttr[SIGMAT] = makeReal("SIGMAT", "SIGMAt (m)", 1.0e-2);
209
    itsAttr[SIGMAZ] = makeReal("SIGMAZ", "SIGMAz (m)", -99.0);
gsell's avatar
gsell committed
210 211 212 213

    itsAttr[SIGMAPX] = makeReal("SIGMAPX", "SIGMApx", 0.0);
    itsAttr[SIGMAPY] = makeReal("SIGMAPY", "SIGMApy", 0.0);
    itsAttr[SIGMAPT] = makeReal("SIGMAPT", "SIGMApt", 0.0);
214
    itsAttr[SIGMAPZ] = makeReal("SIGMAPZ", "SIGMApz", -99.0);
gsell's avatar
gsell committed
215 216 217 218

    itsAttr[CORRX] = makeReal("CORRX", "CORRx", -0.5);
    itsAttr[CORRY] = makeReal("CORRY", "CORRy", 0.5);
    itsAttr[CORRT] = makeReal("CORRT", "CORRt", 0.0);
219
    itsAttr[CORRZ] = makeReal("CORRZ", "CORRz", -99.0);
gsell's avatar
gsell committed
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309

    itsAttr[OFFSETX] = makeReal("OFFSETX", "OFFSETx", 0.0);
    itsAttr[OFFSETY] = makeReal("OFFSETY", "OFFSETy", 0.0);

    itsAttr[TEMISSION] = makeReal("TEMISSION", "Time in seconds in which we have emission",  0.0);
    itsAttr[NBIN]      = makeReal("NBIN", "In case of emission how many energy bins should we use", 0.0);
    itsAttr[SBIN]      = makeReal("SBIN", "In case of emission how many sample bins an energy bin should use", 100.0);
    itsAttr[DEBIN]     = makeReal("DEBIN", "Energy band for a bin in keV, defines the rebinning", 1000000.0);

    itsAttr[TPULSEFWHM]  = makeReal("TPULSEFWHM", "Pulse FWHM (s)", 0.0);
    itsAttr[TRISE]       = makeReal("TRISE", "Rise time for GUNGAUSSFLATTOP distribution type (s)", 0.0);
    itsAttr[TFALL]       = makeReal("TFALL", "Fall time for GUNGAUSSFLATTOP distribution type (s)", 0.0);
    itsAttr[CUTOFF]      = makeReal("CUTOFF", "Cutoff for GUNGAUSSFLATTOP distribution type in sigmas", 3.0);

    itsAttr[FTOSCAMPLITUDE] = makeReal("FTOSCAMPLITUDE", "Amplitude of oscillations superimposed on flat top portion of GUNGAUSSFLATTOPTH distribtuion (in percent of flat top amplitude)", 0.0);
    itsAttr[FTOSCPERIODS]    = makeReal("FTOSCPERIODS", "Number of oscillations superimposed on flat top portion of GUNGAUSSFLATTOPTH distribution", 0.0);

    itsAttr[WEIGHT] = makeReal("WEIGHT", "Weight of this distribution when used in a distribution list.", 1.0);

    itsAttr[ELASER] = makeReal("ELASER", "Laser energy (eV)", 0.0);
    itsAttr[SIGLASER] = makeReal("SIGLASER", "Sigma of (uniform) laser spot size (m)", 0.0);
    itsAttr[W] = makeReal("W", "Workfunction of material (eV)", 0.0);
    itsAttr[FE] = makeReal("FE", "Fermi energy (eV)", 0.0);
    itsAttr[AG] = makeReal("AG", "Acceleration Gradient (MV/m)", 0.0);

    itsAttr[EKIN] = makeReal("EKIN", "Ekin used in ASTRA (eV)", -1.0);

    itsAttr[NPDARKCUR] = makeReal("NPDARKCUR", "Number of dark current particles", 1000.0);
    itsAttr[INWARDMARGIN] = makeReal("INWARDMARGIN", "Inward margin of initialized dark current particle positions", 0.001);
    itsAttr[EINITHR] = makeReal("EINITHR", "E field threshold (MV), only in position r with E(r)>EINITHR that particles will be initialized", 0.0);
    itsAttr[FNA] = makeReal("FNA", "Empirical constant A for Fowler-Nordheim emission model", 1.54e-6);
    itsAttr[FNB] = makeReal("FNB", "Empirical constant B for Fowler-Nordheim emission model", 6.83e9);
    itsAttr[FNY] = makeReal("FNY", "Constant for image charge effect parameter y(E) in Fowler-Nordheim emission model", 3.795e-5);
    itsAttr[FNVYZERO] = makeReal("FNVYZERO", "Zero order constant for v(y) function in Fowler-Nordheim emission model", 0.9632);
    itsAttr[FNVYSECOND] = makeReal("FNVYSECOND", "Second order constant for v(y) function in Fowler-Nordheim emission model", 1.065);
    itsAttr[FNPHIW] = makeReal("FNPHIW", "Work function of gun surface material (eV)", 4.65);
    itsAttr[FNBETA] = makeReal("FNBETA", "Field enhancement factor for Fowler-Nordheim emission", 50.0);
    itsAttr[FNFIELDTHR] = makeReal("FNFIELDTHR", "Field threshold for Fowler-Nordheim emission (MV/m)", 30.0);
    itsAttr[FNMAXEMI] = makeReal("FNMAXEMI", "Maximum number of electrons emitted from a single triangle for Fowler-Nordheim emission", 20.0);
    itsAttr[SECONDARYFLAG] = makeReal("SECONDARYFLAG", "Select the secondary model type(0:no secondary emission; 1:Furman-Pivi; 2 or larger: Vaughan's model", 0);
    itsAttr[NEMISSIONMODE] = makeBool("NEMISSIONMODE", "Secondary emission mode type(true: emit n true secondaries; false: emit one particle with n times charge", true);
    itsAttr[VSEYZERO] = makeReal("VSEYZERO", "Sey_0 in Vaughan's model", 0.5);
    itsAttr[VEZERO] = makeReal("VEZERO", "Energy related to sey_0 in Vaughan's model in eV", 12.5);
    itsAttr[VSEYMAX] = makeReal("VSEYMAX", "Sey max in Vaughan's model", 2.22);
    itsAttr[VEMAX] = makeReal("VEMAX", "Emax in Vaughan's model in eV", 165);
    itsAttr[VKENERGY] = makeReal("VKENERGY", "Fitting parameter denotes the roughness of surface for impact energy in Vaughan's model", 1.0);
    itsAttr[VKTHETA] = makeReal("VKTHETA", "Fitting parameter denotes the roughness of surface for impact angle in Vaughan's model", 1.0);
    itsAttr[VVTHERMAL] = makeReal("VVTHERMAL", "Thermal velocity of Maxwellian distribution of secondaries in Vaughan's model", 7.268929821 * 1e5); // electrons 1.5eV default
    itsAttr[VW] = makeReal("VW", "VW denote the velocity scalar for Parallel plate benchmark", 1.0);
    itsAttr[SURFMATERIAL] = makeReal("SURFMATERIAL", "Material type number of the cavity surface for Furman-Pivi's model, 0 for copper, 1 for stainless steel", 0);

    // Set up default beam.
    Distribution *defDistribution = clone("UNNAMED_Distribution");
    defDistribution->builtin = true;

    try {
        defDistribution->update();
        OpalData::getInstance()->define(defDistribution);
    } catch(...) {
        delete defDistribution;
    }
    pbin_m = NULL;
    lp_m = NULL;

    darkCurrentParts_m = (size_t) Attributes::getReal(itsAttr[NPDARKCUR]);
    darkInwardMargin_m = Attributes::getReal(itsAttr[INWARDMARGIN]);
    eInitThreshold_m = Attributes::getReal(itsAttr[EINITHR]);

    workFunction_m = Attributes::getReal(itsAttr[FNPHIW]);
    fieldEnhancement_m = Attributes::getReal(itsAttr[FNBETA]);
    maxFN_m = (size_t) Attributes::getReal(itsAttr[FNMAXEMI]);
    fieldThrFN_m = Attributes::getReal(itsAttr[FNFIELDTHR]);
    paraFNA_m = Attributes::getReal(itsAttr[FNA]);
    paraFNB_m = Attributes::getReal(itsAttr[FNB]);
    paraFNY_m = Attributes::getReal(itsAttr[FNY]);
    paraFNVYZe_m = Attributes::getReal(itsAttr[FNVYZERO]);
    paraFNVYSe_m = Attributes::getReal(itsAttr[FNVYSECOND]);

    secondaryFlag_m = Attributes::getReal(itsAttr[SECONDARYFLAG]);
    ppVw_m = Attributes::getReal(itsAttr[VW]);
    vVThermal_m = Attributes::getReal(itsAttr[VVTHERMAL]);
    tEmission_m = -1.0;
    qrng_m = NULL;
}
/**
 *
 *
 * @param name
 * @param parent
 */
310
Distribution::Distribution(const std::string &name, Distribution *parent):
gsell's avatar
gsell committed
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
    Definition(name, parent),
    reference(parent->reference),
    pbin_m(NULL),
    distrTypeT_m(NODIST),
    rn_m(parent->rn_m),
    R_m(parent->R_m),
    qrng_m(parent->qrng_m),
    tEmission_m(parent->tEmission_m),
    distributionTable_m(parent->distributionTable_m),
    lp_m(NULL),
    darkCurrentParts_m(parent->darkCurrentParts_m),
    darkInwardMargin_m(parent->darkInwardMargin_m),
    eInitThreshold_m(parent->eInitThreshold_m),
    workFunction_m(parent->workFunction_m),
    fieldEnhancement_m(parent->fieldEnhancement_m),
    fieldThrFN_m(parent->fieldThrFN_m),
    maxFN_m(parent->maxFN_m),
    paraFNA_m(parent-> paraFNA_m),
    paraFNB_m(parent-> paraFNB_m),
    paraFNY_m(parent-> paraFNY_m),
    paraFNVYSe_m(parent-> paraFNVYSe_m),
    paraFNVYZe_m(parent-> paraFNVYZe_m),
    secondaryFlag_m(parent->secondaryFlag_m) {

    darkCurrentParts_m = (size_t) Attributes::getReal(itsAttr[NPDARKCUR]);
    darkInwardMargin_m = Attributes::getReal(itsAttr[INWARDMARGIN]);
    eInitThreshold_m = Attributes::getReal(itsAttr[EINITHR]);

    workFunction_m = Attributes::getReal(itsAttr[FNPHIW]);
    fieldEnhancement_m = Attributes::getReal(itsAttr[FNBETA]);
    maxFN_m = (size_t) Attributes::getReal(itsAttr[FNMAXEMI]);
    fieldThrFN_m = Attributes::getReal(itsAttr[FNFIELDTHR]);
    paraFNA_m = Attributes::getReal(itsAttr[FNA]);
    paraFNB_m = Attributes::getReal(itsAttr[FNB]);
    paraFNY_m = Attributes::getReal(itsAttr[FNY]);
    paraFNVYZe_m = Attributes::getReal(itsAttr[FNVYZERO]);
    paraFNVYSe_m = Attributes::getReal(itsAttr[FNVYSECOND]);

    secondaryFlag_m = Attributes::getReal(itsAttr[SECONDARYFLAG]);
    ppVw_m = Attributes::getReal(itsAttr[VW]);
    vVThermal_m = Attributes::getReal(itsAttr[VVTHERMAL]);
}

/**
 * Destructor
 *
 */
Distribution::~Distribution() {
    if(pbin_m) {
        delete pbin_m;
        pbin_m = NULL;
    }

    if((Ippl::getNodes() == 1) && (os_m.is_open()))
        os_m.close();

    if(lp_m) {
        delete lp_m;
        lp_m = NULL;
    }

    if(distributionTable_m)
        delete[] distributionTable_m;

    if(rn_m) {
        gsl_rng_free(rn_m);
        gsl_qrng_free(R_m);
    }
    if(qrng_m)
        gsl_qrng_free(qrng_m);
}

/**
384 385
 * At the moment only write the header into the file dist.dat
 * PartBunch will then append (very uggly)
386 387 388
 * @param
 * @param
 * @param
389 390 391 392
 */
void Distribution::writeToFile() {

    if(Ippl::getNodes() == 1) {
393
        if(os_m.is_open()) {
394
            ;
395
        } else {
396
            *gmsg << " Write distribution to file dist.dat" << endl;
397
            std::string file("data/dist.dat");
398 399 400 401 402 403 404 405 406 407 408 409 410
            os_m.open(file.c_str());
            if(os_m.bad()) {
                *gmsg << "Unable to open output file " <<  file << endl;
            }
            os_m << "# x y ti px py pz Ekin= " << ekin_m << " [eV] " << endl;
            os_m.close();
        }
    }
}

/**
 * This is the main entrypoint, called from PartBunch::setDistribution
 * The envelope trackes is doing it differently by calling createSliceBunch
gsell's avatar
gsell committed
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
 * @param beam
 * @param Np
 * @param scan
 */
void Distribution::setup(PartBunch &beam, size_t Np, bool scan) {

    scan_m = scan;
    nBins_m = static_cast<int>(fabs(Attributes::getReal(itsAttr[NBIN])));

    bool isBinned = (nBins_m > 0);

    if(isBinned) {
        if(pbin_m)
            delete pbin_m;
        pbin_m = new PartBins(static_cast<int>(fabs(Attributes::getReal(itsAttr[NBIN]))),
                              static_cast<int>(fabs(Attributes::getReal(itsAttr[SBIN]))));
    } else
        pbin_m = NULL;

    if(scan_m) {
        beam.destroy(beam.getLocalNum(), 0);
        beam.update();
        INFOMSG("In scan mode: delete all particles in the bunch" << endl;);
    }

    laserProfileFn_m = Attributes::getString(itsAttr[LASERPROFFN]);

438
    if(!(laserProfileFn_m == std::string(""))) {
gsell's avatar
gsell committed
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
        laserImage_m  = Attributes::getString(itsAttr[IMAGENAME]);
        intensityCut_m = Attributes::getReal(itsAttr[INTENSITYCUT]);
        lp_m = new LaserProfile(laserProfileFn_m, laserImage_m, intensityCut_m);
    }

    beam.setTEmission(Attributes::getReal(itsAttr[TEMISSION]));
    beam.setNumBunch(1);

    distT_m = Attributes::getString(itsAttr[DISTRIBUTION]);
    if(distT_m == "GAUSS")
        distrTypeT_m = GAUSS;
    else if(distT_m == "GUNGAUSSFLATTOPTH")
        distrTypeT_m = GUNGAUSSFLATTOPTH;
    else if(distT_m == "ASTRAFLATTOPTH")
        distrTypeT_m = ASTRAFLATTOPTH;
    else if(distT_m == "FROMFILE")
        distrTypeT_m = FROMFILE;
    else if(distT_m == "BINOMIAL")
        distrTypeT_m = BINOMIAL;
    else if(distT_m == "SURFACEEMISSION")
        distrTypeT_m = SURFACEEMISSION;
    else if(distT_m == "SURFACERANDCREATE")
        distrTypeT_m = SURFACERANDCREATE;

adelmann's avatar
adelmann committed
463 464 465
    /*
      Setup some common data:
    */
466
    if(distrTypeT_m == GUNGAUSSFLATTOPTH || distrTypeT_m == ASTRAFLATTOPTH) {
adelmann's avatar
adelmann committed
467 468 469 470 471 472 473
        corr_m[0] = Attributes::getReal(itsAttr[CORRX]);
        corr_m[1] = Attributes::getReal(itsAttr[CORRY]);
        corr_m[2] = Attributes::getReal(itsAttr[CORRT]);

        nBins_m = static_cast<int>(fabs(Attributes::getReal(itsAttr[NBIN])));
        sBins_m = static_cast<int>(fabs(Attributes::getReal(itsAttr[SBIN])));
        transvCutOff_m = Attributes::getReal(itsAttr[TRANSVCUTOFF]);
474

adelmann's avatar
adelmann committed
475 476 477
        sigx_m = Vector_t(Attributes::getReal(itsAttr[SIGMAX]),
                          Attributes::getReal(itsAttr[SIGMAY]),
                          Attributes::getReal(itsAttr[SIGMAT]));
478

adelmann's avatar
adelmann committed
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
        sigp_m = Vector_t(eVtoBetaGamma(Attributes::getReal(itsAttr[SIGMAPX]), beam.getM()),
                          eVtoBetaGamma(Attributes::getReal(itsAttr[SIGMAPY]), beam.getM()),
                          eVtoBetaGamma(Attributes::getReal(itsAttr[SIGMAPT]), beam.getM()));

        tPulseLengthFWHM_m = Attributes::getReal(itsAttr[TPULSEFWHM]);
        cutoff_m = Attributes::getReal(itsAttr[CUTOFF]);
        tRise_m = Attributes::getReal(itsAttr[TRISE]);
        tFall_m = Attributes::getReal(itsAttr[TFALL]);
        double tratio = sqrt(2.0 * log(10.0)) - sqrt(2.0 * log(10.0 / 9.0));
        sigmaRise_m = tRise_m / tratio;
        sigmaFall_m = tFall_m / tratio;

        double dEBins = Attributes::getReal(itsAttr[DEBIN]);

        pbin_m->setRebinEnergy(dEBins);

        /*
          prepare quantities for thermal emittance calculation
        */
        workf_m = 0.0;         // eV
        siglaser_m = 0.0;      // m
        elaser_m = 0.0;        // eV
        fe_m = 0.0;            // Fermi energy eV
        ag_m = 0.0;            // Acceleration gradient eV/m
        ekin_m = 0.0;          // eV
        phimax_m = 0.0;        // rad
        schottky_m = 0.0;      // eV
        ptot_m = 0.0;          // beta gamma

        ekin_m = Attributes::getReal(itsAttr[EKIN]);
        ptot_m = eVtoBetaGamma(ekin_m, beam.getM());
    }

512
    if(distrTypeT_m == BINOMIAL || distrTypeT_m == GAUSS) {
adelmann's avatar
adelmann committed
513 514 515 516 517 518 519 520 521 522 523 524 525 526

        corr_m[0] = Attributes::getReal(itsAttr[CORRX]);
        corr_m[1] = Attributes::getReal(itsAttr[CORRY]);
        corr_m[2] = Attributes::getReal(itsAttr[CORRT]);
        corr_m[3] = Attributes::getReal(itsAttr[R61]);
        corr_m[4] = Attributes::getReal(itsAttr[R62]);
        corr_m[5] = Attributes::getReal(itsAttr[R51]);
        corr_m[6] = Attributes::getReal(itsAttr[R52]);
        gauss_offset_m[0] = Attributes::getReal(itsAttr[OFFSETX]);
        gauss_offset_m[1] = Attributes::getReal(itsAttr[OFFSETY]);

        sigx_m = Vector_t(Attributes::getReal(itsAttr[SIGMAX]),
                          Attributes::getReal(itsAttr[SIGMAY]),
                          Attributes::getReal(itsAttr[SIGMAT]));
527

adelmann's avatar
adelmann committed
528 529 530 531 532 533 534 535 536
        sigp_m = Vector_t(eVtoBetaGamma(Attributes::getReal(itsAttr[SIGMAPX]), beam.getM()),
                          eVtoBetaGamma(Attributes::getReal(itsAttr[SIGMAPY]), beam.getM()),
                          eVtoBetaGamma(Attributes::getReal(itsAttr[SIGMAPT]), beam.getM()));

        binc_m = Vector_t(Attributes::getReal(itsAttr[MX]),
                          Attributes::getReal(itsAttr[MY]),
                          Attributes::getReal(itsAttr[MT]));
    }

gsell's avatar
gsell committed
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
    switch(distrTypeT_m) {
        case SURFACERANDCREATE: {
            darkCurrentParts_m = (size_t) Attributes::getReal(itsAttr[NPDARKCUR]);
            darkInwardMargin_m = Attributes::getReal(itsAttr[INWARDMARGIN]);
            //ppVw_m = Attributes::getReal(itsAttr[VW]);
            //vVThermal_m = Attributes::getReal(itsAttr[VVTHERMAL]);
        }
        break;
        case SURFACEEMISSION: {
            darkCurrentParts_m = (size_t) Attributes::getReal(itsAttr[NPDARKCUR]);
            darkInwardMargin_m = Attributes::getReal(itsAttr[INWARDMARGIN]);
            eInitThreshold_m = Attributes::getReal(itsAttr[EINITHR]);

            workFunction_m = Attributes::getReal(itsAttr[FNPHIW]);
            fieldEnhancement_m = Attributes::getReal(itsAttr[FNBETA]);
            maxFN_m = (size_t) Attributes::getReal(itsAttr[FNMAXEMI]);
            fieldThrFN_m = Attributes::getReal(itsAttr[FNFIELDTHR]);
            paraFNA_m = Attributes::getReal(itsAttr[FNA]);
            paraFNB_m = Attributes::getReal(itsAttr[FNB]);
            paraFNY_m = Attributes::getReal(itsAttr[FNY]);
            paraFNVYZe_m = Attributes::getReal(itsAttr[FNVYZERO]);
            paraFNVYSe_m = Attributes::getReal(itsAttr[FNVYSECOND]);

            secondaryFlag_m = Attributes::getReal(itsAttr[SECONDARYFLAG]);

        }
        break;
        case ASTRAFLATTOPTH: {

566
            if(Options::rngtype != std::string("RANDOM")) {
gsell's avatar
gsell committed
567
                INFOMSG("RNGTYPE= " << Options::rngtype << endl);
568
                if(Options::rngtype == std::string("HALTON"))
gsell's avatar
gsell committed
569
                    qrng_m = gsl_qrng_alloc(gsl_qrng_halton, 2);
570
                else if(Options::rngtype == std::string("SOBOL"))
gsell's avatar
gsell committed
571
                    qrng_m = gsl_qrng_alloc(gsl_qrng_sobol, 2);
572
                else if(Options::rngtype == std::string("NIEDERREITER"))
gsell's avatar
gsell committed
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
                    qrng_m = gsl_qrng_alloc(gsl_qrng_niederreiter_2, 2);
                else {
                    INFOMSG("RNGTYPE= " << Options::rngtype << " not known, using HALTON" << endl);
                    qrng_m = gsl_qrng_alloc(gsl_qrng_halton, 2);
                }
            }

            rGen_m = new RANLIB_class(265314159, 4);

            gsl_rng_env_setup();
            rn_m = gsl_rng_alloc(gsl_rng_1dhalton);
            R_m = gsl_qrng_alloc(gsl_qrng_halton, 2);
            int binTotal = sBins_m * nBins_m;

            h_m = gsl_histogram_alloc(binTotal);
            distributionTable_m = new double[binTotal + 1];

            double a = tPulseLengthFWHM_m / 2.;
            double sig = tRise_m / 2.;
            double inv_erf08 = 0.906193802436823; // erfinv(0.8)
            double sqr2 = sqrt(2.);
            double t = a - sqr2 * sig * inv_erf08;
            double tmps = sig;
            double tmpt = t;
            for(int i = 0; i < 10; ++ i) {
                sig = (t + tRise_m - a) / (sqr2 * inv_erf08);
                t = a - 0.5 * sqr2 * (sig + tmps) * inv_erf08;
                sig = (0.5 * (t + tmpt) + tRise_m - a) / (sqr2 * inv_erf08);
                tmps = sig;
                tmpt = t;
            }
            tEmission_m = tPulseLengthFWHM_m + 10. * sig;
            tBin_m = tEmission_m / nBins_m;

            double lo = -tBin_m / 2.0 * nBins_m;
            double hi = tBin_m / 2.0 * nBins_m;
            double dx = tBin_m / sBins_m;
            double x = lo;
            double tot = 0;
            double weight = 2.0;
            gsl_histogram_set_ranges_uniform(h_m, lo, hi);

            // sample the function that describes the histogram of the requested distribution
            for(int i = 0; i < binTotal + 1; ++ i, x += dx, weight = 6. - weight) {
                distributionTable_m[i] = gsl_sf_erf((x + a) / (sqrt(2) * sig)) - gsl_sf_erf((x - a) / (sqrt(2) * sig));
                tot += distributionTable_m[i] * weight;
            }
            tot -= distributionTable_m[binTotal] * (5. - weight);
            tot -= distributionTable_m[0];

            for(int k = 0; k < nBins_m; ++ k) {
                gsl_ran_discrete_t *table = gsl_ran_discrete_preproc(sBins_m, &(distributionTable_m[sBins_m * k]));
                double loc_fraction = -distributionTable_m[sBins_m * k] / tot;

                weight = 2.0;
                for(int i = sBins_m * k; i < sBins_m * (k + 1) + 1; ++ i, weight = 6. - weight) {
                    loc_fraction += distributionTable_m[i] * weight / tot;
                }
                loc_fraction -= distributionTable_m[sBins_m * (k + 1)] * (5. - weight) / tot;
                int bin_size = static_cast<int>(floor(loc_fraction * Np + 0.5)); //number of particles in bin!

                for(int i = 0; i < bin_size; i++) {
                    double xx[2];
                    gsl_qrng_get(R_m, xx);
637 638
                    gsl_histogram_increment(h_m, (hi * (xx[1] +
                                                        static_cast<int>(gsl_ran_discrete(rn_m, table)) - binTotal / 2 + k * sBins_m) / (binTotal / 2)));
gsell's avatar
gsell committed
639 640 641 642 643 644 645 646 647 648 649 650 651 652
                }
                gsl_ran_discrete_free(table);
            }
            pbin_m->setHistogram(h_m);

            // ASTRA mode
            phimax_m = Physics::pi / 2.0;
            *gmsg << " -- B I N N I N G in T -----------------------------------------" << endl;
            *gmsg << " ---------------------I N P U T --------------------------------" << endl;
            *gmsg << " ASTRA FLAT TOP &  THERMAL EMITTANCE in ASTRA MODE" << endl;
            *gmsg << " Kinetic energy (thermal emittance) = " << ekin_m << " [eV]  " << endl;
            *gmsg << " Phi max = " << phimax_m * 180 / Physics::pi << " [deg]  " << endl;
            *gmsg << " tBin = " << tBin_m << " [sec]  nBins = " << nBins_m << " tEmission =  " << tEmission_m << " [sec] " << endl;

653
            writeToFile();
gsell's avatar
gsell committed
654 655 656 657 658
        }

        break;
        case GUNGAUSSFLATTOPTH: {

659 660
            tEmission_m = tPulseLengthFWHM_m + (cutoff_m - sqrt(2.0 * log(2.0))) * (sigmaRise_m + sigmaFall_m);
            tBin_m = tEmission_m / nBins_m;
gsell's avatar
gsell committed
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681

            rGen_m = new RANLIB_class(265314159, 4);

            //FIXME: hack
            gsl_rng_env_setup();
            rn_m = gsl_rng_alloc(gsl_rng_1dhalton);
            R_m = gsl_qrng_alloc(gsl_qrng_halton, 2);
            int binTotal = sBins_m * nBins_m; // number of sampling bins

            h_m = gsl_histogram_alloc(binTotal);
            createTimeBins(Np);
            pbin_m->setHistogram(h_m);

            distributionTable_m = new double[binTotal];
            for(int i = 0; i < binTotal; i++)
                distributionTable_m[i] = gsl_histogram_get(h_m, i);

            // ASTRA mode
            phimax_m = Physics::pi / 2.0;
            *gmsg << " -- B I N N I N G in T -----------------------------------------" << endl;
            *gmsg << " ---------------------I N P U T --------------------------------" << endl;
adelmann's avatar
cleanup  
adelmann committed
682
            *gmsg << " GUNGAUSS FLAT TOP &  THERMAL EMITTANCE" << endl;
gsell's avatar
gsell committed
683 684 685 686
            *gmsg << " Kinetic energy (thermal emittance) = " << ekin_m << " [eV]  " << endl;
            *gmsg << " Phi max = " << phimax_m * 180 / Physics::pi << " [deg]  " << endl;
            *gmsg << " tBin = " << tBin_m << " [sec]  nBins = " << nBins_m << " tEmission =  " << tEmission_m << " [sec] " << endl;

687
            writeToFile();
gsell's avatar
gsell committed
688 689 690 691 692 693 694 695 696
        }
        break;

        case BINOMIAL: {

            for(int j = 0; j < 3; j++) {
                double chi = asin(corr_m[j]);
                emit_m[j] = sigx_m[j] * sigp_m[j] * cos(chi);
            }
adelmann's avatar
cleanup  
adelmann committed
697

gsell's avatar
gsell committed
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
            for(int j = 0; j < 3; j++) {
                beta_m[j]  = sigx_m[j] * sigx_m[j] / emit_m[j];
                gamma_m[j] = sigp_m[j] * sigp_m[j] / emit_m[j];
                alpha_m[j] = -corr_m[j] * sqrt(beta_m[j] * abs(gamma_m[j]));
            }
            createBinom(emit_m, alpha_m, beta_m, gamma_m, binc_m, beam, Np, isBinned);
        }
        break;

        case GAUSS: {

            avrgpt_m = eVtoBetaGamma(Attributes::getReal(itsAttr[PT]), beam.getM());
            avrgt_m  = Attributes::getReal(itsAttr[T]);

            /*
              give up the portability w.r.t. the rangen
              and hope to be more scalable
            */
            rGen_m = new RANLIB_class((Ippl::myNode() + 1) * 265314159, 4);

            IpplTimings::startTimer(beam.distrCreate_m);

            if(Np > 1E8) {
                int k = 10;
                Np = (size_t)Np / k;
                //Np = (size_t)Np/Ippl::getNodes()/k;
                *gmsg << "Sampl= " << Np *Ippl::getNodes() << " x " << k << " Total= " << k *Np *Ippl::getNodes() <<  endl;
                for(int kk = 0; kk < k; kk++) {
                    sampleGauss(beam, kk * Np);
                    beam.boundp();
                    *gmsg << "Sampl Gauss k= " << kk << " N= " << beam.getTotalNum() << endl;
                }
            } else {
                //Np = (size_t) Np / Ippl::getNodes();
                sampleGauss(beam, Np);
            }
            *gmsg << "Sample Gauss done ..." << endl;

            IpplTimings::stopTimer(beam.distrCreate_m);
        }
        break;
        case FROMFILE: {
            *gmsg << "\n-------------------------------------------------------------" << endl;
            *gmsg << "     READ ININITAL DISTRIBUTION FROM FILE    " << endl;
            *gmsg << "     BE AWARE OF THE FACT THAT ONLY NODE 0 IS READING IN " << endl;
            *gmsg << "-------------------------------------------------------------\n" << endl;

            if(isBinned) {
                *gmsg << "     DISTRIBUTION will be binned using " << nBins_m << " energy bins " << endl;
747
                const std::string fn;
gsell's avatar
gsell committed
748 749 750 751 752 753
                binnDistributionFromFile(beam, fn);

            } else {
                std::ofstream os;
                if(Ippl::getNodes() == 1) {
                    *gmsg << " Write distribution to file dist.dat" << endl;
754
                    std::string file("data/dist.dat");
gsell's avatar
gsell committed
755 756 757 758 759 760 761 762
                    os.open(file.c_str());
                    if(os.bad()) {
                        *gmsg << "Unable to open output file " <<  file << endl;
                    }
                    os << "# x px y py z pz " << endl;
                }

                if(Ippl::myNode() == 0) {
763
                    const std::string filename = Attributes::getString(itsAttr[FNAME]);
gsell's avatar
gsell committed
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 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 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885
                    double x0, px0, y0, py0, psi0, del0;

                    std::ifstream fs;
                    fs.open(filename.c_str());

                    if(fs.fail()) {
                        throw OpalException("Distribution::Create()",
                                            "Open file operation failed, please check if \""
                                            + filename +  "\" really exists.");
                    }

                    fs >> Np;
                    if(Np <= 0) {
                        throw OpalException("Distribution::Create()",
                                            " The particle number should be bigger than zero! Please check the first line of file \""
                                            + filename +  "\".");
                    }

                    for(unsigned int i = 0; i < Np; i++) {
                        if(!fs.eof()) {
                            beam.create(1);
                            fs >> x0 >> px0 >> y0 >> py0 >> psi0 >> del0;
                            beam.R[i] = Vector_t(x0, y0, psi0);
                            beam.P[i] = Vector_t(px0, py0, del0);
                            beam.Bin[i] = 0; // not initialized
                            beam.Q[i] = beam.getChargePerParticle();
                            beam.PType[i] = 0;
                            if(Ippl::getNodes() == 1) {
                                os <<  beam.R[i](0) << "\t " <<  beam.P[i](0)    << "\t "
                                   <<  beam.R[i](1) << "\t " <<  beam.P[i](1)    << "\t "
                                   <<  beam.R[i](2) << "\t " <<  beam.P[i](2)    << "\t "
                                   << endl;
                            }
                        } else {
                            throw OpalException("Distribution::Create()",
                                                "End of file reached before all particles imported, please check file \""
                                                + filename +  "\".");
                            return;
                        }
                    }
                    fs.close();
                    os.close();
                }
            }
        }
        break;
        default:
            INFOMSG("Distribution unknown" << endl;);
    }

    /*
      In the case of a binned distribution (gun)
      we have to do the boundp after emission.
    */

    if(isBinned)
        beam.setPBins(pbin_m);
    else
        beam.boundp();
    beam.LastSection = 0;

}

/*
 * This adds other distributions to the main distribution. This is currently only
 * defined to work with distribution type "GUNGAUSSFLATTOPTH". All others will return
 * a false value.
 *
 * Also note that only the time structure of the added distributions are used. The
 * transverse profile is defined only by the main distribution (that is being added to).
 *
 */
bool Distribution::addDistributions(PartBunch &beam, vector<Distribution *> distributions, size_t numberOfParticles) {
    /// Check main distribution type.
    switch(distrTypeT_m) {

        case GUNGAUSSFLATTOPTH: {

            /// Find weight of each distribution. Also check that we have distributions to add.
            double totalWeight = Attributes::getReal(itsAttr[WEIGHT]);
            unsigned int numberOfDistToAdd = 0;
            vector<double> relativeWeight;
            relativeWeight.push_back(totalWeight);
            for(vector<Distribution *>::const_iterator distIterator = distributions.begin(); distIterator != distributions.end(); distIterator++) {

                if(distT_m != Attributes::getString(*((*distIterator)->findAttribute("DISTRIBUTION")))) {
                    *gmsg << " --- Mismatched Distribution types in Distribution List ---" << endl
                          << " Type: " << Attributes::getString(*((*distIterator)->findAttribute("DISTRIBUTION"))) << endl
                          << " Distribution will not be used. " << endl
                          << " ----------------------------------------------------------" << endl;
                    relativeWeight.push_back(0.0);
                } else {
                    relativeWeight.push_back(Attributes::getReal(*((*distIterator)->findAttribute("WEIGHT"))));
                    totalWeight += Attributes::getReal(*((*distIterator)->findAttribute("WEIGHT")));
                    numberOfDistToAdd++;
                }
            }

            if(numberOfDistToAdd == 0)
                return false;
            else {

                for(vector<double>::iterator weightIterator = relativeWeight.begin(); weightIterator != relativeWeight.end(); weightIterator++)
                    *weightIterator /= totalWeight;

                /*
                 * Find emission bounds of each distribution, including delay defined by itsAttr[T]".
                 * The total emission time will be defined by these bounds.
                 *
                 * We assume that particles start to emit at t = 0 i the absence of a distribution time
                 * shift.
                 */
                double maxT = 0.0;
                double minT = 0.0;
                for(unsigned int distIterator = 0; distIterator < relativeWeight.size(); distIterator++) {

                    double deltaT = 0.0;
                    if(distIterator == 0) {

                        deltaT = Attributes::getReal(itsAttr[T]);
                        maxT = tEmission_m + deltaT;
                        minT = deltaT;
886

kraus's avatar
kraus committed
887
                        // FIXME: floating point comparison
gsell's avatar
gsell committed
888 889
                    } else if(relativeWeight.at(distIterator) != 0.0) {

kraus's avatar
kraus committed
890 891 892 893 894
                        // // Find emission time without time shift.
                        // double pulseLengthFWHM = Attributes::getReal(*(distributions.at(distIterator - 1)->findAttribute("TPULSEFWHM")));
                        // double cutOff = Attributes::getReal(*(distributions.at(distIterator - 1)->findAttribute("CUTOFF")));
                        // double riseTime = Attributes::getReal(*(distributions.at(distIterator - 1)->findAttribute("TRISE")));
                        // double fallTime = Attributes::getReal(*(distributions.at(distIterator - 1)->findAttribute("TFALL")));
gsell's avatar
gsell committed
895

kraus's avatar
kraus committed
896 897 898
                        // double timeRatio = sqrt(2.0 * log(10.0)) - sqrt(2.0 * log(10.0 / 9.0));
                        // double sigmaRiseTime = riseTime / timeRatio;
                        // double sigmaFallTime = fallTime / timeRatio;
gsell's avatar
gsell committed
899

kraus's avatar
kraus committed
900
                        // double emissionTime = pulseLengthFWHM + (cutOff - sqrt(2.0 * log(2.0))) * (sigmaRiseTime + sigmaFallTime);
gsell's avatar
gsell committed
901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933

                        // Find max. and min. time.
                        deltaT = Attributes::getReal(*(distributions.at(distIterator - 1)->findAttribute("T")));
                        if(maxT < tEmission_m + deltaT) maxT = tEmission_m + deltaT;
                        if(minT > deltaT) minT = deltaT;
                    }
                }
                tEmission_m = maxT - minT;
                tBin_m = tEmission_m / nBins_m;

                /*
                 * Now we reset the main histogram and reallocate particles to the different time bins.
                 */
                gsl_histogram_reset(h_m);
                gsl_histogram_set_ranges_uniform(h_m, 0, tEmission_m);

                gsl_rng_env_setup();
                gsl_rng *ranNumberGen = gsl_rng_alloc(gsl_rng_default);

                unsigned int particleCount = 0;
                double deltaT = 0.0;

                for(int distIterator = relativeWeight.size() - 1; distIterator >= 0; distIterator--) {

                    // Calculate number of particles for this distribution.
                    unsigned int nParticles = 0;
                    if(distIterator != 0) {
                        nParticles = static_cast<unsigned int>(numberOfParticles * relativeWeight.at(distIterator));
                        particleCount += nParticles;
                    } else
                        nParticles = numberOfParticles - particleCount;

                    // Add particles to time histogram.
934
                    if(nParticles > 0) {
935

936 937 938 939
                        double sigmaRiseTime = 0.0;
                        double sigmaFallTime = 0.0;
                        double timeFlat = 0.0;
                        double cutOff = 0.0;
940

941 942 943 944 945
                        if(distIterator == 0) {
                            sigmaRiseTime = sigmaRise_m;
                            sigmaFallTime = sigmaFall_m;
                            timeFlat = tPulseLengthFWHM_m - sqrt(2.0 * log(2.0)) * (sigmaRise_m + sigmaFall_m);
                            cutOff = cutoff_m;
946
                            deltaT = Attributes::getReal(itsAttr[T]);
947 948 949
                        } else {
                            double riseTime = Attributes::getReal(*(distributions.at(distIterator - 1)->findAttribute("TRISE")));
                            double fallTime = Attributes::getReal(*(distributions.at(distIterator - 1)->findAttribute("TFALL")));
950

951 952
                            cutOff = Attributes::getReal(*(distributions.at(distIterator - 1)->findAttribute("CUTOFF")));
                            deltaT = Attributes::getReal(*(distributions.at(distIterator - 1)->findAttribute("T")));
953

954 955 956
                            double timeRatio = sqrt(2.0 * log(10.0)) - sqrt(2.0 * log(10.0 / 9.0));
                            sigmaRiseTime = riseTime / timeRatio;
                            sigmaFallTime = fallTime / timeRatio;
957

958
                            timeFlat = Attributes::getReal(*(distributions.at(distIterator - 1)->findAttribute("TPULSEFWHM")))
959
                                       - sqrt(2.0 * log(2.0)) * (sigmaRiseTime + sigmaFallTime);
gsell's avatar
gsell committed
960
                        }
961
                        if(timeFlat < 0.0) timeFlat = 0.0;
962

963
                        const double totalArea = timeFlat + 0.5 * sqrt(2.0 * Physics::pi) * (sigmaRiseTime + sigmaFallTime);
964

965
                        unsigned int numPartInRise = nParticles * 0.5 * gsl_sf_erf(cutOff / sqrt(2.0))
966
                                                     * sqrt(2.0 * Physics::pi) * sigmaRiseTime / totalArea;
967
                        unsigned int numPartInFall = nParticles * 0.5 * gsl_sf_erf(cutOff / sqrt(2.0))
968
                                                     * sqrt(2.0 * Physics::pi) * sigmaFallTime / totalArea;
969
                        unsigned int numPartInFlat = nParticles - numPartInRise - numPartInFall;
970

971 972 973 974 975
                        if(timeFlat == 0.0) {
                            numPartInRise += numPartInFlat / 2;
                            numPartInFall = nParticles - numPartInRise;
                            numPartInFlat = 0;
                        }
976

977 978 979 980 981 982
                        for(unsigned int partIterator = 0; partIterator < numPartInRise; partIterator++) {
                            double tRandom = gsl_ran_gaussian_tail(ranNumberGen, 0, sigmaRiseTime);
                            while(tRandom > cutOff * sigmaRiseTime)
                                tRandom = gsl_ran_gaussian_tail(ranNumberGen, 0, sigmaRiseTime);
                            gsl_histogram_increment(h_m, -tRandom + cutOff * sigmaRiseTime + deltaT - minT);
                        }
983

984 985 986 987 988 989
                        for(unsigned int partIterator = 0; partIterator < numPartInFall; partIterator++) {
                            double tRandom = gsl_ran_gaussian_tail(ranNumberGen, 0, sigmaFallTime);
                            while(tRandom > cutOff * sigmaFallTime)
                                tRandom = gsl_ran_gaussian_tail(ranNumberGen, 0, sigmaFallTime);
                            gsl_histogram_increment(h_m, tRandom + cutOff * sigmaRiseTime + timeFlat + deltaT - minT);
                        }
990

991 992 993 994 995
                        for(unsigned int partIterator = 0; partIterator < numPartInFlat; partIterator++) {
                            double tRandom = 0.0;
                            gsl_qrng_get(R_m, &tRandom);
                            tRandom *= timeFlat;
                            gsl_histogram_increment(h_m, tRandom + cutOff * sigmaRiseTime + deltaT - minT);
gsell's avatar
gsell committed
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
                        }
                    }
                }

                // Free random number generator.
                gsl_rng_free(ranNumberGen);
            }

            /*
             * Do a boundp if we don't have energy bins.
             */
            if(!(nBins_m > 0))
                beam.boundp();

            /*
             * Write time histogram to file.
             */
            if(Ippl::myNode() == 0) {
                FILE *fp;
                fp = fopen("data/hist.dat", "w");
                gsl_histogram_fprintf(fp, h_m, "%g", "%g");
                fclose(fp);
            }

            return true;
        }
        break;

        default:
            return false;
    }
}

/**
 * This is the generator for a Gaussian distribution
 *
 * @param beam
 * @param Np
 */
void Distribution::sampleGauss(PartBunch &beam, size_t Np) {
    int pc = 0;
    size_t count = 0;

    for(size_t i = beam.getTotalNum(); i < Np; i++) {
        double x, y;      // generate independent Gaussians, then correlate and finaly scale
        x  = rGen_m->gauss(0.0, 1.0);
        y  = rGen_m->gauss(0.0, 1.0);
        double xx = x;
        double yy = y;
        double px0  = x * corr_m[0] + y * sqrt(1.0 - corr_m[0] * corr_m[0]);
adelmann's avatar
adelmann committed
1046
        double x0   = x * sigx_m[0] + gauss_offset_m[0];
1047
        px0 *= sigp_m[0];
gsell's avatar
gsell committed
1048 1049 1050 1051

        x  = rGen_m->gauss(0.0, 1.0);
        y  = rGen_m->gauss(0.0, 1.0);
        double py0  = x * corr_m[1] + y * sqrt(1.0 - corr_m[1] * corr_m[1]);
adelmann's avatar
adelmann committed
1052 1053
        double y0   =  x * sigx_m[1] + gauss_offset_m[1];
        py0 *= sigp_m[1];
gsell's avatar
gsell committed
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070

        double del0;
        double psi0;
        x  = rGen_m->gauss(0.0, 1.0);
        y  = rGen_m->gauss(0.0, 1.0);

        double tempa = 1.0 - corr_m[0] * corr_m[0];
        const double l32 = (corr_m[6] - corr_m[0] * corr_m[5]) / sqrt(abs(tempa)) * tempa / abs(tempa);
        double tempb = 1 - corr_m[5] * corr_m[5] - l32 * l32;
        const double l33 = sqrt(abs(tempb)) * tempb / abs(tempb);
        psi0 = xx * corr_m[5] + yy * l32 + x * l33;
        const double l42 = (corr_m[4] - corr_m[0] * corr_m[3]) / sqrt(abs(tempa)) * tempa / abs(tempa);
        const double l43 = (corr_m[2] - corr_m[5] * corr_m[3] - l42 * l32) / l33;
        double tempc = 1 - corr_m[3] * corr_m[3] - l42 * l42 - l43 * l43;
        const double l44 = sqrt(abs(tempc)) * tempc / abs(tempc);

        del0 = xx * corr_m[3] + yy * l42 + x * l43 + y * l44;
adelmann's avatar
adelmann committed
1071 1072
        psi0 = avrgt_m + psi0 * sigx_m[2];
        del0 = avrgpt_m + sigp_m[2] * del0;
gsell's avatar
gsell committed
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
        if(pc == Ippl::myNode()) {
            beam.create(1);
            beam.R[count] = Vector_t(x0, y0, psi0);
            beam.P[count] = Vector_t(px0, py0, del0);
            beam.Bin[count] = 0; // not initialized
            beam.Q[count] = beam.getChargePerParticle();
            beam.PType[count] = 0;
            beam.TriID[count] = 0;
            count++;
        }
        pc++;
        if(pc == Ippl::getNodes())
            pc = 0;
    }
}

/**
 *
 *
 * @param dt
 *
 * @return
 */
pair<Vector_t, Vector_t> Distribution::sample(double dt, int binNumber) {

    Vector_t r(0.0);
    Vector_t p(0.0);

    double x0, y0;

    switch(distrTypeT_m) {

        case ASTRAFLATTOPTH:
        case GUNGAUSSFLATTOPTH: {
            double x, y;
            double xy = 6;

            if(lp_m != NULL) {
                lp_m->GetXY(&x, &y);
                x = 2 * x - 1.0;
                y = 2 * y - 1.0;
            } else if(qrng_m != NULL) {
                while(xy > 1) {
                    double v0[2];
                    gsl_qrng_get(qrng_m, v0);
                    x = -1.0 + (2.0 * v0[0]);
                    y = -1.0 + (2.0 * v0[1]);
                    xy = sqrt(x * x + y * y);
                }
            } else {
                while(xy > 1) {
                    x  = rGen_m->uniform(-1.0, 1.0);
                    y  = rGen_m->uniform(-1.0, 1.0);
                    xy = sqrt(x * x + y * y);
                }
            }

adelmann's avatar
adelmann committed
1130 1131
            x0   =  x * sigx_m[0];
            y0   =  y * sigx_m[1];
gsell's avatar
gsell committed
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167

            /*
              Now calculate the thermal emittances
            */

            const double phi   = 2.0 * acos(sqrt(rGen_m->uniform(0.0, 1.0)));
            const double theta = 2.0 * Physics::pi * rGen_m->uniform(0.0, 1.0);

            const double px0   = ptot_m * sin(phi) * cos(theta);
            const double py0   = ptot_m * sin(phi) * sin(theta);
            const double del0  = ptot_m * abs(cos(phi));

            p = Vector_t(px0, py0, del0);


            gsl_ran_discrete_t *table = gsl_ran_discrete_preproc(sBins_m, &(distributionTable_m[sBins_m * binNumber]));
            double xr[2] = {0.0, 0.0};
            gsl_qrng_get(R_m, xr);
            double s0 = dt * (xr[1] + static_cast<int>(gsl_ran_discrete(rn_m, table))) / sBins_m;
            r = Vector_t(x0, y0, s0);

            gsl_ran_discrete_free(table);
            break;
        }

        default:
            INFOMSG("Distribution unknown" << endl;);
    }
    return pair<Vector_t, Vector_t>(r, p);
}

pair<Vector_t, Vector_t> Distribution::sampleNEW(double dt, int binNumber) {

    Vector_t r(0.0);
    Vector_t p(0.0);

1168 1169
    double x0 = 0.0;
    double y0 = 0.0;
gsell's avatar
gsell committed
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181

    switch(distrTypeT_m) {

        case ASTRAFLATTOPTH:
        case GUNGAUSSFLATTOPTH: {
            double x, y;
            double xy = 6;

            if(lp_m != NULL) {
                lp_m->GetXY(&x, &y);
                x = 2 * x - 1.0;
                y = 2 * y - 1.0;
1182 1183 1184 1185 1186 1187
            } else if(transvCutOff_m > 0.0) {
                x0 = rGen_m->gauss(0.0, sigx_m[0]);
                y0 = rGen_m->gauss(0.0, sigx_m[1]);
                while(sqrt(pow(x0, 2.0) + pow(y0, 2.0)) > transvCutOff_m) {
                    x0 = rGen_m->gauss(0.0, sigx_m[0]);
                    y0 = rGen_m->gauss(0.0, sigx_m[1]);
gsell's avatar
gsell committed
1188 1189
                }
            } else {
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
                if(qrng_m != NULL) {
                    while(xy > 1) {
                        double v0[2];
                        gsl_qrng_get(qrng_m, v0);
                        x = -1.0 + (2.0 * v0[0]);
                        y = -1.0 + (2.0 * v0[1]);
                        xy = sqrt(x * x + y * y);
                    }
                } else {
                    while(xy > 1) {
                        x  = rGen_m->uniform(-1.0, 1.0);
                        y  = rGen_m->uniform(-1.0, 1.0);
                        xy = sqrt(x * x + y * y);
                    }
gsell's avatar
gsell committed
1204 1205
                }

1206 1207 1208
                x0   =  x * sigx_m[0];
                y0   =  y * sigx_m[1];
            }
gsell's avatar
gsell committed
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248

            /*
              Now calculate the thermal emittances
            */

            const double phi   = 2.0 * acos(sqrt(rGen_m->uniform(0.0, 1.0)));
            const double theta = 2.0 * Physics::pi * rGen_m->uniform(0.0, 1.0);

            const double px0   = ptot_m * sin(phi) * cos(theta);
            const double py0   = ptot_m * sin(phi) * sin(theta);
            const double del0  = ptot_m * abs(cos(phi));

            p = Vector_t(px0, py0, del0);

            //           gsl_ran_discrete_t *table = gsl_ran_discrete_preproc(1, &(distributionTable_m[binNumber]));
            double xr;
            gsl_qrng_get(R_m, &xr);

            double s0 = dt * xr;

            r = Vector_t(x0, y0, s0);

            //            gsl_ran_discrete_free(table);
            break;
        }

        default:
            INFOMSG("Distribution unknown" << endl;);
    }
    return pair<Vector_t, Vector_t>(r, p);
}

/**
 * This method fills the gsl histogram (h_m) with a binned
 * Gauss-Flattop-Distribution as specified in the manual.
 *
 * @param Np  number of total particles to generate
 */
void Distribution::createTimeBins(const int Np) {

1249
    if(Options::rngtype != std::string("RANDOM")) {
1250
        INFOMSG("RNGTYPE= " << Options::rngtype << endl);
1251
        if(Options::rngtype == std::string("HALTON"))
1252
            qrng_m = gsl_qrng_alloc(gsl_qrng_halton, 2);
1253
        else if(Options::rngtype == std::string("SOBOL"))
1254
            qrng_m = gsl_qrng_alloc(gsl_qrng_sobol, 2);
1255
        else if(Options::rngtype == std::string("NIEDERREITER"))
1256 1257 1258 1259
            qrng_m = gsl_qrng_alloc(gsl_qrng_niederreiter_2, 2);
        else {
            INFOMSG("RNGTYPE= " << Options::rngtype << " not known, using HALTON" << endl);
            qrng_m = gsl_qrng_alloc(gsl_qrng_halton, 2);
gsell's avatar
gsell committed
1260
        }
1261
    }
1262

1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
    gsl_histogram_set_ranges_uniform(h_m, 0, tEmission_m);
    gsl_rng_env_setup();
    gsl_rng *r = gsl_rng_alloc(gsl_rng_default);
    const double sq2pi = sqrt(2.0 * Physics::pi);
    double tFlat = tPulseLengthFWHM_m - sqrt(2.0 * log(2.0)) * (sigmaRise_m + sigmaFall_m);
    if(tFlat < 0.0) tFlat = 0.0;
    const double totA = tFlat + 0.5 * sq2pi * (sigmaRise_m + sigmaFall_m);
    int nrise = Np * 0.5 * gsl_sf_erf(cutoff_m / sqrt(2.0)) * sq2pi * sigmaRise_m / totA;
    int nfall = Np * 0.5 * gsl_sf_erf(cutoff_m / sqrt(2.0)) * sq2pi * sigmaFall_m / totA;
    int nflat = Np - nrise - nfall;
1273

1274 1275 1276 1277 1278
    if(tFlat == 0.0) {
        nrise += nflat / 2;
        nfall = Np - nrise;
        nflat = 0;
    }
1279

1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
    // Rise: [0, c\sigma_R]
    for(int i = 0; i < nrise; i++) {
        double r1 = gsl_ran_gaussian_tail(r, 0, sigmaRise_m);
        while(r1 > cutoff_m * sigmaRise_m)
            r1 = gsl_ran_gaussian_tail(r, 0, sigmaRise_m);
        gsl_histogram_increment(h_m, -r1 + cutoff_m * sigmaRise_m);
    }
    // Fall: [c\sigma_R + tFlat, c\sigma_R + tFlat + c\sigma_F]
    for(int i = 0; i < nfall; i++) {
        double r1 = gsl_ran_gaussian_tail(r, 0, sigmaFall_m);
        while(r1 > cutoff_m * sigmaFall_m)
            r1 = gsl_ran_gaussian_tail(r, 0, sigmaFall_m);
        gsl_histogram_increment(h_m, r1 + cutoff_m * sigmaRise_m + tFlat);
    }
    // Flattop: [c\sigma_R, c\sigma_R + tFlat]
    //
    // The flat top can also have sinusoidal modulations.
1297

1298
    gsl_qrng *Qrng = gsl_qrng_alloc(gsl_qrng_halton, 1);
1299

1300
    gsl_qrng *R2_m = gsl_qrng_alloc(gsl_qrng_halton, 2);
1301

1302 1303 1304 1305 1306
    // Get modulation parameters.
    double modulationAmplitude = Attributes::getReal(itsAttr[FTOSCAMPLITUDE]) / 100.0;
    double numberOfModulationPeriods = fabs(Attributes::getReal(itsAttr[FTOSCPERIODS]));
    double modulationPeriod = 0.0;
    if(numberOfModulationPeriods != 0) modulationPeriod = tFlat / numberOfModulationPeriods;
1307

1308 1309 1310 1311 1312 1313 1314 1315
    // Sample flat top.
    for(int i = 0; i < nflat; i++) {
        double r1 = 0.0;
        double r2 = 0.0;
        double rn[2] = {0.0, 0.0};
        if(modulationAmplitude == 0.0 || numberOfModulationPeriods == 0) {
            // r1 = gsl_ran_flat(r, 0, tFlat);
            gsl_qrng_get(Qrng, &r1);
1316

1317
            r1 *= tFlat;
1318

1319 1320 1321 1322
        } else {
            bool accept = false;
            while(!accept) {
                gsl_qrng_get(R2_m, rn);
gsell's avatar
gsell committed
1323
                // r1 = gsl_ran_flat(r, 0, tFlat);
1324
                /// r2 = gsl_ran_flat(r, 0, 1.0);
1325 1326 1327 1328 1329
                r1 = rn[0] * tFlat;
                r2 = rn[1];
                double function = (1.0 + modulationAmplitude * sin(Physics::two_pi * r1 / modulationPeriod))
                                  / (1.0 + fabs(modulationAmplitude));
                if(r2 <= function) accept = true;
gsell's avatar
gsell committed
1330 1331
            }
        }
1332 1333 1334 1335 1336 1337 1338
        gsl_histogram_increment(h_m, r1 + cutoff_m * sigmaRise_m);
    }
    if(Ippl::myNode() == 0) {
        FILE *fp;
        fp = fopen("data/hist.dat", "w");
        gsl_histogram_fprintf(fp, h_m, "%g", "%g");
        fclose(fp);
gsell's avatar
gsell committed
1339
    }
1340 1341
    gsl_qrng_free(Qrng);
    gsl_rng_free(r);
gsell's avatar
gsell committed
1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
}

/**
 *
 *
 * @param p
 */
void Distribution::createSlicedBunch(int sl, double charge, double gamma, double mass, double current, double center, double Bz0, EnvelopeBunch *p) {
    double beamWidth = 0.0;
    double beamEnergy = 0.0;
    //int sl = (int) Attributes::getReal(itsAttr[NBIN]);
    *gmsg << "About to create a sliced bunch with " << sl << " slices" << endl;
    *gmsg << "mass = " << mass << " gamma = " << gamma << endl;
    IpplTimings::startTimer(p->distrCreate_m);

    distT_m = Attributes::getString(itsAttr[DISTRIBUTION]);
    if(distT_m == "GAUSS")
        distrTypeT_m = GAUSS;
    else if(distT_m == "GUNGAUSSFLATTOPTH")
        distrTypeT_m = GUNGAUSSFLATTOPTH;
    else if(distT_m == "FROMFILE")
        distrTypeT_m = FROMFILE;
    else if(distT_m == "BINOMIAL")
        distrTypeT_m = BINOMIAL;

adelmann's avatar
adelmann committed
1367 1368 1369 1370 1371 1372 1373
    corr_m[0] = Attributes::getReal(itsAttr[CORRX]);
    corr_m[1] = Attributes::getReal(itsAttr[CORRY]);
    corr_m[2] = Attributes::getReal(itsAttr[CORRT]);
    corr_m[3] = Attributes::getReal(itsAttr[R61]);
    corr_m[4] = Attributes::getReal(itsAttr[R62]);
    corr_m[5] = Attributes::getReal(itsAttr[R51]);
    corr_m[6] = Attributes::getReal(itsAttr[R52]);
1374

adelmann's avatar
adelmann committed
1375 1376 1377
    sigx_m = Vector_t(Attributes::getReal(itsAttr[SIGMAX]),
                      Attributes::getReal(itsAttr[SIGMAY]),
                      Attributes::getReal(itsAttr[SIGMAT]));
1378

gsell's avatar
gsell committed
1379 1380
    switch(distrTypeT_m) {

1381
        case GUNGAUSSFLATTOPTH: {
adelmann's avatar
adelmann committed
1382

1383
            nBins_m = static_cast<int>(fabs(Attributes::getReal(itsAttr[NBIN])));
adelmann's avatar
adelmann committed
1384