SBend.cpp 48.3 KB
Newer Older
gsell's avatar
gsell committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
// ------------------------------------------------------------------------
// $RCSfile: SBend.cpp,v $
// ------------------------------------------------------------------------
// $Revision: 1.1.1.1 $
// ------------------------------------------------------------------------
// Copyright: see Copyright.readme
// ------------------------------------------------------------------------
//
// Definitions for class: SBend
//   Defines the abstract interface for a sector bend magnet.
//
// ------------------------------------------------------------------------
// Class category: AbsBeamline
// ------------------------------------------------------------------------
//
// $Date: 2000/03/27 09:32:31 $
// $Author: fci $
//
// ------------------------------------------------------------------------

#include "Algorithms/PartPusher.h"
#include "AbsBeamline/SBend.h"
23
#include "Algorithms/PartBunch.h"
gsell's avatar
gsell committed
24 25 26 27 28 29 30 31 32 33
#include "AbsBeamline/BeamlineVisitor.h"
#include "Fields/Fieldmap.hh"
#include <iostream>
#include <fstream>

// Class SBend
// ------------------------------------------------------------------------

SBend::SBend():
    Component(),
34
    pusher_m(),
35
    fileName_m(""),
gsell's avatar
gsell committed
36
    fieldmap_m(NULL),
kraus's avatar
kraus committed
37
    fast_m(false),
38 39 40 41 42
    angle_m(0.0),
    aperture_m(0.0),
    designEnergy_m(0.0),
    designRadius_m(0.0),
    fieldAmplitude_m(0.0),
43 44
    bX_m(0.0),
    bY_m(0.0),
45 46 47 48 49
    angleGreaterThanPi_m(false),
    entranceAngle_m(0.0),
    exitAngle_m(0.0),
    gradient_m(0.0),
    elementEdge_m(0.0),
gsell's avatar
gsell committed
50
    startField_m(0.0),
kraus's avatar
kraus committed
51
    endField_m(0.0),
52 53
    reinitialize_m(false),
    recalcRefTraj_m(false),
gsell's avatar
gsell committed
54 55
    length_m(0.0),
    gap_m(0.0),
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
    refTrajMapSize_m(0),
    refTrajMapStepSize_m(0.0),
    entranceParameter1_m(0.0),
    entranceParameter2_m(0.0),
    entranceParameter3_m(0.0),
    exitParameter1_m(0.0),
    exitParameter2_m(0.0),
    exitParameter3_m(0.0),
    xOriginEngeEntry_m(0.0),
    zOriginEngeEntry_m(0.0),
    deltaBeginEntry_m(0.0),
    deltaEndEntry_m(0.0),
    polyOrderEntry_m(0),
    xExit_m(0.0),
    zExit_m(0.0),
    xOriginEngeExit_m(0.0),
    zOriginEngeExit_m(0.0),
    deltaBeginExit_m(0.0),
    deltaEndExit_m(0.0),
    polyOrderExit_m(0),
    cosEntranceAngle_m(1.0),
    sinEntranceAngle_m(0.0),
    exitEdgeAngle_m(0.0),
    cosExitAngle_m(1.0),
    sinExitAngle_m(0.0) {
gsell's avatar
gsell committed
81 82 83 84 85
    setElType(isDipole);
}

SBend::SBend(const SBend &right):
    Component(right),
86
    pusher_m(right.pusher_m),
87
    fileName_m(right.fileName_m),
gsell's avatar
gsell committed
88
    fieldmap_m(right.fieldmap_m),
kraus's avatar
kraus committed
89
    fast_m(right.fast_m),
90 91 92 93 94
    angle_m(right.angle_m),
    aperture_m(right.aperture_m),
    designEnergy_m(right.designEnergy_m),
    designRadius_m(right.designRadius_m),
    fieldAmplitude_m(right.fieldAmplitude_m),
95 96
    bX_m(right.bX_m),
    bY_m(right.bY_m),
97 98 99 100 101
    angleGreaterThanPi_m(right.angleGreaterThanPi_m),
    entranceAngle_m(right.entranceAngle_m),
    exitAngle_m(right.exitAngle_m),
    gradient_m(right.gradient_m),
    elementEdge_m(right.elementEdge_m),
gsell's avatar
gsell committed
102 103
    startField_m(right.startField_m),
    endField_m(right.endField_m),
104 105
    reinitialize_m(right.reinitialize_m),
    recalcRefTraj_m(right.recalcRefTraj_m),
gsell's avatar
gsell committed
106 107
    length_m(right.length_m),
    gap_m(right.gap_m),
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
    refTrajMapX_m(right.refTrajMapX_m),
    refTrajMapY_m(right.refTrajMapY_m),
    refTrajMapZ_m(right.refTrajMapZ_m),
    refTrajMapSize_m(right.refTrajMapSize_m),
    refTrajMapStepSize_m(right.refTrajMapStepSize_m),
    entranceParameter1_m(right.entranceParameter1_m),
    entranceParameter2_m(right.entranceParameter2_m),
    entranceParameter3_m(right.entranceParameter3_m),
    exitParameter1_m(right.exitParameter1_m),
    exitParameter2_m(right.exitParameter2_m),
    exitParameter3_m(right.exitParameter3_m),
    xOriginEngeEntry_m(right.xOriginEngeEntry_m),
    zOriginEngeEntry_m(right.zOriginEngeEntry_m),
    deltaBeginEntry_m(right.deltaBeginEntry_m),
    deltaEndEntry_m(right.deltaEndEntry_m),
    polyOrderEntry_m(right.polyOrderEntry_m),
    xExit_m(right.xExit_m),
    zExit_m(right.zExit_m),
    xOriginEngeExit_m(right.xOriginEngeExit_m),
    zOriginEngeExit_m(right.zOriginEngeExit_m),
    deltaBeginExit_m(right.deltaBeginExit_m),
    deltaEndExit_m(right.deltaEndExit_m),
    polyOrderExit_m(right.polyOrderExit_m),
    cosEntranceAngle_m(right.cosEntranceAngle_m),
    sinEntranceAngle_m(right.sinEntranceAngle_m),
    exitEdgeAngle_m(right.exitEdgeAngle_m),
    cosExitAngle_m(right.cosExitAngle_m),
    sinExitAngle_m(right.sinExitAngle_m) {

gsell's avatar
gsell committed
137 138
    setElType(isDipole);

139
}
gsell's avatar
gsell committed
140

Steve Russell's avatar
Steve Russell committed
141
SBend::SBend(const std::string &name):
142
    Component(name),
143
    pusher_m(),
144
    fileName_m(""),
gsell's avatar
gsell committed
145
    fieldmap_m(NULL),
kraus's avatar
kraus committed
146
    fast_m(false),
147 148 149 150 151
    angle_m(0.0),
    aperture_m(0.0),
    designEnergy_m(0.0),
    designRadius_m(0.0),
    fieldAmplitude_m(0.0),
152 153
    bX_m(0.0),
    bY_m(0.0),
154 155 156 157 158
    angleGreaterThanPi_m(false),
    entranceAngle_m(0.0),
    exitAngle_m(0.0),
    gradient_m(0.0),
    elementEdge_m(0.0),
gsell's avatar
gsell committed
159 160
    startField_m(0.0),
    endField_m(0.0),
161 162
    reinitialize_m(false),
    recalcRefTraj_m(false),
gsell's avatar
gsell committed
163 164
    length_m(0.0),
    gap_m(0.0),
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
    refTrajMapSize_m(0),
    refTrajMapStepSize_m(0.0),
    entranceParameter1_m(0.0),
    entranceParameter2_m(0.0),
    entranceParameter3_m(0.0),
    exitParameter1_m(0.0),
    exitParameter2_m(0.0),
    exitParameter3_m(0.0),
    xOriginEngeEntry_m(0.0),
    zOriginEngeEntry_m(0.0),
    deltaBeginEntry_m(0.0),
    deltaEndEntry_m(0.0),
    polyOrderEntry_m(0),
    xExit_m(0.0),
    zExit_m(0.0),
    xOriginEngeExit_m(0.0),
    zOriginEngeExit_m(0.0),
    deltaBeginExit_m(0.0),
    deltaEndExit_m(0.0),
    polyOrderExit_m(0),
    cosEntranceAngle_m(1.0),
    sinEntranceAngle_m(0.0),
    exitEdgeAngle_m(0.0),
    cosExitAngle_m(1.0),
    sinExitAngle_m(0.0) {

gsell's avatar
gsell committed
191
    setElType(isDipole);
192

gsell's avatar
gsell committed
193 194 195 196 197 198 199 200 201
}

SBend::~SBend() {
}

void SBend::accept(BeamlineVisitor &visitor) const {
    visitor.visitSBend(*this);
}

202 203 204 205
/*
 * OPAL-MAP methods
 * ================
 */
gsell's avatar
gsell committed
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
double SBend::getNormalComponent(int n) const {
    return getField().getNormalComponent(n);
}

double SBend::getSkewComponent(int n) const {
    return getField().getSkewComponent(n);
}

void SBend::setNormalComponent(int n, double v) {
    getField().setNormalComponent(n, v);
}

void SBend::setSkewComponent(int n, double v) {
    getField().setSkewComponent(n, v);
}

222

223 224 225 226 227 228 229 230 231
/*
 * OPAL-T Methods.
 * ===============
 */

/*
 *  This function merely repackages the field arrays as type Vector_t and calls
 *  the equivalent method but with the Vector_t data types.
 */
232
bool SBend::apply(const size_t &i, const double &t, double E[], double B[]) {
233 234 235 236 237

    Vector_t Ev(0.0, 0.0, 0.0);
    Vector_t Bv(0.0, 0.0, 0.0);
    if(apply(RefPartBunch_m->R[i], RefPartBunch_m->get_rmean(), t, Ev, Bv))
        return true;
gsell's avatar
gsell committed
238 239 240 241 242 243 244 245 246 247 248

    E[0] = Ev(0);
    E[1] = Ev(1);
    E[2] = Ev(2);
    B[0] = Bv(0);
    B[1] = Bv(1);
    B[2] = Bv(2);

    return false;
}

249
bool SBend::apply(const size_t &i, const double &t, Vector_t &E, Vector_t &B) {
gsell's avatar
gsell committed
250

251
    if(designRadius_m > 0.0) {
gsell's avatar
gsell committed
252

253 254 255 256 257
        // Check if we need to reinitialize the bend field amplitude.
        if(reinitialize_m) {
            reinitialize_m = Reinitialize();
            recalcRefTraj_m = false;
        }
gsell's avatar
gsell committed
258

259 260 261 262 263 264 265 266 267 268 269 270 271
        /*
         * Always recalculate the reference trajectory on first call even
         * if we do not reinitialize the bend. The reference trajectory
         * has to be calculated at the same energy as the actual beam or
         * we do not get accurate values for the magnetic field in the output
         * file.
         */
        if(recalcRefTraj_m) {
            double angleX = 0.0;
            double angleY = 0.0;
            CalculateRefTrajectory(angleX, angleY);
            recalcRefTraj_m = false;
        }
gsell's avatar
gsell committed
272

273 274 275
        // Shift position to magnet frame.
        Vector_t X = RefPartBunch_m->X[i];
        X(2) += startField_m - elementEdge_m;
gsell's avatar
gsell committed
276

277 278 279 280 281 282
        /*
         * Add in transverse bend displacements. (ds is already
         * accounted for.)
         */
        X(0) -= dx_m;
        X(1) -= dy_m;
gsell's avatar
gsell committed
283

284 285 286 287 288
        // Get field from field map.
        Vector_t eField(0.0, 0.0, 0.0);
        Vector_t bField(0.0, 0.0, 0.0);
        CalculateMapField(X, eField, bField);
        bField *= fieldAmplitude_m;
gsell's avatar
gsell committed
289

290 291 292
        B(0) += bField(0);
        B(1) += bField(1);
        B(2) += bField(2);
gsell's avatar
gsell committed
293

294
    }
gsell's avatar
gsell committed
295

296 297
    return false;
}
gsell's avatar
gsell committed
298

299 300 301 302 303
bool SBend::apply(const Vector_t &R,
                  const Vector_t &centroid,
                  const double &t,
                  Vector_t &E,
                  Vector_t &B) {
gsell's avatar
gsell committed
304

305
    if(designRadius_m > 0.0) {
gsell's avatar
gsell committed
306

307 308
        int index = static_cast<int>
                    (std::floor((R(2) - startField_m) / refTrajMapStepSize_m));
gsell's avatar
gsell committed
309

310
        if(index > 0 && index + 1 < refTrajMapSize_m) {
gsell's avatar
gsell committed
311

312 313 314 315 316 317 318 319
            // Find indices for position in pre-computed central trajectory map.
            double lever = (R(2) - startField_m) / refTrajMapStepSize_m - index;
            double x = (1.0 - lever) * refTrajMapX_m.at(index)
                       + lever * refTrajMapX_m.at(index + 1);
            double y = (1.0 - lever) * refTrajMapY_m.at(index)
                       + lever * refTrajMapY_m.at(index + 1);
            double z = (1.0 - lever) * refTrajMapZ_m.at(index)
                       + lever * refTrajMapZ_m.at(index + 1);
gsell's avatar
gsell committed
320

321 322 323 324 325
            // Adjust position relative to pre-computed central trajectory map.
            Vector_t X(0.0, 0.0, 0.0);
            X(0) = R(0) + x;
            X(1) = R(1) + y;
            X(2) = z;
gsell's avatar
gsell committed
326

327 328 329
            Vector_t tempE(0.0, 0.0, 0.0);
            Vector_t tempB(0.0, 0.0, 0.0);
            Vector_t XInBendFrame = RotateToBendFrame(X);
gsell's avatar
gsell committed
330

331 332 333 334 335 336
            /*
             * Add in transverse bend displacements. (ds is already
             * accounted for.)
             */
            XInBendFrame(0) -= dx_m;
            XInBendFrame(1) -= dy_m;
gsell's avatar
gsell committed
337

338 339
            CalculateMapField(XInBendFrame, tempE, tempB);
            tempB = fieldAmplitude_m * RotateOutOfBendFrame(tempB);
gsell's avatar
gsell committed
340

341 342 343
            B(0) += tempB(0);
            B(1) += tempB(1);
            B(2) += tempB(2);
gsell's avatar
gsell committed
344

345 346
        }
    }
gsell's avatar
gsell committed
347

348
    return false;
gsell's avatar
gsell committed
349

350
}
gsell's avatar
gsell committed
351

352 353 354
bool SBend::bends() const {
    return true;
}
gsell's avatar
gsell committed
355

356 357 358
void SBend::finalise() {
    online_m = false;
}
gsell's avatar
gsell committed
359

360 361 362 363
void SBend::getDimensions(double &sBegin, double &sEnd) const {
    sBegin = startField_m;
    sEnd = endField_m;
}
gsell's avatar
gsell committed
364

365 366 367 368
const std::string &SBend::getType() const {
    static const std::string type("SBend");
    return type;
}
gsell's avatar
gsell committed
369

370 371 372 373
void SBend::initialise(PartBunch *bunch,
                       double &startField,
                       double &endField,
                       const double &scaleFactor) {
gsell's avatar
gsell committed
374

375
    Inform msg("SBend ");
gsell's avatar
gsell committed
376

377
    if(InitializeFieldMap(msg)) {
gsell's avatar
gsell committed
378

379 380 381 382 383 384 385 386
        SetupPusher(bunch);
        ReadFieldMap(msg);
        SetupBendGeometry(msg, startField, endField);
        double bendAngleX = 0.0;
        double bendAngleY = 0.0;
        CalculateRefTrajectory(bendAngleX, bendAngleY);
        recalcRefTraj_m = true;
        Print(msg, bendAngleX, bendAngleY);
387 388

        // Pass start and end of field to calling function.
gsell's avatar
gsell committed
389 390 391 392
        startField = startField_m;
        endField = endField_m;

    } else {
393 394 395 396
        msg << " There is something wrong with your field map \""
            << fileName_m
            << "\"";
        endField = startField - 1.0e-3;
gsell's avatar
gsell committed
397 398 399
    }
}

400 401
double SBend::GetBendAngle() const {
    return angle_m;
gsell's avatar
gsell committed
402 403
}

404 405
double SBend::GetBendRadius() const {
    return designRadius_m;
gsell's avatar
gsell committed
406 407
}

408 409
double SBend::GetEffectiveCenter() const {
    return elementEdge_m + designRadius_m * angle_m / 2.0;
410 411
}

412 413
double SBend::GetEffectiveLength() const {
    return designRadius_m * angle_m;
gsell's avatar
gsell committed
414 415
}

416 417
std::string SBend::GetFieldMapFN() const {
    return fileName_m;
418 419
}

420 421
double SBend::GetStartElement() const {
    return elementEdge_m;
gsell's avatar
gsell committed
422 423
}

424 425
void SBend::SetAngleGreaterThanPiFlag(bool angleGreaterThanPi) {
    angleGreaterThanPi_m = angleGreaterThanPi;
gsell's avatar
gsell committed
426 427
}

428 429
void SBend::SetAperture(double aperture) {
    aperture_m = std::abs(aperture);
gsell's avatar
gsell committed
430 431
}

432 433
void SBend::SetBendAngle(double angle) {
    angle_m = angle;
gsell's avatar
gsell committed
434 435
}

436 437
void SBend::SetBeta(double beta) {
    Orientation_m(1) = beta;
gsell's avatar
gsell committed
438 439
}

440 441
void SBend::SetDesignEnergy(double energy) {
    designEnergy_m = std::abs(energy);
gsell's avatar
gsell committed
442 443
}

444 445 446
void SBend::SetEntranceAngle(double entranceAngle) {
    entranceAngle_m = entranceAngle;
}
gsell's avatar
gsell committed
447

448 449
void SBend::setExitAngle(double exitAngle) {
    exitAngle_m = exitAngle;
450
}
gsell's avatar
gsell committed
451

452 453 454
void SBend::SetFieldAmplitude(double k0, double k0s) {
    bY_m = k0;
    bX_m = k0s;
455
}
gsell's avatar
gsell committed
456

457 458
void SBend::SetFieldMapFN(std::string fileName) {
    fileName_m = fileName;
459
}
Steve Russell's avatar
Steve Russell committed
460

461 462
void SBend::SetFullGap(double gap) {
    gap_m = std::abs(gap);
463
}
gsell's avatar
gsell committed
464

465
void SBend::SetK1(double k1) {
466 467
    gradient_m = k1;
}
gsell's avatar
gsell committed
468

469 470
void SBend::SetLength(double length) {
    length_m = std::abs(length);
471
}
Steve Russell's avatar
Steve Russell committed
472

473 474
void SBend::SetRotationAboutZ(double rotation) {
    Orientation_m(2) = rotation;
475
}
Steve Russell's avatar
Steve Russell committed
476

477
void SBend::AdjustFringeFields(double ratio) {
gsell's avatar
gsell committed
478

479 480 481 482 483 484 485 486 487 488 489
    double delta = std::abs(entranceParameter1_m - entranceParameter2_m);
    entranceParameter1_m = entranceParameter2_m - delta * ratio;

    delta = std::abs(entranceParameter2_m - entranceParameter3_m);
    entranceParameter3_m = entranceParameter2_m + delta * ratio;

    delta = std::abs(exitParameter1_m - exitParameter2_m);
    exitParameter1_m = exitParameter2_m - delta * ratio;

    delta = std::abs(exitParameter2_m - exitParameter3_m);
    exitParameter3_m = exitParameter2_m + delta * ratio;
Steve Russell's avatar
Steve Russell committed
490

gsell's avatar
gsell committed
491 492
}

493
double SBend::CalculateBendAngle() {
gsell's avatar
gsell committed
494 495

    const double mass = RefPartBunch_m->getM();
496
    const double gamma = designEnergy_m / mass + 1.0;
gsell's avatar
gsell committed
497
    const double betaGamma = sqrt(pow(gamma, 2.0) - 1.0);
498
    const double beta = betaGamma / gamma;
gsell's avatar
gsell committed
499 500 501
    const double deltaT = RefPartBunch_m->getdT();

    // Integrate through field for initial angle.
502 503 504 505
    Vector_t X(0.0, 0.0, startField_m - elementEdge_m);
    Vector_t P(0.0, 0.0, betaGamma);
    double deltaS = 0.0;
    double bendLength = endField_m - startField_m;
gsell's avatar
gsell committed
506

507
    while(deltaS < bendLength) {
gsell's avatar
gsell committed
508 509 510 511 512

        X /= Vector_t(Physics::c * deltaT);
        pusher_m.push(X, P, deltaT);
        X *= Vector_t(Physics::c * deltaT);

513 514 515 516
        Vector_t eField(0.0, 0.0, 0.0);
        Vector_t bField(0.0, 0.0, 0.0);
        CalculateMapField(X, eField, bField);
        bField = fieldAmplitude_m * bField;
gsell's avatar
gsell committed
517 518

        X /= Vector_t(Physics::c * deltaT);
519
        pusher_m.kick(X, P, eField, bField, deltaT);
gsell's avatar
gsell committed
520 521 522 523

        pusher_m.push(X, P, deltaT);
        X *= Vector_t(Physics::c * deltaT);

524
        deltaS += deltaT * beta * Physics::c;
gsell's avatar
gsell committed
525

526
    }
gsell's avatar
gsell committed
527

528
    double angle =  -atan2(P(0), P(2));
gsell's avatar
gsell committed
529

530
    return angle;
gsell's avatar
gsell committed
531

532
}
gsell's avatar
gsell committed
533

534 535 536 537
void SBend::CalcCentralField(Vector_t R,
                             double deltaX,
                             double angle,
                             Vector_t &B) {
gsell's avatar
gsell committed
538

539 540 541
    B(0) = -gradient_m * R(1) * cos(angle) / designRadius_m;
    B(1) = 1.0 - gradient_m * deltaX / designRadius_m;
    B(2) = -gradient_m * R(1) * sin(angle) / designRadius_m;
gsell's avatar
gsell committed
542

543
}
gsell's avatar
gsell committed
544

545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
void SBend::CalcEngeFunction(double zNormalized,
                             std::vector<double> engeCoeff,
                             int polyOrder,
                             double &engeFunc,
                             double &engeFuncDeriv,
                             double &engeFuncSecDeriv) {

    double expSum = 0.0;
    double expSumDeriv = 0.0;
    double expSumSecDeriv = 0.0;

    if(polyOrder >= 2) {

        expSum = engeCoeff.at(0)
                 + engeCoeff.at(1) * zNormalized;
        expSumDeriv = engeCoeff.at(1);

        for(int index = 2; index <= polyOrder; index++) {
            expSum += engeCoeff.at(index) * pow(zNormalized, index);
            expSumDeriv += index * engeCoeff.at(index)
                           * pow(zNormalized, index - 1);
            expSumSecDeriv += index * (index - 1) * engeCoeff.at(index)
                              * pow(zNormalized, index - 2);
gsell's avatar
gsell committed
568 569
        }

570
    } else if(polyOrder == 1) {
Steve Russell's avatar
Steve Russell committed
571

572 573 574
        expSum = engeCoeff.at(0)
                 + engeCoeff.at(1) * zNormalized;
        expSumDeriv = engeCoeff.at(1);
gsell's avatar
gsell committed
575

576 577 578 579 580
    } else
        expSum = engeCoeff.at(0);

    expSumDeriv /= gap_m;
    expSumSecDeriv /= pow(gap_m, 2.0);
gsell's avatar
gsell committed
581

582 583 584
    double engeExp = exp(expSum);
    double engeExpDeriv = expSumDeriv * engeExp;
    double engeExpSecDeriv = (expSumSecDeriv + pow(expSumDeriv, 2.0)) * engeExp;
gsell's avatar
gsell committed
585

586 587 588 589 590
    engeFunc = 1.0 / (1.0 + engeExp);
    if(engeFunc > 1.0e-30) {
        engeFuncDeriv = -engeExpDeriv * pow(engeFunc, 2.0);
        engeFuncSecDeriv = -engeExpSecDeriv * pow(engeFunc, 2.0)
                           + 2.0 * pow(engeExpDeriv, 2.0) * pow(engeFunc, 3.0);
591
    } else {
592 593 594
        engeFunc = 0.0;
        engeFuncDeriv = 0.0;
        engeFuncSecDeriv = 0.0;
gsell's avatar
gsell committed
595 596
    }

597
}
gsell's avatar
gsell committed
598

599 600 601
void SBend::CalcEntranceFringeField(Vector_t REntrance,
                                    double deltaX,
                                    Vector_t &B) {
gsell's avatar
gsell committed
602

603 604 605 606
    double zNormalized = -REntrance(2) / gap_m;
    double engeFunc = 0.0;
    double engeFuncDeriv = 0.0;
    double engeFuncSecDeriv = 0.0;
gsell's avatar
gsell committed
607

608 609 610 611 612 613
    CalcEngeFunction(zNormalized,
                     engeCoeffsEntry_m,
                     polyOrderEntry_m,
                     engeFunc,
                     engeFuncDeriv,
                     engeFuncSecDeriv);
gsell's avatar
gsell committed
614

615 616 617 618 619
    double bXEntrance = -(engeFunc - (engeFuncSecDeriv / 2.0) * pow(REntrance(1), 2.0))
                        * gradient_m * REntrance(1) / designRadius_m;
    double bYEntrance = engeFunc - (engeFuncSecDeriv / 2.0) * pow(REntrance(1), 2.0)
                        * (1.0 - gradient_m * deltaX / designRadius_m);
    double bZEntrance = -engeFuncDeriv * REntrance(1);
gsell's avatar
gsell committed
620

621 622 623
    B(0) = bXEntrance * cosEntranceAngle_m - bZEntrance * sinEntranceAngle_m;
    B(1) = bYEntrance;
    B(2) = bXEntrance * sinEntranceAngle_m + bZEntrance * cosEntranceAngle_m;
gsell's avatar
gsell committed
624 625 626

}

627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
void SBend::CalcExitFringeField(Vector_t RExit, double deltaX, Vector_t &B) {

    double zNormalized = RExit(2) / gap_m;
    double engeFunc = 0.0;
    double engeFuncDeriv = 0.0;
    double engeFuncSecDeriv = 0.0;
    CalcEngeFunction(zNormalized,
                     engeCoeffsExit_m,
                     polyOrderExit_m,
                     engeFunc,
                     engeFuncDeriv,
                     engeFuncSecDeriv);

    double bXExit = -(engeFunc - (engeFuncSecDeriv / 2.0) * pow(RExit(1), 2.0))
                    * gradient_m * RExit(1) / designRadius_m;
    double bYExit = engeFunc - (engeFuncSecDeriv / 2.0) * pow(RExit(1), 2.0)
                    * (1.0 - gradient_m * deltaX / designRadius_m);
    double bZExit = engeFuncDeriv * RExit(1);

    B(0) = bXExit * cosExitAngle_m - bZExit * sinExitAngle_m;
    B(1) = bYExit;
    B(2) = bXExit * sinExitAngle_m + bZExit * cosExitAngle_m;
gsell's avatar
gsell committed
649

650
}
gsell's avatar
gsell committed
651

652
void SBend::CalculateMapField(Vector_t R, Vector_t &E, Vector_t &B) {
gsell's avatar
gsell committed
653

654 655
    E = Vector_t(0.0);
    B = Vector_t(0.0);
gsell's avatar
gsell committed
656

657 658 659 660 661 662 663 664 665
    //    Vector_t REntrance(0.0, 0.0, 0.0);
    //    Vector_t RExit(0.0, 0.0, 0.0);
    //    if (IsPositionInEntranceField(R, REntrance)) {
    //        CalcEntranceFringeField(REntrance, 0.0, B);
    //    } else if (IsPositionInExitField(R, RExit)) {
    //        CalcExitFringeField(RExit, 0.0, B);
    //    } else {
    //        CalcCentralField(R, 0.0, 0.0, B);
    //    }
gsell's avatar
gsell committed
666

667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
    double deltaXEntrance = 0.0;
    double deltaXExit = 0.0;
    bool inEntranceRegion = InMagnetEntranceRegion(R, deltaXEntrance);
    bool inExitRegion = InMagnetExitRegion(R, deltaXExit);

    if(!inEntranceRegion && !inExitRegion) {

        double deltaX = 0.0;
        double angle = 0.0;
        if(InMagnetCentralRegion(R, deltaX, angle)) {
            Vector_t REntrance(0.0, 0.0, 0.0);
            Vector_t RExit(0.0, 0.0, 0.0);
            if(IsPositionInEntranceField(R, REntrance))
                CalcEntranceFringeField(REntrance, deltaX, B);
            else if(IsPositionInExitField(R, RExit))
                CalcExitFringeField(RExit, deltaX, B);
            else
                CalcCentralField(R, deltaX, angle, B);
gsell's avatar
gsell committed
685

686
        }
gsell's avatar
gsell committed
687

688
    } else if(inEntranceRegion && !inExitRegion) {
gsell's avatar
gsell committed
689

690 691 692 693 694
        Vector_t REntrance(0.0, 0.0, 0.0);
        if(IsPositionInEntranceField(R, REntrance)) {
            CalcEntranceFringeField(REntrance, deltaXEntrance, B);
        } else if(REntrance(2) > 0.0)
            CalcCentralField(R, deltaXEntrance, 0.0, B);
gsell's avatar
gsell committed
695

696
    } else if(!inEntranceRegion && inExitRegion) {
gsell's avatar
gsell committed
697

698 699 700 701 702
        Vector_t RExit(0.0, 0.0, 0.0);
        if(IsPositionInExitField(R, RExit)) {
            CalcExitFringeField(RExit, deltaXExit, B);
        } else if(RExit(2) < 0.0)
            CalcCentralField(R, deltaXExit, angle_m, B);
gsell's avatar
gsell committed
703

704
    } else if(inEntranceRegion && inExitRegion) {
gsell's avatar
gsell committed
705

706 707 708 709 710 711 712 713 714 715
        /*
         * This is an unusual condition and should only happen with
         * a sector magnet that bends more than 180 degrees. Here, we
         * have the possibility that the particle sees both the
         * entrance and exit fringe fields.
         */
        Vector_t BEntrance(0.0, 0.0, 0.0);
        Vector_t REntrance(0.0, 0.0, 0.0);
        if(IsPositionInEntranceField(R, REntrance))
            CalcEntranceFringeField(REntrance, deltaXEntrance, BEntrance);
716

717 718 719 720
        Vector_t BExit(0.0, 0.0, 0.0);
        Vector_t RExit(0.0, 0.0, 0.0);
        if(IsPositionInExitField(R, RExit))
            CalcExitFringeField(RExit, deltaXExit, BExit);
721

722 723 724
        B(0) = BEntrance(0) + BExit(0);
        B(1) = BEntrance(1) + BExit(1);
        B(2) = BEntrance(2) + BExit(2);
725 726 727 728

    }
}

729
void SBend::CalculateRefTrajectory(double &angleX, double &angleY) {
730 731

    const double mass = RefPartBunch_m->getM();
732
    const double gamma = designEnergy_m / mass + 1.;
733 734 735
    const double betaGamma = sqrt(gamma * gamma - 1.);
    const double dt = RefPartBunch_m->getdT();

736 737
    Vector_t X(0.0, 0.0, startField_m - elementEdge_m);
    Vector_t P(0.0, 0.0, betaGamma);
738

739 740 741 742 743 744
    if(!refTrajMapX_m.empty())
        refTrajMapX_m.clear();
    if(!refTrajMapY_m.empty())
        refTrajMapY_m.clear();
    if(!refTrajMapZ_m.empty())
        refTrajMapZ_m.clear();
745

746 747 748
    refTrajMapX_m.push_back(X(0));
    refTrajMapY_m.push_back(X(1));
    refTrajMapZ_m.push_back(X(2));
749

750 751 752
    refTrajMapStepSize_m = betaGamma / gamma * Physics::c * dt;
    double deltaS = 0.0;
    double bendLength = endField_m - startField_m;
753

754
    while(deltaS < bendLength) {
755 756 757 758 759

        X /= Vector_t(Physics::c * dt);
        pusher_m.push(X, P, dt);
        X *= Vector_t(Physics::c * dt);

760 761 762 763 764 765 766 767 768 769 770 771 772 773
        Vector_t eField(0.0, 0.0, 0.0);
        Vector_t bField(0.0, 0.0, 0.0);
        Vector_t XInBendFrame = RotateToBendFrame(X);

        /*
         * Add in transverse bend displacements. (ds is already
         * accounted for.)
         */
        XInBendFrame(0) -= dx_m;
        XInBendFrame(1) -= dy_m;

        CalculateMapField(XInBendFrame, eField, bField);
        bField = fieldAmplitude_m * RotateOutOfBendFrame(bField);

774
        X /= Vector_t(Physics::c * dt);
775 776
        pusher_m.kick(X, P, eField, bField, dt);

777 778 779
        pusher_m.push(X, P, dt);
        X *= Vector_t(Physics::c * dt);

780 781 782 783 784 785
        refTrajMapX_m.push_back(X(0));
        refTrajMapY_m.push_back(X(1));
        refTrajMapZ_m.push_back(X(2));

        deltaS += refTrajMapStepSize_m;

786 787
    }

788
    refTrajMapSize_m = refTrajMapX_m.size();
789

790 791 792 793 794
    if(Orientation_m(2) == Physics::pi / 2.0
       || Orientation_m(2) == 3.0 * Physics::pi / 2.0)
        angleX = 0.0;
    else
        angleX = -atan2(P(0), P(2));
795

796 797 798 799 800
    if(Orientation_m(2) == 0.0
       || Orientation_m(2) == Physics::pi)
        angleY = 0.0;
    else
        angleY = atan2(P(1), P(2));
801 802 803

}

804 805 806
double SBend::EstimateFieldAdjustmentStep(double actualBendAngle,
        double mass,
        double betaGamma) {
807

808 809
    double amplitude1 = fieldAmplitude_m;
    double bendAngle1 = actualBendAngle;
810

811 812 813 814 815 816
    // Estimate field adjustment step.
    double effectiveLength = angle_m * designRadius_m;
    double fieldStep = (angle_m - bendAngle1) * betaGamma * mass / (2.0 * effectiveLength * Physics::c);
    if(pow(fieldAmplitude_m * effectiveLength * Physics::c / (betaGamma * mass), 2.0) < 1.0)
        fieldStep = (angle_m - bendAngle1) * betaGamma * mass / (2.0 * effectiveLength * Physics::c)
                    * std::sqrt(1.0 - pow(fieldAmplitude_m * effectiveLength * Physics::c / (betaGamma * mass), 2.0));
817

818
    fieldStep *= amplitude1 / std::abs(amplitude1);
819

820
    return fieldStep;
821 822 823

}

824
void SBend::FindBendEffectiveLength(double startField, double endField) {
825

826 827 828 829 830 831 832 833
    /*
     * Use an iterative procedure to set the width of the
     * default field map for the defined field amplitude
     * and bend angle.
     */
    SetEngeOriginDelta(0.0);
    SetFieldCalcParam(false);
    SetFieldBoundaries(startField, endField);
834

835 836
    double actualBendAngle = CalculateBendAngle();
    double error = std::abs(actualBendAngle - angle_m);
837 838

    if(error > 1.0e-6) {
gsell's avatar
gsell committed
839

840 841 842 843 844 845 846
        double deltaStep = 0.0;
        if(std::abs(actualBendAngle) < std::abs(angle_m))
            deltaStep = -gap_m / 2.0;
        else
            deltaStep = gap_m / 2.0;

        double delta1 = 0.0;
847 848
        double bendAngle1 = actualBendAngle;

849 850 851 852 853 854 855 856 857 858 859 860 861
        double delta2 = deltaStep;
        SetEngeOriginDelta(delta2);
        SetFieldCalcParam(false);
        SetFieldBoundaries(startField, endField);
        double bendAngle2 = CalculateBendAngle();

        if(std::abs(bendAngle1) > std::abs(angle_m)) {
            while(std::abs(bendAngle2) > std::abs(angle_m)) {
                delta2 += deltaStep;
                SetEngeOriginDelta(delta2);
                SetFieldCalcParam(false);
                SetFieldBoundaries(startField, endField);
                bendAngle2 = CalculateBendAngle();
862 863
            }
        } else {
864 865 866 867 868 869
            while(std::abs(bendAngle2) < std::abs(angle_m)) {
                delta2 += deltaStep;
                SetEngeOriginDelta(delta2);
                SetFieldCalcParam(false);
                SetFieldBoundaries(startField, endField);
                bendAngle2 = CalculateBendAngle();
870 871 872
            }
        }

873
        // Now we should have the proper field map width bracketed.
874
        unsigned int iterations = 1;
875 876
        double delta = 0.0;
        error = std::abs(actualBendAngle - angle_m);
877 878
        while(error > 1.0e-6 && iterations < 100) {

879 880 881 882 883
            delta = (delta1 + delta2) / 2.0;
            SetEngeOriginDelta(delta);
            SetFieldCalcParam(false);
            SetFieldBoundaries(startField, endField);
            double newBendAngle = CalculateBendAngle();
884

885
            error = std::abs(newBendAngle - angle_m);
886 887 888 889 890 891 892

            if(error > 1.0e-6) {

                if(bendAngle1 - angle_m < 0.0) {

                    if(newBendAngle - angle_m < 0.0) {
                        bendAngle1 = newBendAngle;
893
                        delta1 = delta;
894 895
                    } else {
                        bendAngle2 = newBendAngle;
896
                        delta2 = delta;
897 898 899 900 901 902
                    }

                } else {

                    if(newBendAngle - angle_m < 0.0) {
                        bendAngle2 = newBendAngle;
903
                        delta2 = delta;
904 905
                    } else {
                        bendAngle1 = newBendAngle;
906
                        delta1 = delta;
907 908 909 910 911 912 913
                    }
                }
            }
            iterations++;
        }
    }
}
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 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 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

void SBend::FindBendStrength(double mass,
                             double gamma,
                             double betaGamma,
                             double charge) {

    /*
     * Use an iterative procedure to set the magnet field amplitude
     * for the defined bend angle.
     */
    double actualBendAngle = CalculateBendAngle();
    double fieldStep = EstimateFieldAdjustmentStep(actualBendAngle,
                       mass,
                       betaGamma);
    double amplitude1 = fieldAmplitude_m;
    double bendAngle1 = actualBendAngle;

    double amplitude2 = fieldAmplitude_m + fieldStep;
    fieldAmplitude_m = amplitude2;
    double bendAngle2 = CalculateBendAngle();

    if(std::abs(bendAngle1) > std::abs(angle_m)) {
        while(std::abs(bendAngle2) > std::abs(angle_m)) {
            amplitude2 += fieldStep;
            fieldAmplitude_m = amplitude2;
            bendAngle2 = CalculateBendAngle();
        }
    } else {
        while(std::abs(bendAngle2) < std::abs(angle_m)) {
            amplitude2 += fieldStep;
            fieldAmplitude_m = amplitude2;
            bendAngle2 = CalculateBendAngle();
        }
    }

    // Now we should have the proper field amplitude bracketed.
    unsigned int iterations = 1;
    double error = std::abs(actualBendAngle - angle_m);
    while(error > 1.0e-6 && iterations < 100) {

        fieldAmplitude_m = (amplitude1 + amplitude2) / 2.0;
        double newBendAngle = CalculateBendAngle();

        error = std::abs(newBendAngle - angle_m);

        if(error > 1.0e-6) {

            if(bendAngle1 - angle_m < 0.0) {

                if(newBendAngle - angle_m < 0.0) {
                    bendAngle1 = newBendAngle;
                    amplitude1 = fieldAmplitude_m;
                } else {
                    bendAngle2 = newBendAngle;
                    amplitude2 = fieldAmplitude_m;
                }

            } else {

                if(newBendAngle - angle_m < 0.0) {
                    bendAngle2 = newBendAngle;
                    amplitude2 = fieldAmplitude_m;
                } else {
                    bendAngle1 = newBendAngle;
                    amplitude1 = fieldAmplitude_m;
                }
            }
        }
        iterations++;
    }
}

bool SBend::FindChordLength(Inform &msg,
                            double &chordLength,
                            bool &chordLengthFromMap) {

    /*
     * Find bend chord length. If this was not set by the user using the
     * L (length) attribute, infer it from the field map.
     */
    chordLength = length_m;
    if(chordLength > 0.0) {
        chordLengthFromMap = false;
        return true;
    } else {

        if(chordLength == 0.0)
            chordLength = exitParameter2_m - entranceParameter2_m;

        chordLengthFromMap = true;

        if(chordLength <= 0.0) {
            msg << "Magnet length inferred from field map is less than or equal"
                " to zero. Check your bend magnet input."
                << endl;
            return false;
        } else
            return true;

    }
}

bool SBend::FindIdealBendParameters(double chordLength) {

    double refMass = RefPartBunch_m->getM();
    double refGamma = designEnergy_m / refMass + 1.0;
    double refBetaGamma = sqrt(pow(refGamma, 2.0) - 1.0);
    double refCharge = RefPartBunch_m->getQ();

    if(angle_m != 0.0) {

        if(angle_m < 0.0) {
            // Negative angle is a positive bend rotated 180 degrees.
            angle_m = std::abs(angle_m);
            gradient_m *= -1.0;
            Orientation_m(2) += Physics::pi;
        }
        designRadius_m = chordLength / (2.0 * std::sin(angle_m / 2.0));
        fieldAmplitude_m = (refCharge / std::abs(refCharge))
                           * refBetaGamma * refMass
                           / (Physics::c * designRadius_m);
        return true;

1037
    } else if(bX_m == 0.0) {
1038 1039

        // Negative angle is a positive bend rotated 180 degrees.
1040 1041
        if((refCharge > 0.0 && bY_m < 0.0)
           || (refCharge < 0.0 && bY_m > 0.0)) {
1042 1043 1044 1045
            gradient_m *= -1.0;
            Orientation_m(2) += Physics::pi;
        }

1046
        fieldAmplitude_m = refCharge * std::abs(bY_m / refCharge);
1047 1048 1049 1050 1051 1052 1053 1054 1055
        designRadius_m = std::abs(refBetaGamma * refMass / (Physics::c * fieldAmplitude_m));
        double bendAngle = 2.0 * std::asin(chordLength / (2.0 * designRadius_m));

        if(angleGreaterThanPi_m)
            bendAngle = 2.0 * Physics::pi - bendAngle;

        angle_m = bendAngle;
        return false;

1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
    } else {

        Orientation_m(2) += atan2(bX_m, bY_m);
        if(refCharge < 0.0) {
            gradient_m *= -1.0;
            Orientation_m(2) -= Physics::pi;
        }

        fieldAmplitude_m = refCharge
                           * std::abs(sqrt(pow(bY_m, 2.0) + pow(bX_m, 2.0))
                                      / refCharge);
        designRadius_m = std::abs(refBetaGamma * refMass / (Physics::c * fieldAmplitude_m));
        double bendAngle = 2.0 * std::asin(chordLength / (2.0 * designRadius_m));

        if(angleGreaterThanPi_m)
            bendAngle = 2.0 * Physics::pi - bendAngle;

        angle_m = bendAngle;

        return false;
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 1131 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 1168 1169 1170 1171 1172