SBend.cpp 48.4 KB
Newer Older
gsell's avatar
gsell committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
// ------------------------------------------------------------------------
// $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 "AbsBeamline/SBend.h"
kraus's avatar
kraus committed
22
#include "Algorithms/PartPusher.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 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 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
    }
}

void SBend::FindReferenceExitOrigin(double &x, double &z) {

    /*
      * Find x,z coordinates of reference trajectory as it passes exit edge
      * of the bend magnet. This assumes an entrance position of (x,z) = (0,0).
      */
    if(angle_m <= Physics::pi / 2.0) {
        x = - designRadius_m * (1.0 - std::cos(angle_m));
        z = designRadius_m * std::sin(angle_m);
    } else if(angle_m <= Physics::pi) {
        x = -designRadius_m * (1.0 + std::sin(angle_m - Physics::pi / 2.0));
        z = designRadius_m * std::cos(angle_m - Physics::pi / 2.0);
    } else if(angle_m <= 3.0 * Physics::pi / 2.0) {
        x = -designRadius_m * (2.0 - std::cos(angle_m - Physics::pi));
        z = -designRadius_m * std::sin(angle_m - Physics::pi);
    } else {
        x = -designRadius_m * (1.0 - std::cos(angle_m - 3.0 * Physics::pi / 2.0));
        z = -designRadius_m * std::sin(angle_m - 3.0 * Physics::pi / 2.0);
    }
}

bool SBend::InitializeFieldMap(Inform &msg) {

    fieldmap_m = Fieldmap::getFieldmap(fileName_m, fast_m);

    if(fieldmap_m != NULL) {
        if(fileName_m != "1DPROFILE1-DEFAULT")
            return true;
        else
            return SetupDefaultFieldMap(msg);

    } else
        return false;

}

bool SBend::InMagnetCentralRegion(Vector_t R, double &deltaX, double &angle) {

    deltaX = sqrt(pow(R(2), 2.0) + pow(R(0) + designRadius_m, 2.0)) - designRadius_m;
    if(std::abs(deltaX) <= aperture_m / 2.0) {

        angle = atan2(R(2), R(0) + designRadius_m);
        return true;

    } else
        return false;

}

bool SBend::InMagnetEntranceRegion(Vector_t R, double &deltaX) {

    if(std::abs(R(0) <= aperture_m / 2.0)) {

        Vector_t RTransformed(0.0, R(1), 0.0);
        RTransformed(0) = (R(0) - xOriginEngeEntry_m) * cosEntranceAngle_m
                          + (R(2) - zOriginEngeEntry_m) * sinEntranceAngle_m;
        RTransformed(2) = -(R(0) - xOriginEngeEntry_m) * sinEntranceAngle_m
                          + (R(2) - zOriginEngeEntry_m) * cosEntranceAngle_m;

        if(RTransformed(2) <= 0.0) {
            deltaX = R(0);
            return true;
        } else
            return false;

    } else
        return false;

}

bool SBend::InMagnetExitRegion(Vector_t R, double &deltaX) {

    Vector_t RTransformed(0.0, R(1), 0.0);
    RTransformed(0) = (R(0) - xExit_m) * cosExitAngle_m
                      + (R(2) - zExit_m) * sinExitAngle_m;
    RTransformed(2) = -(R(0) - xExit_m) * sinExitAngle_m
                      + (R(2) - zExit_m) * cosExitAngle_m;

    if(RTransformed(2) >= 0.0) {

        deltaX = (R(0) - xExit_m) * cos(angle_m)
                 + (R(2) - zExit_m) * sin(angle_m);
        if(std::abs(deltaX) <= aperture_m / 2.0)
            return true;
        else
            return false;

    } else
        return false;
}

bool SBend::IsPositionInEntranceField(Vector_t R, Vector_t &REntrance) {

    REntrance(1) = R(1);

    REntrance(0) = (R(0) - xOriginEngeEntry_m) * cosEntranceAngle_m
                   + (R(2) - zOriginEngeEntry_m) * sinEntranceAngle_m;
    REntrance(2) = -(R(0) - xOriginEngeEntry_m) * sinEntranceAngle_m
                   + (R(2) - zOriginEngeEntry_m) * cosEntranceAngle_m;

    if(REntrance(2) >= -deltaBeginEntry_m && REntrance(2) <= deltaEndEntry_m)
        return true;
    else
        return false;
}

bool SBend::IsPositionInExitField(Vector_t R, Vector_t &RExit) {

    RExit(1) = R(1);

    RExit(0) = (R(0) - xOriginEngeExit_m) * cosExitAngle_m
               + (R(2) - zOriginEngeExit_m) * sinExitAngle_m;
    RExit(2) = -(R(0) - xOriginEngeExit_m) * sinExitAngle_m
               + (R(2) - zOriginEngeExit_m) * cosExitAngle_m;

    if(RExit(2) >= -deltaBeginExit_m && RExit(2) <= deltaEndExit_m)
        return true;
    else
        return false;

}

void SBend::Print(Inform &msg, double bendAngleX, double bendAngleY) {

    msg << endl
        << "Start of field map:      "
        << startField_m
        << " m (in s coordinates)"
        << endl;
    msg << "End of field map:        "
        << endField_m
        << " m (in s coordinates)"
        << endl;
    msg << "Entrance edge of magnet: "
        << elementEdge_m
        << " m (in s coordinates)"
        << endl;
    msg << endl
1217
        << "Reference Trajectory Properties"
1218
        << endl
1219
        << "==============================="
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
        << endl << endl;
    msg << "Bend angle magnitude:    "
        << angle_m
        << " rad ("
        << angle_m * 180.0 / Physics::pi
        << " degrees)"
        << endl;
    msg << "Entrance edge angle:     "
        << entranceAngle_m
        << " rad ("
        << entranceAngle_m * 180.0 / Physics::pi
        << " degrees)"
        << endl;
    msg << "Exit edge angle:         "
        << exitAngle_m
        << " rad ("
        << exitAngle_m * 180.0 / Physics::pi
        << " degrees)"
        << endl;
    msg << "Bend design radius:      "
        << designRadius_m
        << " m"
        << endl;
1243 1244 1245 1246
    msg << "Bend design energy:      "
        << designEnergy_m
        << " eV"
        << endl;
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
    msg << endl
        << "Bend Field and Rotation Properties"
        << endl
        << "=================================="
        << endl << endl;
    msg << "Field amplitude:         "
        << fieldAmplitude_m
        << " T"
        << endl;
    msg << "Field index (gradient):  "
        << gradient_m
        << " m^-1"
        << endl;
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278
    msg << "Rotation about x axis:   "
        << Orientation_m(1)
        << " rad ("
        << Orientation_m(1) * 180.0 / Physics::pi
        << " degrees)"
        << endl;
    msg << "Rotation about y axis:   "
        << Orientation_m(0)
        << " rad ("
        << Orientation_m(0) * 180.0 / Physics::pi
        << " degrees)"
        << endl;
    msg << "Rotation about z axis:   "
        << Orientation_m(2)
        << " rad ("
        << Orientation_m(2) * 180.0 / Physics::pi
        << " degrees)"
        << endl;
    msg << endl
1279
        << "Reference Trajectory Properties Through Bend Magnet with Fringe Fields"
1280
        << endl
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 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 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 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 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 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 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 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
        << endl << endl;
    msg << "Reference particle is bent: "
        << bendAngleX
        << " rad ("
        << bendAngleX * 180.0 / Physics::pi
        << " degrees) in x plane"
        << endl;
    msg << "Reference particle is bent: "
        << bendAngleY
        << " rad ("
        << bendAngleY * 180.0 / Physics::pi
        << " degrees) in y plane"
        << endl << endl;

}

void SBend::ReadFieldMap(Inform &msg) {

    msg << getName() << " using file ";
    fieldmap_m->getInfo(&msg);
    Fieldmap::readMap(fileName_m);
    fieldmap_m->Get1DProfile1EntranceParam(entranceParameter1_m,
                                           entranceParameter2_m,
                                           entranceParameter3_m);
    fieldmap_m->Get1DProfile1ExitParam(exitParameter1_m,
                                       exitParameter2_m,
                                       exitParameter3_m);
    SetGapFromFieldMap();
    fieldmap_m->Get1DProfile1EngeCoeffs(engeCoeffsEntry_m,
                                        engeCoeffsExit_m);
    polyOrderEntry_m = engeCoeffsEntry_m.size() - 1;
    polyOrderExit_m = engeCoeffsExit_m.size() - 1;

}

bool SBend::Reinitialize() {

    if(designEnergy_m != RefPartBunch_m->get_meanEnergy() * 1.0e6) {

        designEnergy_m = RefPartBunch_m->get_meanEnergy() * 1.0e6;
        SetBendStrength();
        double bendAngleX = 0.0;
        double bendAngleY = 0.0;
        CalculateRefTrajectory(bendAngleX, bendAngleY);

        Inform msg("SBend ");
        msg << "Bend design energy changed to: "
            << designEnergy_m * 1.0e-6
            << " MeV"
            << endl;
        Print(msg, bendAngleX, bendAngleY);

    }

    return false;
}

Vector_t SBend::RotateOutOfBendFrame(Vector_t X) {

    /*
     * Rotate vector out of the bend's local coordinate system back to
     * the lab frame.
     *
     * 1) Rotate about the x axis by angle negative Orientation_m(1).
     * 2) Rotate about the y axis by angle Orientation_m(0).
     * 3) Rotate about the z axis by angle Orientation_m(3).
     */

    double sina = sin(Orientation_m(0));
    double cosa = cos(Orientation_m(0));
    double sinb = sin(Orientation_m(1));
    double cosb = cos(Orientation_m(1));
    double sinc = sin(Orientation_m(2));
    double cosc = cos(Orientation_m(2));

    Vector_t temp(0.0, 0.0, 0.0);

    temp(0) = (cosa * cosc) *                       X(0)
              + (-sina * sinb * cosc - cosb * sinc) * X(1)
              + (sina * cosb * cosc - sinb * sinc)  * X(2);
    temp(1) = (cosa * sinc) *                       X(0)
              + (-sina * sinb * sinc + cosb * cosc) * X(1)
              + (sina * cosb * sinc + sinb * cosc)  * X(2);
    temp(2) =   -sina *                               X(0)
                + (-cosa * sinb) *                      X(1)
                + (cosa * cosb) *                       X(2);

    return temp;

}

Vector_t SBend::RotateToBendFrame(Vector_t X) {

    /*
     * Rotate vector to the bend's local coordinate system.
     *
     * 1) Rotate about the z axis by angle negative Orientation_m(2).
     * 2) Rotate about the y axis by angle negative Orientation_m(0).
     * 3) Rotate about the x axis by angle Orientation_m(1).
     */

    double sina = sin(Orientation_m(0));
    double cosa = cos(Orientation_m(0));
    double sinb = sin(Orientation_m(1));
    double cosb = cos(Orientation_m(1));
    double sinc = sin(Orientation_m(2));
    double cosc = cos(Orientation_m(2));

    Vector_t temp(0.0, 0.0, 0.0);

    temp(0) = (cosa * cosc) * X(0)
              + (cosa * sinc) * X(1)
              -  sina *         X(2);
    temp(1) = (-cosb * sinc - sina * sinb * cosc) * X(0)
              + (cosb * cosc - sina * sinb * sinc)  * X(1)
              -  cosa * sinb *                        X(2);
    temp(2) = (-sinb * sinc + sina * cosb * cosc) * X(0)
              + (sinb * cosc + sina * cosb * sinc)  * X(1)
              + cosa * cosb *                         X(2);

    return temp;
}

void SBend::SetBendEffectiveLength(double startField, double endField) {

    // Find initial angle.
    double actualBendAngle = CalculateBendAngle();

    // Adjust field map to match bend angle.
    double error = std::abs(actualBendAngle - angle_m);
    if(error > 1.0 - 6)
        FindBendEffectiveLength(startField, endField);

}

void SBend::SetBendStrength() {

    // Estimate bend field magnitude.
    double mass = RefPartBunch_m->getM();
    double gamma = designEnergy_m / mass + 1.0;
    double betaGamma = sqrt(pow(gamma, 2.0) - 1.0);
    double charge = RefPartBunch_m->getQ();

    fieldAmplitude_m = (charge / std::abs(charge)) * betaGamma * mass
                       / (Physics::c * designRadius_m);

    // Find initial angle.
    double actualBendAngle = CalculateBendAngle();

    // Search for angle if initial guess is not good enough.
    double error = std::abs(actualBendAngle - angle_m);
    if(error > 1.0e-6)
        FindBendStrength(mass, gamma, betaGamma, charge);

}

void SBend::SetEngeOriginDelta(double delta) {
    /*
     * This function is used to shift the perpendicular distance of the
     * entrance and exit Enge function origins with respect to the entrance
     * and exit points in the magnet. A positive delta shifts them towards
     * the center of the magnet.
     */
    entranceParameter1_m = delta - std::abs(entranceParameter1_m
                                            - entranceParameter2_m);
    entranceParameter3_m = delta + std::abs(entranceParameter2_m
                                            - entranceParameter3_m);
    entranceParameter2_m = delta;

    exitParameter1_m = -delta - std::abs(exitParameter1_m - exitParameter2_m);
    exitParameter3_m = -delta + std::abs(exitParameter2_m - exitParameter3_m);
    exitParameter2_m = -delta;
}

void SBend::SetFieldCalcParam(bool chordLengthFromMap) {

    cosEntranceAngle_m = cos(entranceAngle_m);
    sinEntranceAngle_m = sin(entranceAngle_m);

    deltaBeginEntry_m = std::abs(entranceParameter1_m - entranceParameter2_m);
    deltaEndEntry_m = std::abs(entranceParameter2_m - entranceParameter3_m);

    exitEdgeAngle_m = angle_m - exitAngle_m;
    cosExitAngle_m = cos(exitEdgeAngle_m);
    sinExitAngle_m = sin(exitEdgeAngle_m);

    deltaBeginExit_m = std::abs(exitParameter1_m - exitParameter2_m);
    deltaEndExit_m = std::abs(exitParameter2_m - exitParameter3_m);

    if(chordLengthFromMap) {
        /*
         * The magnet chord length is taken from this field map. In this case,
         * we assume that the origin points for the entrance and exit Enge
         * functions correspond to the physical edges of the bend magnet. These
         * are the points where the ideal reference particle trajectory intercepts
         * the entrance and exit edges.
         */
        xOriginEngeEntry_m = 0.0;
        zOriginEngeEntry_m = 0.0;
        xOriginEngeExit_m = xExit_m;
        zOriginEngeExit_m = zExit_m;

    } else {
        /*
         * In this case, the chord length of the magnet is set in the input file
         * and is not taken from the field map file. This allows us to set the
         * origin points for the entrance and exit Enge functions some perpendicular
         * distance away from the physical edges of the magnet.
         */
        xOriginEngeEntry_m = -entranceParameter2_m * sinEntranceAngle_m;
        zOriginEngeEntry_m = entranceParameter2_m * cosEntranceAngle_m;

        xOriginEngeExit_m = xExit_m - exitParameter2_m * sinExitAngle_m;
        zOriginEngeExit_m = zExit_m + exitParameter2_m * cosExitAngle_m;

    }
}

void SBend::SetGapFromFieldMap() {

    if(gap_m <= 0.0)
        gap_m = fieldmap_m->GetFieldGap();
    else if(gap_m != fieldmap_m->GetFieldGap())
        AdjustFringeFields(gap_m / fieldmap_m->GetFieldGap());

}

bool SBend::SetupBendGeometry(Inform &msg, double &startField, double &endField) {

    double chordLength = 0.0;
    bool chordLengthFromMap = false;
    if(!FindChordLength(msg, chordLength, chordLengthFromMap))
        return false;

1516
    if(TreatAsDrift(msg, chordLength)) {
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
        startField_m = startField;
        endField_m = startField + chordLength;
        return true;
    }

    reinitialize_m = FindIdealBendParameters(chordLength);
    FindReferenceExitOrigin(xExit_m, zExit_m);

    /*
     * Set field map geometry.
     */
    if(aperture_m <= 0.0)
        aperture_m = designRadius_m / 2.0;
    SetFieldCalcParam(chordLengthFromMap);

    /*
     * If we are using the default field map, then the origins for the
     * Enge functions will be shifted so that we get the desired bend
     * angle for the given bend strength. (We match the effective length
     * of our field map to the ideal bend length.)
     *
     * If we are not using the default field map, we assume it cannot
     * change so we either leave everything alone (if the user defines
     * the bend strength) or we adjust the bend field to get the right
     * angle.
     */
    elementEdge_m = startField + ds_m;
    SetFieldBoundaries(startField, endField);

    if(fileName_m != "1DPROFILE1-DEFAULT") {
        if(reinitialize_m)
            SetBendStrength();
    } else {
        SetBendEffectiveLength(startField, endField);
    }

    startField = startField_m;
    endField = endField_m;
    return true;

}

bool SBend::SetupDefaultFieldMap(Inform &msg) {

    if(length_m <= 0.0) {
        msg << "If using \"1DPROFILE1-DEFAULT\" field map you must set the "
            "chord length of the bend using the L attribute in the OPAL "
            "input file."
            << endl;
        return false;
    } else {
        fieldmap_m->getInfo(&msg);
        return true;
    }

}

void SBend::SetFieldBoundaries(double startField, double endField) {

    startField_m = startField - deltaBeginEntry_m / cos(entranceAngle_m) + ds_m;
    endField_m = startField + angle_m * designRadius_m
                 + deltaEndExit_m / cos(exitAngle_m)
                 + ds_m;

}

void SBend::SetupPusher(PartBunch *bunch) {

    RefPartBunch_m = bunch;
    pusher_m.initialise(bunch->getReference());

}

1590
bool SBend::TreatAsDrift(Inform &msg, double chordLength) {
1591 1592 1593 1594 1595
    if(designEnergy_m <= 0.0) {
        msg << "Warning: bend design energy is zero. Treating as drift."
            << endl;
        designRadius_m = 0.0;
        return true;
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
    } else if(angle_m == 0.0) {

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

        double amplitude = std::abs(fieldAmplitude_m);
        double radius = std::abs(refBetaGamma * refMass / (Physics::c * amplitude));
        double sinArgument = chordLength / (2.0 * radius);

        if(std::abs(sinArgument) > 1.0) {
            msg << "Warning: bend strength and defined reference trajectory "
                << "chord length are not consistent. Treating bend as drift."
                << endl;
            designRadius_m = 0.0;
            return true;
        } else
            return false;

    } else if(angle_m == 0.0 &&
              pow(bY_m, 2.0) + pow(bX_m, 2.0) == 0.0) {

        msg << "Warning bend angle/strength is zero. Treating as drift."
            << endl;
        designRadius_m = 0.0;
        return true;

1623 1624 1625
    } else
        return false;
}