SBend.cpp 33.7 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 34 35
#include "AbsBeamline/BeamlineVisitor.h"
#include "Fields/Fieldmap.hh"
#include <iostream>
#include <fstream>

extern Inform *gmsg;

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

SBend::SBend():
    Component(),
36 37
    pusher_m(),
    field_orientation_m(1.0, 0.0),
gsell's avatar
gsell committed
38 39
    filename_m(""),
    fieldmap_m(NULL),
kraus's avatar
kraus committed
40
    fast_m(false),
41
    reinitialize_m(false),
gsell's avatar
gsell committed
42
    startField_m(0.0),
kraus's avatar
kraus committed
43
    endField_m(0.0),
gsell's avatar
gsell committed
44 45
    length_m(0.0),
    gap_m(0.0),
46 47 48 49 50 51
    ElementEdge_m(0.0),
    startElement_m(0.0),
    amplitude_m(0.0),
    gradient_m(0.0),
    angle_m(0.0),
    design_energy_m(0.0),
gsell's avatar
gsell committed
52 53 54 55 56 57 58 59 60 61 62
    alpha_m(0.0),
    exitAngle_m(0.0),
    sin_face_alpha_m(0.0),
    cos_face_alpha_m(1.0),
    tan_face_alpha_m(0.0),
    sin_face_beta_m(0.0),
    cos_face_beta_m(1.0),
    tan_face_beta_m(0.0),
    map_m(NULL),
    map_size_m(0),
    map_step_size_m(0.0),
63
    R_m(0.0),
gsell's avatar
gsell committed
64
    effectiveLength_m(0.0),
kraus's avatar
kraus committed
65
    effectiveCenter_m(0.0),
66
    effectiveStart_m(0.0) {
gsell's avatar
gsell committed
67 68 69 70 71
    setElType(isDipole);
}

SBend::SBend(const SBend &right):
    Component(right),
72 73
    pusher_m(right.pusher_m),
    field_orientation_m(right.field_orientation_m),
gsell's avatar
gsell committed
74 75
    filename_m(right.filename_m),
    fieldmap_m(right.fieldmap_m),
kraus's avatar
kraus committed
76
    fast_m(right.fast_m),
77
    reinitialize_m(right.reinitialize_m),
gsell's avatar
gsell committed
78 79 80 81
    startField_m(right.startField_m),
    endField_m(right.endField_m),
    length_m(right.length_m),
    gap_m(right.gap_m),
82 83 84 85 86 87
    ElementEdge_m(right.ElementEdge_m),
    startElement_m(right.startElement_m),
    amplitude_m(right.amplitude_m),
    gradient_m(right.gradient_m),
    angle_m(right.angle_m),
    design_energy_m(right.design_energy_m),
kraus's avatar
kraus committed
88 89
    alpha_m(right.alpha_m),
    exitAngle_m(right.exitAngle_m),
gsell's avatar
gsell committed
90 91 92 93 94 95
    sin_face_alpha_m(right.sin_face_alpha_m),
    cos_face_alpha_m(right.cos_face_alpha_m),
    tan_face_alpha_m(right.tan_face_alpha_m),
    sin_face_beta_m(right.sin_face_beta_m),
    cos_face_beta_m(right.cos_face_beta_m),
    tan_face_beta_m(right.tan_face_beta_m),
kraus's avatar
kraus committed
96
    map_m(NULL),
gsell's avatar
gsell committed
97 98
    map_size_m(right.map_size_m),
    map_step_size_m(right.map_step_size_m),
99
    R_m(right.R_m),
gsell's avatar
gsell committed
100
    effectiveLength_m(right.effectiveLength_m),
kraus's avatar
kraus committed
101
    effectiveCenter_m(right.effectiveCenter_m),
102
    effectiveStart_m(right.effectiveStart_m) {
gsell's avatar
gsell committed
103 104 105 106 107 108 109 110 111
    setElType(isDipole);
    if(map_size_m > 0) {
        map_m = new double[3 * (map_size_m + 1)];
        for(int i = 0; i < 3 * (map_size_m + 1); ++i)
            map_m[i] = right.map_m[i];
    }
}


Steve Russell's avatar
Steve Russell committed
112
SBend::SBend(const std::string &name):
113
    Component(name),
114 115
    pusher_m(),
    field_orientation_m(1.0, 0.0),
gsell's avatar
gsell committed
116 117
    filename_m(""),
    fieldmap_m(NULL),
kraus's avatar
kraus committed
118
    fast_m(false),
119
    reinitialize_m(false),
gsell's avatar
gsell committed
120 121 122 123
    startField_m(0.0),
    endField_m(0.0),
    length_m(0.0),
    gap_m(0.0),
124 125 126 127 128 129
    ElementEdge_m(0.0),
    startElement_m(0.0),
    amplitude_m(0.0),
    gradient_m(0.0),
    angle_m(0.0),
    design_energy_m(0.0),
kraus's avatar
kraus committed
130 131
    alpha_m(0.0),
    exitAngle_m(0.0),
gsell's avatar
gsell committed
132 133 134 135 136 137 138 139 140
    sin_face_alpha_m(0.0),
    cos_face_alpha_m(1.0),
    tan_face_alpha_m(0.0),
    sin_face_beta_m(0.0),
    cos_face_beta_m(1.0),
    tan_face_beta_m(0.0),
    map_m(NULL),
    map_size_m(0),
    map_step_size_m(0.0),
141
    R_m(0.0),
gsell's avatar
gsell committed
142
    effectiveLength_m(0.0),
kraus's avatar
kraus committed
143
    effectiveCenter_m(0.0),
144
    effectiveStart_m(0.0) {
gsell's avatar
gsell committed
145 146 147 148 149 150 151 152 153 154 155 156 157 158
    setElType(isDipole);
}

SBend::~SBend() {
    if(map_m) {
        delete[] map_m;
        map_m = NULL;
    }
}

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

159 160 161 162
/*
 * OPAL-MAP methods
 * ================
 */
gsell's avatar
gsell committed
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
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);
}

179 180 181 182 183 184 185 186 187 188
/*
 * 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.
 */

189
bool SBend::apply(const size_t &i, const double &t, double E[], double B[]) {
gsell's avatar
gsell committed
190 191 192 193 194 195 196 197 198 199 200 201 202
    Vector_t Ev(0, 0, 0), Bv(0, 0, 0);
    if(apply(RefPartBunch_m->R[i], RefPartBunch_m->get_rmean(), t, Ev, Bv)) return true;

    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;
}

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

205 206 207
    // Check if we need to reinitialize the bend field amplitude.
    if(reinitialize_m)
        reinitialize_m = reinitialize();
gsell's avatar
gsell committed
208

209
    // Get field from field map.
gsell's avatar
gsell committed
210
    const Vector_t &X = RefPartBunch_m->X[i];
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
    double bX = 0.0;
    double bY = 0.0;
    double bZ = 0.0;
    calculateMapField(X, bX, bY, bZ);

    B(0) += bX;
    B(1) += bY;
    B(2) += bZ;

    //    Vector_t strength(0.0);
    //    Vector_t info(0.0);
    //    fieldmap_m->getFieldstrength(X, strength, info);
    //
    //    double dd, dx, dz, rho;
    //    const double &k34 = info(2);
    //
    //    if(k34 > 0) {
    //        dx = X(0) + R_m * cos_face_alpha_m;
    //        dz = X(2) - R_m * sin_face_alpha_m;
    //        rho = sqrt(dx * dx + dz * dz);
    //        dd = 1.0 - rho / R_m;
    //    } else {
    //        dx = -X(0) + R_m * cos_face_alpha_m;
    //        dz = -X(2) + R_m * sin_face_alpha_m;
    //        rho = sqrt(dx * dx + dz * dz);
    //        dd = -1.0 + rho / R_m;
    //    }
    //
    //    if(info(0) > 0.99) {
    //
    //        B(1) += amplitude_m * (strength(0) - strength(2) / 2.0 * pow(X(1), 2.0)) * (1.0 - gradient_m * dd);
    //        double bX = amplitude_m * (strength(0) - strength(2) / 2.0 * pow(X(1), 2.0)) * gradient_m * X(1) / (rho * R_m);
    //
    //        if(info(1) > 0.99) {
    //            B(0) -= amplitude_m * strength(1) * X(1) * sin(angle_m - alpha_m - exitAngle_m) + bX * dx;
    //            B(2) += amplitude_m * strength(1) * X(1) * cos(angle_m - alpha_m - exitAngle_m) + bX * dz;
    //        } else {
    //            B(0) += bX * dx;
    //            B(2) -= amplitude_m * strength(1) * X(1) + bX * dz;
    //        }
    //
    //    } else if(fabs(info(0)) < 0.01) {
    //        B(0) += amplitude_m * gradient_m * X(1) * dx / (rho * R_m);
    //        B(1) += amplitude_m * (1.0 - gradient_m * dd);
    //        B(2) += amplitude_m * gradient_m * X(1) * dz / (rho * R_m);
    //    }
gsell's avatar
gsell committed
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
    //    if(info(0) > 0.99) {
    //        B(1) +=  amplitude_m * (strength(0) - strength(2) / 2. * X(1) * X(1)) * (1. - gradient_m * dd);
    //        double Bx = amplitude_m * (strength(0) - strength(2) / 2. * X(1) * X(1)) * gradient_m * X(1) / (rho * R_m);
    //        double Bz = amplitude_m * strength(1) * X(1);
    //        if(info(1) > 0.99) {
    //            B(0) += - Bz * k34 / sqrt(1. + k34 * k34) + Bx * dx;
    //            B(2) += Bz / sqrt(1. + k34 * k34) + Bx * dz;
    //        } else {
    //            B(0) += Bx * dx;
    //            B(2) += -Bz + Bx * dz;
    //        }
    //    } else if(info(0) < 0.01) {
    //        B(0) += amplitude_m * gradient_m * X(1) * dx / (rho * R_m);
    //        B(1) += amplitude_m * (1. - gradient_m * dd);
    //        B(2) += amplitude_m * gradient_m * X(1) * dz / (rho * R_m);
    //    }

    return false;
}

bool SBend::apply(const Vector_t &R, const Vector_t &centroid, const double &t, Vector_t &E, Vector_t &B) {

    int index = (int)floor((R(2) - startField_m) / map_step_size_m);
    if(index > 0 && index + 1 < map_size_m) {

        //        // Find indices for position in pre-computed central trajectory map.
        //        double lever = (R(2) - startField_m) / map_step_size_m - index;
        //        double z = (1. - lever) * map_m[3 * index + 2] + lever * map_m[3 * index + 5];
        //        double x = (1. - lever) * map_m[3 * index] + lever * map_m[3 * index + 3];
        //        double y = (1. - lever) * map_m[3 * index + 1] + lever * map_m[3 * index + 4];

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

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

        Vector_t X(0.0);
        //        X(0) = (cosa * cosc) * (x + R(0)) + (cosa * sinc) * (y + R(1)) - sina *        R(2);
        //        X(1) = (-cosb * sinc - sina * sinb * cosc) * (x + R(0)) + (cosb * cosc - sina * sinb * sinc) * (y + R(1)) - cosa * sinb * R(2);
        //        X(2) = z;

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

        // Find indices for position in pre-computed central trajectory map.
        double lever = (R(2) - startField_m) / map_step_size_m - index;
        double z = (1. - lever) * map_m[3 * index + 2] + lever * map_m[3 * index + 5];
        double x = (1. - lever) * map_m[3 * index] + lever * map_m[3 * index + 3];
        double y = (1. - lever) * map_m[3 * index + 1] + lever * map_m[3 * index + 4];

        // Adjust position relative to pre-computed central trajectory map.
        X(0) += x;
        X(1) += y;
        X(2) = z;

        Vector_t strength(0.0), info(0.0);

        fieldmap_m->getFieldstrength(X, strength, info);
        Vector_t tempB(0.0);

        if(info(0) > 0.99) {
            tempB(1) += amplitude_m * (strength(0) - strength(2) / 2.0 * pow(X(1), 2.0));

            if(info(1) > 0.99) {
Steve Russell's avatar
Steve Russell committed
330
                tempB(0) -= amplitude_m * strength(1) * X(1) * sin(exitAngle_m);
gsell's avatar
gsell committed
331 332
                tempB(2) += amplitude_m * strength(1) * X(1) * cos(exitAngle_m);
            } else {
Steve Russell's avatar
Steve Russell committed
333
                tempB(2) -= amplitude_m * strength(1) * X(1);
gsell's avatar
gsell committed
334 335 336 337
            }
        } else if(fabs(info(0)) < 0.01)
            tempB(1) += amplitude_m;

kraus's avatar
kraus committed
338
        // double dd, dx, dz, rho;
gsell's avatar
gsell committed
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
        //        const double &k34 = info(2);
        //
        //        if(k34 > 0) {
        //            dx = X(0) + R_m * cos_face_alpha_m;
        //            dz = X(2) - R_m * sin_face_alpha_m;
        //            rho = sqrt(dx * dx + dz * dz);
        //            dd = 1.0 - rho / R_m;
        //        } else {
        //            dx = -X(0) + R_m * cos_face_alpha_m;
        //            dz = -X(2) + R_m * sin_face_alpha_m;
        //            rho = sqrt(dx * dx + dz * dz);
        //            dd = -1.0 + rho / R_m;
        //        }
        //
        //        if(info(0) > 0.99) {
        //            tempB(1) =  amplitude_m * (strength(0) - strength(2) / 2. * X(1) * X(1)) * (1. - gradient_m * dd);
        //            double Bx = amplitude_m * (strength(0) - strength(2) / 2. * X(1) * X(1)) * gradient_m * X(1) / (rho * R_m);
        //            double Bz = amplitude_m * strength(1) * X(1);
        //            if(info(1) > 0.99) {
        //                tempB(0) = - Bz * k34 / sqrt(1. + k34 * k34) + Bx * dx;
        //                tempB(2) = Bz / sqrt(1. + k34 * k34) + Bx * dz;
        //            } else {
        //                tempB(0) = Bx * dx;
        //                tempB(2) = -Bz + Bx * dz;
        //            }
        //        } else if(info(0) < 0.01) {
        //            tempB(0) = amplitude_m * gradient_m * X(1) * dx / (rho * R_m);
        //            tempB(1) = amplitude_m * (1. - gradient_m * dd);
        //            tempB(2) = amplitude_m * gradient_m * X(1) * dz / (rho * R_m);
        //        }

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

        B(0) +=  cosa * cosc * tempB(0) + (-sina * sinb * cosc - cosb * sinc) * tempB(1) + (sina * cosb * cosc - sinb * sinc) * tempB(2);
        B(1) +=  cosa * sinc * tempB(0) + (-sina * sinb * sinc + cosb * cosc) * tempB(1) + (sina * cosb * sinc + sinb * cosc) * tempB(2);
        B(2) += -sina *        tempB(0) + (-cosa * sinb) * tempB(1) + (cosa * cosb) * tempB(2);
    }


    return false;

}

386
/// Does initial setup of the bend.
gsell's avatar
gsell committed
387 388 389 390 391 392 393 394 395 396 397 398 399 400
void SBend::initialise(PartBunch *bunch, double &startField, double &endField, const double &scaleFactor) {

    Inform msg("SBend ");

    double zBegin = 0.0;
    double zEnd = 0.0;
    double rBegin = 0.0;
    double rEnd = 0.0;

    startElement_m = startField;

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

401
    // Initialize field map.
gsell's avatar
gsell committed
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
    fieldmap_m = Fieldmap::getFieldmap(filename_m, fast_m);
    fieldmap_m->getFieldDimensions(zBegin, zEnd, rBegin, rEnd);

    if((fieldmap_m != NULL) && (zEnd > zBegin)) {

        // Read in field map.
        msg << getName() << " using file ";
        fieldmap_m->getInfo(&msg);
        Fieldmap::readMap(filename_m);

        // Check that the design energy is greater then zero.
        if(design_energy_m <= 0.0) {
            msg << "The bend must have a design energy greater than zero set in the input file." << endl;
            return;
        }

        // If using default field map, set length and gap.
        if(filename_m == "1DPROFILE1-DEFAULT") {
            if(gap_m <= 0.0 || length_m <= 0.0) {
421 422 423
                msg << "If using \"1DPROFILE1-DEFAULT\" field map you must set the full magnet gap, GAP, "
                    << " and magnet length, L, in the OPAL input file."
                    << endl;
gsell's avatar
gsell committed
424 425 426 427 428 429 430 431 432
                return;
            } else {
                fieldmap_m->setFieldGap(gap_m);
                fieldmap_m->setFieldLength(length_m);
                fieldmap_m->setEdgeConstants(0.0, 0.0, 0.0);
                fieldmap_m->adjustFringeFields();
                msg << "Adjusted fringe field parameters." << endl;
                fieldmap_m->getFieldDimensions(zBegin, zEnd, rBegin, rEnd);
                fieldmap_m->getInfo(&msg);
433 434 435 436

                // Primitive check to make sure field map is ok.
                if(zEnd < zBegin)
                    return;
gsell's avatar
gsell committed
437 438 439
            }
        }

440
        length_m = zEnd - zBegin;
gsell's avatar
gsell committed
441

442 443 444 445
        /*
         * If the bend angle is specified, find the proper field amplitude.
         * Otherwise, calculate the bend angle for the given field strength.
         */
gsell's avatar
gsell committed
446
        if(angle_m != 0.0) {
447
            // Negative bend angle is just a positive bend rotated 180 degrees.
gsell's avatar
gsell committed
448 449 450 451 452 453
            if(angle_m < 0.0) {
                angle_m *= -1.0;
                Orientation_m(2) += Physics::pi;
            }
            setBendStrength();
            reinitialize_m = true;
Steve Russell's avatar
Steve Russell committed
454 455
        } else if(amplitude_m != 0.0) {
            angle_m = calculateBendAngle(length_m, true);
456 457 458 459 460 461 462

            // Make negative bend angle a positive bend rotated 180 degrees.
            if(angle_m < 0.0) {
                amplitude_m *= -1.0;
                Orientation_m(2) += Physics::pi;
                angle_m = calculateBendAngle(length_m, true);
            }
gsell's avatar
gsell committed
463 464 465
            reinitialize_m = false;
        }

Steve Russell's avatar
Steve Russell committed
466 467
        // Calculate the reference particle trajectory map. Make sure field map edge constants
        // are reset.
gsell's avatar
gsell committed
468 469
        double bendAngle = calculateRefTrajectory(zBegin);

470 471 472 473 474 475
        // Set effective length and effective center.
        effectiveLength_m = R_m * std::abs(bendAngle);
        calculateEffectiveCenter();
        effectiveStart_m = startField_m + effectiveCenter_m - effectiveLength_m / 2.0;

        // Pass start and end of field to calling function.
gsell's avatar
gsell committed
476 477 478
        startField = startField_m;
        endField = endField_m;

479 480 481 482 483 484 485 486 487
        // Output bend information.
        msg << "Start:                " << startField_m << " m (in floor coordinates)" << endl;
        msg << "End:                  " << endField_m << " m (in floor coordinates)" << endl;
        msg << "Bend angle magnitude: " << bendAngle * 180.0 / Physics::pi << " degrees" << endl;
        msg << "Field amplitude:      " << amplitude_m << " T" << endl;
        msg << "Bend radius:          " << R_m << " m" << endl;
        msg << "Effective length:     " << effectiveLength_m << " m (in s coordinates)" << endl;
        msg << "Effective center:     " << effectiveCenter_m << " m (in s coordinates with respect to bend field map start position)" << endl;
        msg << "Effective start:      " << effectiveStart_m << " m (in floor coordinates)" << endl;
gsell's avatar
gsell committed
488 489 490 491 492 493 494 495 496 497 498 499 500

    } else {
        endField = startField - 1e-3;
    }
}

void SBend::finalise() {
    online_m = false;
}

bool SBend::bends() const
{ return true; }

Steve Russell's avatar
Steve Russell committed
501
std::string SBend::getFieldMapFN() const {
gsell's avatar
gsell committed
502 503 504
    return filename_m;
}

505 506 507 508 509
const std::string &SBend::getType() const {
    static const std::string type("SBend");
    return type;
}

gsell's avatar
gsell committed
510 511 512 513 514
void SBend::getDimensions(double &zBegin, double &zEnd) const {
    zBegin = startField_m;
    zEnd = endField_m;
}

515 516 517 518
double SBend::getBendAngle() const {
    return angle_m;
}

gsell's avatar
gsell committed
519 520 521 522 523 524 525 526
double SBend::getEffectiveLength() const {
    return effectiveLength_m;
}

double SBend::getEffectiveCenter() const {
    return effectiveCenter_m;
}

527 528
double SBend::getR() const {
    return R_m;
gsell's avatar
gsell committed
529 530 531 532 533 534
}

double SBend::getStartElement() const {
    return startElement_m;
}

535 536
void SBend::setAmplitudem(double vPeak) {
    amplitude_m = vPeak;
gsell's avatar
gsell committed
537 538
}

539 540
void SBend::setBendAngle(const double &angle) {
    angle_m = angle * Physics::pi / 180.0;
gsell's avatar
gsell committed
541 542
}

543 544
void SBend::setAlpha(const double &alpha) {
    alpha_m = alpha * Physics::pi / 180.0;
gsell's avatar
gsell committed
545

546 547 548 549 550 551 552 553 554 555
    /*
     * We set the orientation of the element to negative
     * of this angle in order to preserve the standard
     * definition of the entrance edge angle of a dipole.
     */
    Orientation_m(0) = -alpha * Physics::pi / 180.0;
    sin_face_alpha_m = sin(Orientation_m(0));
    cos_face_alpha_m = cos(Orientation_m(0));
    tan_face_alpha_m = tan(Orientation_m(0));
}
gsell's avatar
gsell committed
556

557 558 559
void SBend::setExitAngle(const double &exitAngle) {
    exitAngle_m = exitAngle * Physics::pi / 180.0;
}
gsell's avatar
gsell committed
560

561 562 563 564 565 566
void SBend::setBeta(const double &beta) {
    Orientation_m(1) = beta * Physics::pi / 180.0;
    sin_face_beta_m = sin(Orientation_m(1));
    cos_face_beta_m = cos(Orientation_m(1));
    tan_face_beta_m = tan(Orientation_m(1));
}
Steve Russell's avatar
Steve Russell committed
567

568 569 570
void SBend::setDesignEnergy(const double &energy) {
    design_energy_m = energy;
}
gsell's avatar
gsell committed
571

572 573 574
void SBend::setK1(const double &k1) {
    gradient_m = k1;
}
gsell's avatar
gsell committed
575

576 577 578
void SBend::setFieldMapFN(std::string fmapfn) {
    filename_m = fmapfn;
}
Steve Russell's avatar
Steve Russell committed
579

580 581 582
void SBend::setFullGap(const double &gap) {
    gap_m = gap;
}
Steve Russell's avatar
Steve Russell committed
583

584 585 586
void SBend::setLength(const double &length) {
    length_m = length;
}
Steve Russell's avatar
Steve Russell committed
587

588 589 590
void SBend::setLongitudinalRotation(const double &rotation) {
    Orientation_m(2) = rotation * Physics::pi / 180.0;
}
Steve Russell's avatar
Steve Russell committed
591

592
void SBend::setLongitudinalRotation(const double &k0, const double &k0s) {
gsell's avatar
gsell committed
593

594 595
    Orientation_m(2) = atan2(k0s, k0);
    amplitude_m = sqrt(pow(k0, 2.0) + pow(k0s, 2.0));
Steve Russell's avatar
Steve Russell committed
596

597 598 599 600
    if(fabs(k0s) > 1.e-8) {
        if(amplitude_m > 1.e-8) {
            field_orientation_m(0) = k0 / amplitude_m;
            field_orientation_m(1) = k0s / amplitude_m;
Steve Russell's avatar
Steve Russell committed
601
        }
602 603 604
    } else {
        field_orientation_m(0) = 1.0;
        field_orientation_m(1) = 0.0;
gsell's avatar
gsell committed
605 606 607
    }
}

Steve Russell's avatar
Steve Russell committed
608
double SBend::calculateBendAngle(double bendLength, bool modifyField) {
gsell's avatar
gsell committed
609

610
    // Calculate current bend angle given fixed field parameters.
gsell's avatar
gsell committed
611 612 613 614 615 616 617
    const double mass = RefPartBunch_m->getM();
    const double gamma = design_energy_m / mass + 1.0;
    const double betaGamma = sqrt(pow(gamma, 2.0) - 1.0);
    const double deltaT = RefPartBunch_m->getdT();

    // Integrate through field for initial angle.
    Vector_t X(0.0, 0.0, 0.0);
Steve Russell's avatar
Steve Russell committed
618
    Vector_t P(-betaGamma * sin_face_alpha_m, 0.0, betaGamma * cos_face_alpha_m);
gsell's avatar
gsell committed
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
    Vector_t strength(0.0, 0.0, 0.0);
    Vector_t bField(0.0, 0.0, 0.0);
    Vector_t temp(0.0, 0.0, 0.0);

    while(P(2) > 0.0 && X(2) < bendLength) {

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

        fieldmap_m->getFieldstrength(X, strength, temp);
        bField(1) = amplitude_m * strength(0);
        temp = Vector_t(0.0);

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

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

    }

Steve Russell's avatar
Steve Russell committed
642
    double angle =  -atan2(P(0), P(2)) - Orientation_m(0);
gsell's avatar
gsell committed
643

644
    // If given permission, modify field map parameters to iteratively converge on a solution.
gsell's avatar
gsell committed
645
    double error = 1.0;
646
    while(error > 1.0e-6 && modifyField) {
gsell's avatar
gsell committed
647

648
        fieldmap_m->setEdgeConstants(angle, alpha_m, exitAngle_m);
gsell's avatar
gsell committed
649 650

        X = Vector_t(0.0);
Steve Russell's avatar
Steve Russell committed
651
        P = Vector_t(-betaGamma * sin_face_alpha_m, 0.0, betaGamma * cos_face_alpha_m);
gsell's avatar
gsell committed
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
        temp = Vector_t(0.0);

        while(P(2) > 0.0 && X(2) < bendLength) {

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

            fieldmap_m->getFieldstrength(X, strength, temp);
            bField(1) = amplitude_m * strength(0);
            temp = Vector_t(0.0);

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

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

        }

Steve Russell's avatar
Steve Russell committed
673 674
        double newAngle =  -atan2(P(0), P(2)) - Orientation_m(0);

gsell's avatar
gsell committed
675 676 677 678 679 680 681
        error = fabs(newAngle - angle);
        angle = newAngle;
    }

    return angle;
}

682 683 684 685
// Transverse distance of particle from reference trajectory.
void SBend::calculateDistFromRef(Vector_t X, double &deltaX, double &angle) {
    double x = X(0) * cos(alpha_m) - X(2) * sin(alpha_m) + R_m;
    double z = X(0) * sin(alpha_m) + X(2) * cos(alpha_m) - effectiveStart_m;
gsell's avatar
gsell committed
686

687 688 689 690 691 692 693 694
    if(z <= 0.0) {
        deltaX = x - R_m;
        angle = 0.0;
    } else {
        deltaX = sqrt(pow(z, 2.0) + pow(x, 2.0)) - R_m;
        angle = atan2(z, x);
        if(std::abs(angle) > std::abs(angle_m))
            angle = angle_m;
gsell's avatar
gsell committed
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
    }
}

void SBend::calculateEffectiveLength() {

    double zBegin = 0.0;
    double zEnd = 0.0;
    double rBegin = 0.0;
    double rEnd = 0.0;
    fieldmap_m->getFieldDimensions(zBegin, zEnd, rBegin, rEnd);

    // Uses Simpson's rule to integrate field. Make step size about 1 mm.

    // This must be odd.
    unsigned int numberOfIntSteps = 2 * static_cast<unsigned int>(floor((zEnd - zBegin) * 1000.0 / 2.0)) + 1;

    double deltaZ = (zEnd - zBegin) / numberOfIntSteps;
    effectiveLength_m = 0.0;

    for(unsigned int integralIndex = 1; integralIndex <= (numberOfIntSteps - 1) / 2; integralIndex++) {

        Vector_t strength(0.0);
        Vector_t info(0.0);
        Vector_t X(0.0);
        X(2) = (2 * integralIndex - 1) * deltaZ;
        fieldmap_m->getFieldstrength(X, strength, info);
        double field1 = strength(0);

        X(2) = 2 * integralIndex * deltaZ;
        fieldmap_m->getFieldstrength(X, strength, info);
        double field2 = strength(0);

        X(2) = (2 * integralIndex + 1) * deltaZ;
        fieldmap_m->getFieldstrength(X, strength, info);
        double field3 = strength(0);

        effectiveLength_m += deltaZ * (field1 + 4.0 * field2 + field3) / 3.0;
    }
}

void SBend::calculateEffectiveCenter() {

    double zBegin = 0.0;
    double zEnd = 0.0;
    double rBegin = 0.0;
    double rEnd = 0.0;
    fieldmap_m->getFieldDimensions(zBegin, zEnd, rBegin, rEnd);

    // Initial guess for effective center.
    double effectiveCenter = fabs(R_m * angle_m / 2.0) - zBegin;

    // Find initial angle.
Steve Russell's avatar
Steve Russell committed
747
    double actualBendAngle = calculateBendAngle(effectiveCenter, false);
gsell's avatar
gsell committed
748 749 750 751 752 753 754 755 756 757 758 759 760 761

    // Adjust effective center to get a bend angle 0.5 times the full bend angle.
    int iterations = 1;
    double lengthAdjustment = effectiveCenter / 10.0;

    if(fabs(actualBendAngle) > fabs(angle_m / 2.0))
        lengthAdjustment *= -1.0;

    bool lastGreater = true;
    if(fabs(actualBendAngle) < fabs(angle_m / 2.0))
        lastGreater = false;

    while(fabs(actualBendAngle - angle_m / 2.0) > 1.0e-8 && iterations <= 100) {

Steve Russell's avatar
Steve Russell committed
762
        actualBendAngle = calculateBendAngle(effectiveCenter, false);
gsell's avatar
gsell committed
763 764 765 766 767 768 769 770 771 772 773 774 775 776
        iterations++;

        if((!lastGreater && fabs(actualBendAngle) > fabs(angle_m / 2.0)) || (lastGreater && fabs(actualBendAngle) < fabs(angle_m / 2.0)))
            lengthAdjustment /= -10.0;

        if(fabs(actualBendAngle) > fabs(angle_m / 2.0)) lastGreater = true;
        else lastGreater = false;

        effectiveCenter += lengthAdjustment;

    }
    effectiveCenter_m = effectiveCenter - R_m * sin(angle_m / 2.0) + R_m * angle_m / 2.0;
}

777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
void SBend::calculateMapField(Vector_t X, double &bX, double &bY, double &bZ) {

    // Get field from field map.
    Vector_t strength(0.0);
    Vector_t info(0.0);
    fieldmap_m->getFieldstrength(X, strength, info);

    //    double dd, dx, dz, rho;
    //    const double &k34 = info(2);
    //
    //    if(k34 > 0) {
    //        dx = X(0) + R_m * cos_face_alpha_m;
    //        dz = X(2) - R_m * sin_face_alpha_m;
    //        rho = sqrt(dx * dx + dz * dz);
    //        dd = 1.0 - rho / R_m;
    //    } else {
    //        dx = -X(0) + R_m * cos_face_alpha_m;
    //        dz = -X(2) + R_m * sin_face_alpha_m;
    //        rho = sqrt(dx * dx + dz * dz);
    //        dd = -1.0 + rho / R_m;
    //    }
    // Calculations for field index.
    double deltaX = 0.0;
    double angle = 0.0;
    if(gradient_m != 0.0)
        calculateDistFromRef(X, deltaX, angle);

    // Calculate field components based on where we are in the field map.
    if(info(0) > 0.99) {
        // We are in fringe field region.
        bY = amplitude_m * (strength(0) - strength(2) / 2.0 * pow(X(1), 2.0)) * (1.0 - gradient_m * deltaX / R_m);
        double bXTemp = -amplitude_m * (strength(0) - strength(2) / 2.0 * pow(X(1), 2.0)) * gradient_m * X(1) / R_m;
        double bZTemp = amplitude_m * strength(1) * X(1);

        if(info(1) > 0.99) {
            // Exit fringe field.
            bX = -bZTemp * sin(angle_m - alpha_m - exitAngle_m) + bXTemp * cos(angle + alpha_m);
            bZ = bZTemp * cos(angle_m - alpha_m - exitAngle_m) + bXTemp * sin(angle + alpha_m);
        } else {
            // Entrance fringe field.
            bX = bXTemp * cos(angle + alpha_m);
            bZ = -bZTemp + bXTemp * sin(angle + alpha_m);
        }

    } else if(fabs(info(0)) < 0.01) {
        // Central portion of magnet.
        bY = amplitude_m * (1.0 - gradient_m * deltaX / R_m);
        bX = -amplitude_m * gradient_m * X(1) * cos(angle - alpha_m) / R_m;
        bZ = -amplitude_m * gradient_m * X(1) * sin(angle - alpha_m) / R_m;
    }
}

double SBend::calculateRefTrajectory(const double zBegin) {

    // Calculate the reference trajectory map.
    const double mass = RefPartBunch_m->getM();
    const double gamma = design_energy_m / mass + 1.;
    const double betaGamma = sqrt(gamma * gamma - 1.);
    const double dt = RefPartBunch_m->getdT();

    int j = 0;

    Vector_t tmp(0.0);
    Vector_t Bfield(0.0);
    Vector_t strength(0.0);
    Vector_t X(0.0);
    Vector_t P(-betaGamma * sin_face_alpha_m, 0.0, betaGamma * cos_face_alpha_m); // TODO: make it 3D

    bool entryFringePassed = false;
    double pathLengthEntryFringe = 0.0;  // in S coordinates. This value is different from zBegin due to the curvature!

    if(map_m != NULL) delete map_m;

    map_step_size_m = betaGamma / gamma * Physics::c * dt;
    map_size_m = (int)floor(length_m / 2. * Physics::pi / map_step_size_m);
    map_m = new double[3 * (map_size_m + 1)];
    map_m[0] = map_m[1] = map_m[2] = 0.0;

    while(map_m[3 * j + 2] < length_m && j < map_size_m) {
        strength = Vector_t(0.0);
        X /= Vector_t(Physics::c * dt);
        pusher_m.push(X, P, dt);
        X *= Vector_t(Physics::c * dt);

        fieldmap_m->getFieldstrength(X, strength, tmp);
        if(X(2) >= fabs(zBegin) && !entryFringePassed) {
            /*
             * This is the point where we pass ELEMEDGEnot the end of the entry
             * fringe field as the name suggests.
             */
            entryFringePassed = true;
            pathLengthEntryFringe = j * map_step_size_m;
        }
        Bfield(1) = amplitude_m * strength(0);
        tmp = Vector_t(0.0);
        X /= Vector_t(Physics::c * dt);
        pusher_m.kick(X, P, tmp, Bfield, dt);
        pusher_m.push(X, P, dt);
        X *= Vector_t(Physics::c * dt);

        ++ j;
        map_m[3 * j] = X(0);
        map_m[3 * j + 1] = X(1);
        map_m[3 * j + 2] = X(2);
    }

    map_size_m = j;
    double angle = -atan2(P(0), P(2)) - Orientation_m(0);

    // Set the radius in the center of the bend.
    R_m = fabs(betaGamma * mass / (Physics::c * amplitude_m));

    // Adjust start and end of field map.
    startField_m = startElement_m - pathLengthEntryFringe;
    endField_m = startField_m + map_step_size_m * j;

    return angle;
}

bool SBend::reinitialize() {

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

        setBendStrength();

        double zBegin = 0.0;
        double zEnd = 0.0;
        double rBegin = 0.0;
        double rEnd = 0.0;
        fieldmap_m->getFieldDimensions(zBegin, zEnd, rBegin, rEnd);
        calculateRefTrajectory(zBegin);

        Inform msg("SBend ");
        msg << "Bend design energy changed to: " << design_energy_m * 1.0e-6 << " MeV" << endl;
        msg << "Field amplitude:               " << amplitude_m << " T" << endl;
    }

    return false;

}

void SBend::setBendStrength() {
    // This routine uses an iterative procedure to set the bend strength
    // so that the bend angle is the one we want.

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

    fieldmap_m->setEdgeConstants(0.0, 0.0, 0.0);
    calculateEffectiveLength();
    double radius = effectiveLength_m / (2.0 * sin(angle_m / 2.0));

    // We want a positive bend angle to bend in the negative x direction independent of charge.
    amplitude_m = (charge / fabs(charge)) * betaGamma * mass / (Physics::c * radius);

    // Find initial angle.
    double zBegin = 0.0;
    double zEnd = 0.0;
    double rBegin = 0.0;
    double rEnd = 0.0;
    fieldmap_m->setEdgeConstants(angle_m, alpha_m, exitAngle_m);
    fieldmap_m->getFieldDimensions(zBegin, zEnd, rBegin, rEnd);
    double actualBendAngle = calculateBendAngle(zEnd - zBegin, false);

    // Search for angle if initial guess is not good enough.
    double error = fabs(actualBendAngle - angle_m);
    if(error > 1.0e-6) {
gsell's avatar
gsell committed
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
        double amplitude1 = amplitude_m;
        double bendAngle1 = actualBendAngle;

        // Estimate field adjustment step.
        double fieldStep = (angle_m - bendAngle1) * betaGamma * mass / (2.0 * effectiveLength_m * Physics::c);
        if(pow(amplitude_m * effectiveLength_m * Physics::c / (betaGamma * mass), 2.0) < 1.0)
            fieldStep = (angle_m - bendAngle1) * betaGamma * mass / (2.0 * effectiveLength_m * Physics::c)
                        * std::sqrt(1.0 - pow(amplitude_m * effectiveLength_m * Physics::c / (betaGamma * mass), 2.0));

        fieldStep *= amplitude1 / std::abs(amplitude1);
        double amplitude2 = amplitude_m + fieldStep;
        amplitude_m = amplitude2;
        double bendAngle2 = calculateBendAngle(zEnd - zBegin, false);

        if(fabs(bendAngle1) > fabs(angle_m)) {
            while(fabs(bendAngle2) > fabs(angle_m)) {
                amplitude2 += fieldStep;
                amplitude_m = amplitude2;
                bendAngle2 = calculateBendAngle(zEnd - zBegin, false);
            }
        } else {
            while(fabs(bendAngle2) < fabs(angle_m)) {
                amplitude2 += fieldStep;
                amplitude_m = amplitude2;
                bendAngle2 = calculateBendAngle(zEnd - zBegin, false);
            }
        }

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

            amplitude_m = (amplitude1 + amplitude2) / 2.0;
            double newBendAngle = calculateBendAngle(zEnd - zBegin, false);

            error = fabs(newBendAngle - angle_m);

            if(error > 1.0e-6) {

                if(bendAngle1 - angle_m < 0.0) {

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

                } else {

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