SBend.cpp 27.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 23 24 25 26 27 28 29 30 31 32 33 34 35 36
// ------------------------------------------------------------------------
// $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"
#include "AbsBeamline/BeamlineVisitor.h"
#include "Fields/Fieldmap.hh"
#include <iostream>
#include <fstream>

extern Inform *gmsg;

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

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

SBend::SBend(const SBend &right):
    Component(right),
    filename_m(right.filename_m),
    fieldmap_m(right.fieldmap_m),
kraus's avatar
kraus committed
72
    fast_m(right.fast_m),
gsell's avatar
gsell committed
73 74 75 76 77 78
    ElementEdge_m(right.ElementEdge_m),
    startField_m(right.startField_m),
    endField_m(right.endField_m),
    length_m(right.length_m),
    gap_m(right.gap_m),
    reinitialize_m(right.reinitialize_m),
kraus's avatar
kraus committed
79 80
    alpha_m(right.alpha_m),
    exitAngle_m(right.exitAngle_m),
gsell's avatar
gsell committed
81 82 83 84 85 86
    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
87 88
    gradient_m(right.gradient_m),
    amplitude_m(right.amplitude_m),
gsell's avatar
gsell committed
89
    angle_m(right.angle_m),
kraus's avatar
kraus committed
90 91 92 93
    R_m(right.R_m),
    design_energy_m(right.design_energy_m),
    field_orientation_m(right.field_orientation_m),
    map_m(NULL),
gsell's avatar
gsell committed
94 95 96
    map_size_m(right.map_size_m),
    map_step_size_m(right.map_step_size_m),
    effectiveLength_m(right.effectiveLength_m),
kraus's avatar
kraus committed
97 98
    effectiveCenter_m(right.effectiveCenter_m),
    pusher_m(right.pusher_m) {
gsell's avatar
gsell committed
99 100 101 102 103 104 105 106 107
    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
108
SBend::SBend(const std::string &name):
109
    Component(name),
gsell's avatar
gsell committed
110 111
    filename_m(""),
    fieldmap_m(NULL),
kraus's avatar
kraus committed
112
    fast_m(false),
gsell's avatar
gsell committed
113
    ElementEdge_m(0.0),
kraus's avatar
kraus committed
114
    startElement_m(0.0),
gsell's avatar
gsell committed
115 116 117 118
    startField_m(0.0),
    endField_m(0.0),
    length_m(0.0),
    gap_m(0.0),
kraus's avatar
kraus committed
119 120 121
    reinitialize_m(false),
    alpha_m(0.0),
    exitAngle_m(0.0),
gsell's avatar
gsell committed
122 123 124 125 126 127
    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),
kraus's avatar
kraus committed
128 129
    gradient_m(0.0),
    amplitude_m(0.0),
gsell's avatar
gsell committed
130
    angle_m(0.0),
kraus's avatar
kraus committed
131 132 133
    R_m(0.0),
    design_energy_m(0.0),
    field_orientation_m(1.0, 0.0),
gsell's avatar
gsell committed
134 135 136 137
    map_m(NULL),
    map_size_m(0),
    map_step_size_m(0.0),
    effectiveLength_m(0.0),
kraus's avatar
kraus committed
138 139
    effectiveCenter_m(0.0),
    pusher_m() {
gsell's avatar
gsell committed
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 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 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
    setElType(isDipole);
}


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


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


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

bool SBend::apply(const int &i, const double &t, double E[], double B[]) {
    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;
}

bool SBend::apply(const int &i, const double &t, Vector_t &E, Vector_t &B) {

    // If this is the first call, the bend angle is specified in the input
    // file and the design energy of the bend is different from the average
    // energy of the beam, we reinitialize the bend.
    if(reinitialize_m) {
        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;
        }

        reinitialize_m = false;
    }

    // Get field.
    const Vector_t &X = RefPartBunch_m->X[i];
    Vector_t strength(0.0), info(0.0);

    fieldmap_m->getFieldstrength(X, strength, info);
Steve Russell's avatar
Steve Russell committed
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235

    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;
    }
gsell's avatar
gsell committed
236 237 238

    if(info(0) > 0.99) {

Steve Russell's avatar
Steve Russell committed
239 240
        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);
gsell's avatar
gsell committed
241 242

        if(info(1) > 0.99) {
Steve Russell's avatar
Steve Russell committed
243 244
            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;
gsell's avatar
gsell committed
245
        } else {
Steve Russell's avatar
Steve Russell committed
246 247
            B(0) += bX * dx;
            B(2) -= amplitude_m * strength(1) * X(1) + bX * dz;
gsell's avatar
gsell committed
248 249
        }

Steve Russell's avatar
Steve Russell committed
250 251 252 253 254
    } 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
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
    //    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
328
                tempB(0) -= amplitude_m * strength(1) * X(1) * sin(exitAngle_m);
gsell's avatar
gsell committed
329 330
                tempB(2) += amplitude_m * strength(1) * X(1) * cos(exitAngle_m);
            } else {
Steve Russell's avatar
Steve Russell committed
331
                tempB(2) -= amplitude_m * strength(1) * X(1);
gsell's avatar
gsell committed
332 333 334 335
            }
        } else if(fabs(info(0)) < 0.01)
            tempB(1) += amplitude_m;

kraus's avatar
kraus committed
336
        // double dd, dx, dz, rho;
gsell's avatar
gsell committed
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
        //        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;

}

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());

    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) {
                msg << "If using \"1DPROFILE1-DEFAULT\" field map you must set GAP (full magnet gap) and L (length) in the OPAL input file." << endl;
                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);
                startElement_m = startField;
            }
        }

        length_m =  zEnd - zBegin;
        if(length_m < 0.0) {
            // There is probably something wrong with the fieldmap.
            return;
        }

        // If the bend angle is specified, find proper field strength. If only
        // the field strength is given, just calculate the bend angle. This also
        // sets the bend exit angle appropriately.
        if(angle_m != 0.0) {
            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
447 448
        } else if(amplitude_m != 0.0) {
            angle_m = calculateBendAngle(length_m, true);
gsell's avatar
gsell committed
449 450 451
            reinitialize_m = false;
        }

Steve Russell's avatar
Steve Russell committed
452 453
        // Calculate the reference particle trajectory map. Make sure field map edge constants
        // are reset.
gsell's avatar
gsell committed
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
        double bendAngle = calculateRefTrajectory(zBegin);

        startField = startField_m;
        endField = endField_m;

        msg << "Start:            " << startField_m << " m (in floor coordinates)" << endl;
        msg << "End:              " << endField_m << " m (in floor coordinates)" << endl;
        msg << "Bend angle:       " << 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;

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

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

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


void SBend::setBendAngle(const double &angle) {

    // A positive value for the field strength
    angle_m = angle * Physics::pi / 180.0;
}

void SBend::setAmplitudem(double vPeak) {
    amplitude_m = vPeak;
}

void SBend::setFullGap(const double &gap) {
    gap_m = gap;
}

void SBend::setLength(const double &length) {
    length_m = length;
}

Steve Russell's avatar
Steve Russell committed
498
void SBend::setFieldMapFN(std::string fmapfn) {
gsell's avatar
gsell committed
499 500 501
    filename_m = fmapfn;
}

Steve Russell's avatar
Steve Russell committed
502
std::string SBend::getFieldMapFN() const {
gsell's avatar
gsell committed
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
    return filename_m;
}

void SBend::getDimensions(double &zBegin, double &zEnd) const {
    zBegin = startField_m;
    zEnd = endField_m;
}

double SBend::getEffectiveLength() const {
    return effectiveLength_m;
}

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

double SBend::getBendAngle() const {
    return angle_m;
}

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

double SBend::getR() const {
    return R_m;
}

Steve Russell's avatar
Steve Russell committed
531 532
const std::string &SBend::getType() const {
    static const std::string type("SBend");
gsell's avatar
gsell committed
533 534 535 536 537 538 539 540 541 542 543 544 545
    return type;
}

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();

Steve Russell's avatar
Steve Russell committed
546
    fieldmap_m->setEdgeConstants(0.0, 0.0, 0.0);
gsell's avatar
gsell committed
547
    calculateEffectiveLength();
Steve Russell's avatar
Steve Russell committed
548 549 550
    double radius = effectiveLength_m / (2.0 * sin(angle_m / 2.0));

    amplitude_m = (charge / fabs(charge)) * betaGamma * mass / (Physics::c * radius);
gsell's avatar
gsell committed
551 552 553 554 555 556

    // Find initial angle.
    double zBegin = 0.0;
    double zEnd = 0.0;
    double rBegin = 0.0;
    double rEnd = 0.0;
Steve Russell's avatar
Steve Russell committed
557
    fieldmap_m->setEdgeConstants(angle_m, alpha_m, exitAngle_m);
gsell's avatar
gsell committed
558
    fieldmap_m->getFieldDimensions(zBegin, zEnd, rBegin, rEnd);
Steve Russell's avatar
Steve Russell committed
559
    double actualBendAngle = calculateBendAngle(zEnd - zBegin, false);
gsell's avatar
gsell committed
560

Steve Russell's avatar
Steve Russell committed
561 562 563
    // 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
564

Steve Russell's avatar
Steve Russell committed
565 566
        double amplitude1 = amplitude_m;
        double bendAngle1 = actualBendAngle;
gsell's avatar
gsell committed
567

Steve Russell's avatar
Steve Russell committed
568
        double fieldAdjustment = amplitude_m / 10.0;
gsell's avatar
gsell committed
569

Steve Russell's avatar
Steve Russell committed
570 571
        if(fabs(bendAngle1) > fabs(angle_m))
            fieldAdjustment *= -1.0;
gsell's avatar
gsell committed
572

Steve Russell's avatar
Steve Russell committed
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
        double amplitude2 = amplitude_m + fieldAdjustment;
        amplitude_m = amplitude2;
        double bendAngle2 = calculateBendAngle(zEnd - zBegin, false);

        if(fabs(bendAngle1) > fabs(angle_m)) {
            while(fabs(bendAngle2) > fabs(angle_m)) {
                amplitude2 += fieldAdjustment;
                amplitude_m = amplitude2;
                bendAngle2 = calculateBendAngle(zEnd - zBegin, false);
            }
        } else {
            while(fabs(bendAngle2) < fabs(angle_m)) {
                amplitude2 += fieldAdjustment;
                amplitude_m = amplitude2;
                bendAngle2 = calculateBendAngle(zEnd - zBegin, false);
            }
        }
gsell's avatar
gsell committed
590

Steve Russell's avatar
Steve Russell committed
591 592 593
        // Now we should have the proper field amplitude bracketed.
        unsigned int iterations = 1;
        while(error > 1.0e-6 && iterations < 100) {
gsell's avatar
gsell committed
594

Steve Russell's avatar
Steve Russell committed
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
            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;
                    }
gsell's avatar
gsell committed
611

Steve Russell's avatar
Steve Russell committed
612 613 614 615 616 617 618 619 620 621 622 623 624
                } else {

                    if(newBendAngle - angle_m < 0.0) {
                        bendAngle2 = newBendAngle;
                        amplitude2 = amplitude_m;
                    } else {
                        bendAngle1 = newBendAngle;
                        amplitude1 = amplitude_m;
                    }
                }
            }
            iterations++;
        }
gsell's avatar
gsell committed
625 626 627
    }
}

Steve Russell's avatar
Steve Russell committed
628 629
double SBend::calculateBendAngle(double bendLength, bool modifyField) {
    // This routine calculates the bend angle using an iterative process.
gsell's avatar
gsell committed
630 631 632 633 634 635 636 637 638

    // Make initial guess of angle.
    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
639
    Vector_t P(-betaGamma * sin_face_alpha_m, 0.0, betaGamma * cos_face_alpha_m);
gsell's avatar
gsell committed
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
    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
663
    double angle =  -atan2(P(0), P(2)) - Orientation_m(0);
gsell's avatar
gsell committed
664 665 666 667 668

    // Now iterate while adjusting the exit face.
    double error = 1.0;
    while(error > 1.0e-6) {

Steve Russell's avatar
Steve Russell committed
669 670
        if(modifyField)
            fieldmap_m->setEdgeConstants(angle, angle_m, exitAngle_m);
gsell's avatar
gsell committed
671 672

        X = Vector_t(0.0);
Steve Russell's avatar
Steve Russell committed
673
        P = Vector_t(-betaGamma * sin_face_alpha_m, 0.0, betaGamma * cos_face_alpha_m);
gsell's avatar
gsell committed
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
        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
695 696
        double newAngle =  -atan2(P(0), P(2)) - Orientation_m(0);

gsell's avatar
gsell committed
697 698 699 700 701 702 703 704 705 706 707 708
        error = fabs(newAngle - angle);
        angle = newAngle;
    }

    return angle;
}

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.;
Steve Russell's avatar
Steve Russell committed
709
    const double betaGamma = sqrt(gamma * gamma - 1.);
gsell's avatar
gsell committed
710
    const double dt = RefPartBunch_m->getdT();
Steve Russell's avatar
Steve Russell committed
711

gsell's avatar
gsell committed
712 713 714 715 716 717
    int j = 0;

    Vector_t tmp(0.0);
    Vector_t Bfield(0.0);
    Vector_t strength(0.0);
    Vector_t X(0.0);
Steve Russell's avatar
Steve Russell committed
718
    Vector_t P(-betaGamma * sin_face_alpha_m, 0.0, betaGamma * cos_face_alpha_m); // TODO: make it 3D
gsell's avatar
gsell committed
719 720 721 722 723 724

    bool EntryFringe_passed = 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;

Steve Russell's avatar
Steve Russell committed
725
    map_step_size_m = betaGamma / gamma * Physics::c * dt;
gsell's avatar
gsell committed
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
    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) && !EntryFringe_passed) {
            EntryFringe_passed = 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;
Steve Russell's avatar
Steve Russell committed
755
    double angle = -atan2(P(0), P(2)) - Orientation_m(0);
gsell's avatar
gsell committed
756 757 758 759 760

    startField_m = startElement_m - PathLengthEntryFringe;
    endField_m = startField_m + map_step_size_m * j;

    // Set "ideal" bend radius and effective length.
Steve Russell's avatar
Steve Russell committed
761
    R_m = fabs(betaGamma * mass / (Physics::c * amplitude_m));
762
    effectiveLength_m = R_m * std::abs(angle);
gsell's avatar
gsell committed
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
    calculateEffectiveCenter();

    return angle;
}

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
817
    double actualBendAngle = calculateBendAngle(effectiveCenter, false);
gsell's avatar
gsell committed
818 819 820 821 822 823 824 825 826 827 828 829 830 831

    // 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
832
        actualBendAngle = calculateBendAngle(effectiveCenter, false);
gsell's avatar
gsell committed
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
        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;
}