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);
gsell's avatar
gsell committed
171 172 173 174 175
    itsAttr[TRANSVCUTOFF] = makeReal("TRANSVCUTOFF", "Transverse cut-off in units of sigma", 3.0);

    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 310 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

    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
 */
Distribution::Distribution(const string &name, Distribution *parent):
    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 386 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
 * At the moment only write the header into the file dist.dat
 * PartBunch will then append (very uggly)
 * @param 
 * @param 
 * @param 
 */
void Distribution::writeToFile() {

    if(Ippl::getNodes() == 1) {
        if (os_m.is_open()) {
            ;
        }
        else {
            *gmsg << " Write distribution to file dist.dat" << endl;
            string file("data/dist.dat");
            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
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 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
 * @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]);

    if(!(laserProfileFn_m == string(""))) {
        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
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 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 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
    /*
      Setup some common data:
    */
    if (distrTypeT_m == GUNGAUSSFLATTOPTH || distrTypeT_m == ASTRAFLATTOPTH) {
        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]);
    
        sigx_m = Vector_t(Attributes::getReal(itsAttr[SIGMAX]),
                          Attributes::getReal(itsAttr[SIGMAY]),
                          Attributes::getReal(itsAttr[SIGMAT]));
        
        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());
    }

    if (distrTypeT_m == BINOMIAL || distrTypeT_m == GAUSS) {

        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]));
        
        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
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 566 567 568 569 570 571 572 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 637
    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: {

            if(Options::rngtype != string("RANDOM")) {
                INFOMSG("RNGTYPE= " << Options::rngtype << endl);
                if(Options::rngtype == string("HALTON"))
                    qrng_m = gsl_qrng_alloc(gsl_qrng_halton, 2);
                else if(Options::rngtype == string("SOBOL"))
                    qrng_m = gsl_qrng_alloc(gsl_qrng_sobol, 2);
                else if(Options::rngtype == string("NIEDERREITER"))
                    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);
adelmann's avatar
adelmann committed
638 639
                    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
640 641 642 643 644 645 646 647 648 649 650 651 652 653
                }
                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;

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

        break;
        case GUNGAUSSFLATTOPTH: {

660 661
            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
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682

            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
683
            *gmsg << " GUNGAUSS FLAT TOP &  THERMAL EMITTANCE" << endl;
gsell's avatar
gsell committed
684 685 686 687
            *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;

688
            writeToFile();
gsell's avatar
gsell committed
689 690 691 692 693 694 695 696 697
        }
        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
698

gsell's avatar
gsell committed
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 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 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 886
            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;
                const string fn;
                binnDistributionFromFile(beam, fn);

            } else {
                std::ofstream os;
                if(Ippl::getNodes() == 1) {
                    *gmsg << " Write distribution to file dist.dat" << endl;
                    string file("data/dist.dat");
                    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) {
                    const string filename = Attributes::getString(itsAttr[FNAME]);
                    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;
887

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

kraus's avatar
kraus committed
891 892 893 894 895
                        // // 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
896

kraus's avatar
kraus committed
897 898 899
                        // 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
900

kraus's avatar
kraus committed
901
                        // double emissionTime = pulseLengthFWHM + (cutOff - sqrt(2.0 * log(2.0))) * (sigmaRiseTime + sigmaFallTime);
gsell's avatar
gsell committed
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 934

                        // 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.
935 936 937 938 939 940 941 942 943 944 945 946
                    if(nParticles > 0) {
                        
                        double sigmaRiseTime = 0.0;
                        double sigmaFallTime = 0.0;
                        double timeFlat = 0.0;
                        double cutOff = 0.0;
                        
                        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;
gsell's avatar
gsell committed
947
                                deltaT = Attributes::getReal(itsAttr[T]);
948 949 950 951 952 953 954 955 956 957 958 959 960
                        } else {
                            double riseTime = Attributes::getReal(*(distributions.at(distIterator - 1)->findAttribute("TRISE")));
                            double fallTime = Attributes::getReal(*(distributions.at(distIterator - 1)->findAttribute("TFALL")));
                            
                            cutOff = Attributes::getReal(*(distributions.at(distIterator - 1)->findAttribute("CUTOFF")));
                            deltaT = Attributes::getReal(*(distributions.at(distIterator - 1)->findAttribute("T")));
                            
                            double timeRatio = sqrt(2.0 * log(10.0)) - sqrt(2.0 * log(10.0 / 9.0));
                            sigmaRiseTime = riseTime / timeRatio;
                            sigmaFallTime = fallTime / timeRatio;
                            
                            timeFlat = Attributes::getReal(*(distributions.at(distIterator - 1)->findAttribute("TPULSEFWHM")))
                                - sqrt(2.0 * log(2.0)) * (sigmaRiseTime + sigmaFallTime);
gsell's avatar
gsell committed
961
                        }
962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
                        if(timeFlat < 0.0) timeFlat = 0.0;
                        
                        const double totalArea = timeFlat + 0.5 * sqrt(2.0 * Physics::pi) * (sigmaRiseTime + sigmaFallTime);
                        
                        unsigned int numPartInRise = nParticles * 0.5 * gsl_sf_erf(cutOff / sqrt(2.0))
                            * sqrt(2.0 * Physics::pi) * sigmaRiseTime / totalArea;
                        unsigned int numPartInFall = nParticles * 0.5 * gsl_sf_erf(cutOff / sqrt(2.0))
                            * sqrt(2.0 * Physics::pi) * sigmaFallTime / totalArea;
                        unsigned int numPartInFlat = nParticles - numPartInRise - numPartInFall;
                        
                        if(timeFlat == 0.0) {
                            numPartInRise += numPartInFlat / 2;
                            numPartInFall = nParticles - numPartInRise;
                            numPartInFlat = 0;
                        }
                        
                        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);
                        }
                        
                        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);
                        }
                        
                        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
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 1046
                        }
                    }
                }

                // 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
1047 1048
        double x0   = x * sigx_m[0] + gauss_offset_m[0];
        px0 *= sigp_m[0]; 
gsell's avatar
gsell committed
1049 1050 1051 1052

        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
1053 1054
        double y0   =  x * sigx_m[1] + gauss_offset_m[1];
        py0 *= sigp_m[1];
gsell's avatar
gsell committed
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071

        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
1072 1073
        psi0 = avrgt_m + psi0 * sigx_m[2];
        del0 = avrgpt_m + sigp_m[2] * del0;
gsell's avatar
gsell committed
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 1130
        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
1131 1132
            x0   =  x * sigx_m[0];
            y0   =  y * sigx_m[1];
gsell's avatar
gsell committed
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 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197

            /*
              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);

    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
1198 1199
            x0   =  x * sigx_m[0];
            y0   =  y * sigx_m[1];
gsell's avatar
gsell committed
1200 1201 1202 1203 1204 1205 1206 1207 1208 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

            /*
              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) {

1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
    if(Options::rngtype != string("RANDOM")) {
        INFOMSG("RNGTYPE= " << Options::rngtype << endl);
        if(Options::rngtype == string("HALTON"))
            qrng_m = gsl_qrng_alloc(gsl_qrng_halton, 2);
        else if(Options::rngtype == string("SOBOL"))
            qrng_m = gsl_qrng_alloc(gsl_qrng_sobol, 2);
        else if(Options::rngtype == string("NIEDERREITER"))
            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
1251
        }
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
    }
    
    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;
    
    if(tFlat == 0.0) {
        nrise += nflat / 2;
        nfall = Np - nrise;
        nflat = 0;
    }
    
    // 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.
    
    gsl_qrng *Qrng = gsl_qrng_alloc(gsl_qrng_halton, 1);
    
    gsl_qrng *R2_m = gsl_qrng_alloc(gsl_qrng_halton, 2);
    
    // 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;
    
    // 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);
            
            r1 *= tFlat;
            
        } else {
            bool accept = false;
            while(!accept) {
                gsl_qrng_get(R2_m, rn);
gsell's avatar
gsell committed
1314
                // r1 = gsl_ran_flat(r, 0, tFlat);
1315
                /// r2 = gsl_ran_flat(r, 0, 1.0);
gsell's avatar
gsell committed
1316 1317 1318
                    r1 = rn[0] * tFlat;
                    r2 = rn[1];
                    double function = (1.0 + modulationAmplitude * sin(Physics::two_pi * r1 / modulationPeriod))
1319
                        / (1.0 + fabs(modulationAmplitude));
gsell's avatar
gsell committed
1320 1321 1322
                    if(r2 <= function) accept = true;
            }
        }
1323 1324 1325 1326 1327 1328 1329
        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
1330
    }
1331 1332
    gsl_qrng_free(Qrng);
    gsl_rng_free(r);
gsell's avatar
gsell committed
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
}

/**
 *
 *
 * @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
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369
    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]);
    
    sigx_m = Vector_t(Attributes::getReal(itsAttr[SIGMAX]),
                      Attributes::getReal(itsAttr[SIGMAY]),
                      Attributes::getReal(itsAttr[SIGMAT]));
    
gsell's avatar
gsell committed
1370 1371
    switch(distrTypeT_m) {

adelmann's avatar
adelmann committed
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
    case GUNGAUSSFLATTOPTH: {
        
        nBins_m = static_cast<int>(fabs(Attributes::getReal(itsAttr[NBIN])));
        
        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;
        tEmission_m = tPulseLengthFWHM_m + (cutoff_m - sqrt(2.0 * log(2.0))) * (sigmaRise_m + sigmaFall_m);

        ekin_m = Attributes::getReal(itsAttr[EKIN]);

        // EnvelopeTracker expects [eV]
        beamEnergy = ekin_m;
        beamWidth = tEmission_m * Physics::c * sqrt(1.0 - (1.0 / pow(gamma, 2)));
        
        break;
    }
    case GAUSS: {
        gauss_offset_m[0] = Attributes::getReal(itsAttr[OFFSETX]);
        gauss_offset_m[1] = Attributes::getReal(itsAttr[OFFSETY]);        
        avrgt_m  = Attributes::getReal(itsAttr[T]);

        beamEnergy = (gamma * mass - mass) * 1e9;         //FIXME: why 1e9??
        beamWidth = sigx_m[2];
        tEmission_m = 0.0;
        break;
    }
    default:
        ;
gsell's avatar
gsell committed
1405 1406 1407
    }

    center = -1 * beamWidth / 2.0;
adelmann's avatar
adelmann committed
1408
    *gmsg << "x = " << sigx_m[0] << " y = " << sigx_m[1] << endl;
gsell's avatar
gsell committed
1409 1410 1411
    double frac = 0.9;

    // execute initialization command
adelmann's avatar
adelmann committed
1412
    p->initialize(sl, charge, beamEnergy, beamWidth, tEmission_m, frac, current, center, sigx_m[0], sigx_m[1], 0, 0, Bz0, nBins_m);
gsell's avatar
gsell committed
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
    IpplTimings::stopTimer(p->distrCreate_m);
}

/**
 * restart and envelope tracker run
 *
 * @param beam
 * @param Np
 * @param restartStep
 */
void Distribution::doRestartEnvelope(EnvelopeBunch &beam, size_t Np, int restartStep) {
    h5_file_t *H5file;
    h5_int64_t rc;
    string fn;

    IpplTimings::startTimer(beam.distrReload_m);

    if(OpalData::getInstance()->hasRestartFile()) {
        fn = OpalData::getInstance()->getRestartFileName();
        *gmsg << "Restart from a specified file:" << fn << endl;

    } else {
        //        beam.setTEmission(Attributes::getReal(itsAttr[TEMISSION]));
1436
        fn = OpalData::getInstance()->getInputBasename() + string(".h5");
gsell's avatar
gsell committed
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467
    }

#ifdef PARALLEL_IO
    H5file = H5OpenFile(fn.c_str(), H5_O_RDONLY, Ippl::getComm());
#else
    H5file = H5PartOpenFile(fn.c_str(), H5_O_RDONLY, 0);
#endif

    if(!H5file) {
        ERRORMSG("could not open file '" << fn << "';  exiting!" << endl);
        exit(0);
    }

    if(restartStep == -1) {
        restartStep = H5GetNumSteps(H5file) - 1;
        OpalData::getInstance()->setRestartStep(restartStep);
    } else {
        if(restartStep != H5GetNumSteps(H5file) - 1 && !OpalData::getInstance()->hasRestartFile()) {
            ERRORMSG("can't append to the file '" << fn << "' exiting!" << endl);
            exit(0);
        }
    }

    rc = H5SetStep(H5file, restartStep);
    if(rc != H5_SUCCESS)
        ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
    int N = (int)H5PartGetNumParticles(H5file);

    h5_int64_t totalSteps = H5GetNumSteps(H5file);
    *gmsg << "total number of slices = " << N << " total steps " << totalSteps << endl;

1468 1469
    beam.distributeSlices(N);
    beam.createBunch();
gsell's avatar
gsell committed
1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490
    long long starti = beam.mySliceStartOffset();
    long long endi = beam.mySliceEndOffset();

    rc = H5PartSetView(H5file, starti, endi);
    if(rc != H5_SUCCESS)
        ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
    N = (int)H5PartGetNumParticles(H5file);
    assert(N >= 0 && (unsigned int) N != beam.numMySlices());

    double actualT;
    rc = H5ReadStepAttribFloat64(H5file, "TIME", &actualT);
    if(rc != H5_SUCCESS)
        ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);

    beam.setT(actualT);
    double dPhiGlobal;
    rc = H5ReadFileAttribFloat64(H5file, "dPhiGlobal", &dPhiGlobal);
    if(rc != H5_SUCCESS)
        ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
    OpalData::getInstance()->setGlobalPhaseShift(dPhiGlobal);

1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501
    h5_int64_t ltstep;
    rc = H5ReadStepAttribInt64(H5file, "LocalTrackStep", &ltstep);
    if(rc != H5_SUCCESS)
        ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
    beam.setLocalTrackStep((long long)ltstep);

    h5_int64_t gtstep;
    rc = H5ReadStepAttribInt64(H5file, "GlobalTrackStep", &gtstep);
    if(rc != H5_SUCCESS)
        ERRORMSG("H5 rc= " << rc << " in " << __FILE__ << " @ line " << __LINE__ << endl);
    beam.setGlobalTrackStep((long long)gtstep);
1502

1503 1504 1505
    std::unique_ptr<char[]> varray(new char[(N)*sizeof(double)]);
    double *farray = reinterpret_cast<double *>(varray.get());
    h5_int64_t *larray = reinterpret_cast<h5_int64_t *>(varray.get());
gsell's avatar
gsell committed
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768