OrbitThreader.cpp 17.8 KB
Newer Older
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
1 2 3 4
#include "Algorithms/OrbitThreader.h"
#include "Algorithms/CavityAutophaser.h"

#include "AbsBeamline/RFCavity.h"
5
#include "AbsBeamline/BendBase.h"
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
6
#include "AbsBeamline/TravelingWave.h"
kraus's avatar
kraus committed
7
#include "BeamlineCore/MarkerRep.h"
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
8 9 10 11 12 13 14 15 16 17

#include "AbstractObjects/OpalData.h"
#include "BasicActions/Option.h"
#include "Utilities/Options.h"

#include "Utilities/OpalException.h"
#include "Utilities/Util.h"

#include <boost/filesystem.hpp>

18
#include <cmath>
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
#include <iostream>
#include <limits>

#define HITMATERIAL 0x80000000
#define EOL 0x40000000
#define EVERYTHINGFINE 0x00000000
extern Inform *gmsg;

OrbitThreader::OrbitThreader(const PartData &ref,
                             const Vector_t &r,
                             const Vector_t &p,
                             double s,
                             double maxDiffZBunch,
                             double t,
                             double dt,
                             size_t maxIntegSteps,
                             double zstop,
                             OpalBeamline &bl) :
    r_m(r),
    p_m(p),
    pathLength_m(s),
    time_m(t),
    dt_m(dt),
    maxIntegSteps_m(maxIntegSteps),
    zstop_m(zstop),
    itsOpalBeamline_m(bl),
    errorFlag_m(0),
    integrator_m(ref),
    reference_m(ref)
{
49 50
    auto opal = OpalData::getInstance();
    if (Ippl::myNode() == 0 && !opal->isOptimizerRun()) {
51
        std::string fileName = Util::combineFilePath({
frey_m's avatar
frey_m committed
52 53
            opal->getAuxiliaryOutputDirectory(),
            opal->getInputBasename() + "_DesignPath.dat"
54
        });
frey_m's avatar
frey_m committed
55
        if (opal->getOpenMode() == OpalData::OPENMODE::WRITE ||
56
            !boost::filesystem::exists(fileName)) {
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
            logger_m.open(fileName);
            logger_m << "#"
                     << std::setw(17) << "1 - s"
                     << std::setw(18) << "2 - Rx"
                     << std::setw(18) << "3 - Ry"
                     << std::setw(18) << "4 - Rz"
                     << std::setw(18) << "5 - Px"
                     << std::setw(18) << "6 - Py"
                     << std::setw(18) << "7 - Pz"
                     << std::setw(18) << "8 - Efx"
                     << std::setw(18) << "9 - Efy"
                     << std::setw(18) << "10 - Efz"
                     << std::setw(18) << "11 - Bfx"
                     << std::setw(18) << "12 - Bfy"
                     << std::setw(18) << "13 - Bfz"
                     << std::setw(18) << "14 - Ekin"
                     << std::setw(18) << "15 - t"
                     << std::endl;
        } else {
            logger_m.open(fileName, std::ios_base::app);
        }

79
        loggingFrequency_m = std::max(1.0, std::round(1e-11 / std::abs(dt_m)));
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
80 81 82 83
    } else {
        loggingFrequency_m = std::numeric_limits<size_t>::max();
    }

84
    distTrackBack_m = std::min(pathLength_m, std::max(0.0, maxDiffZBunch));
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
85 86 87 88
}

void OrbitThreader::execute() {
    double initialPathLength = pathLength_m;
kraus's avatar
kraus committed
89
    computeMaximalImplicitDrift2();
90 91 92 93 94 95 96
    double maxDistance = computeMaximalImplicitDrift();

    auto allElements = itsOpalBeamline_m.getElementByType(ElementBase::ANY);
    std::set<std::string> visitedElements;

    trackBack(2 * maxDistance);

Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
97 98 99
    Vector_t nextR = r_m / (Physics::c * dt_m);
    integrator_m.push(nextR, p_m, dt_m);
    nextR *= Physics::c * dt_m;
100

Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
101 102 103 104 105 106
    setDesignEnergy(allElements, visitedElements);

    auto elementSet = itsOpalBeamline_m.getElements(nextR);
    errorFlag_m = EVERYTHINGFINE;
    do {
        if (containsCavity(elementSet)) {
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
107
            autophaseCavities(elementSet, visitedElements);
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
108 109 110 111 112
        }

        double initialS = pathLength_m;
        Vector_t initialR = r_m;
        Vector_t initialP = p_m;
113
        integrate(elementSet, maxIntegSteps_m, 2 * maxDistance);
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
114 115 116 117

        registerElement(elementSet, initialS,  initialR, initialP);

        if (errorFlag_m == HITMATERIAL) {
118 119 120
            // Shouldn't be reached because reference particle
            // isn't stopped by collimators
            pathLength_m += std::copysign(1.0, dt_m);
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
121 122 123 124 125 126 127 128 129 130 131 132 133
        }

        imap_m.add(initialS, pathLength_m, elementSet);

        IndexMap::value_t::const_iterator it = elementSet.begin();
        const IndexMap::value_t::const_iterator end = elementSet.end();
        for (; it != end; ++ it) {
            visitedElements.insert((*it)->getName());
        }

        setDesignEnergy(allElements, visitedElements);

        if (errorFlag_m == EVERYTHINGFINE) {
134
            nextR = r_m / (Physics::c * dt_m);
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
135 136 137 138 139
            integrator_m.push(nextR, p_m, dt_m);
            nextR *= Physics::c * dt_m;

            elementSet = itsOpalBeamline_m.getElements(nextR);
        }
140
    } while (errorFlag_m != HITMATERIAL &&
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
141 142
             errorFlag_m != EOL);

kraus's avatar
kraus committed
143
    imap_m.tidyUp(zstop_m);
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
144
    *gmsg << level1 << "\n" << imap_m << endl;
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
145 146 147 148 149
    imap_m.saveSDDS(initialPathLength);

    processElementRegister();
}

150
void OrbitThreader::integrate(const IndexMap::value_t &activeSet, size_t /*maxSteps*/, double maxDrift) {
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
151
    static size_t step = 0;
152 153
    CoordinateSystemTrafo labToBeamline = itsOpalBeamline_m.getCSTrafoLab2Local();
    const double oldPathLength = pathLength_m;
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
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
    Vector_t nextR;
    do {
        errorFlag_m = EVERYTHINGFINE;

        IndexMap::value_t::const_iterator it = activeSet.begin();
        const IndexMap::value_t::const_iterator end = activeSet.end();
        Vector_t oldR = r_m;

        r_m /= Physics::c * dt_m;
        integrator_m.push(r_m, p_m, dt_m);
        r_m *= Physics::c * dt_m;

        Vector_t Ef(0.0), Bf(0.0);
        std::string names("\t");
        for (; it != end; ++ it) {
            Vector_t localR = itsOpalBeamline_m.transformToLocalCS(*it, r_m);
            Vector_t localP = itsOpalBeamline_m.rotateToLocalCS(*it, p_m);
            Vector_t localE(0.0), localB(0.0);

            if ((*it)->applyToReferenceParticle(localR, localP, time_m + 0.5 * dt_m, localE, localB)) {
                errorFlag_m = HITMATERIAL;
                return;
            }
            names += (*it)->getName() + ", ";

            Ef += itsOpalBeamline_m.rotateFromLocalCS(*it, localE);
            Bf += itsOpalBeamline_m.rotateFromLocalCS(*it, localB);
        }

183 184 185 186
        if (pathLength_m > 0.0 &&
            pathLength_m < zstop_m &&
            step % loggingFrequency_m == 0 && Ippl::myNode() == 0 &&
            !OpalData::getInstance()->isOptimizerRun()) {
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
187
            logger_m << std::setw(18) << std::setprecision(8) << pathLength_m + std::copysign(euclidean_norm(r_m - oldR), dt_m)
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
                     << std::setw(18) << std::setprecision(8) << r_m(0)
                     << std::setw(18) << std::setprecision(8) << r_m(1)
                     << std::setw(18) << std::setprecision(8) << r_m(2)
                     << std::setw(18) << std::setprecision(8) << p_m(0)
                     << std::setw(18) << std::setprecision(8) << p_m(1)
                     << std::setw(18) << std::setprecision(8) << p_m(2)
                     << std::setw(18) << std::setprecision(8) << Ef(0)
                     << std::setw(18) << std::setprecision(8) << Ef(1)
                     << std::setw(18) << std::setprecision(8) << Ef(2)
                     << std::setw(18) << std::setprecision(8) << Bf(0)
                     << std::setw(18) << std::setprecision(8) << Bf(1)
                     << std::setw(18) << std::setprecision(8) << Bf(2)
                     << std::setw(18) << std::setprecision(8) << reference_m.getM() * (sqrt(dot(p_m, p_m) + 1) - 1) * 1e-6
                     << std::setw(18) << std::setprecision(8) << (time_m + 0.5 * dt_m) * 1e9
                     << names
                     << std::endl;
        }

        r_m /= Physics::c * dt_m;
        integrator_m.kick(r_m, p_m, Ef, Bf, dt_m);
        integrator_m.push(r_m, p_m, dt_m);
        r_m *= Physics::c * dt_m;

Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
211
        pathLength_m += std::copysign(euclidean_norm(r_m - oldR), dt_m);
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
212 213 214 215 216 217 218
        ++ step;
        time_m += dt_m;

        nextR = r_m / (Physics::c * dt_m);
        integrator_m.push(nextR, p_m, dt_m);
        nextR *= Physics::c * dt_m;

219
        if ((activeSet.size() == 0 && std::abs(pathLength_m - oldPathLength) > maxDrift) ||
220 221
            (activeSet.size() > 0  && dt_m * pathLength_m > dt_m * zstop_m) ||
            (pathLength_m < 0.0 && dt_m < 0.0)) {
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
222 223 224 225
            errorFlag_m = EOL;
            return;
        }

226
    } while (activeSet == itsOpalBeamline_m.getElements(nextR));
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
227 228 229 230 231 232 233
}

bool OrbitThreader::containsCavity(const IndexMap::value_t &activeSet) {
    IndexMap::value_t::const_iterator it = activeSet.begin();
    const IndexMap::value_t::const_iterator end = activeSet.end();

    for (; it != end; ++ it) {
234 235
        if ((*it)->getType() == ElementBase::TRAVELINGWAVE ||
            (*it)->getType() == ElementBase::RFCAVITY) {
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
236 237 238 239 240 241 242
            return true;
        }
    }

    return false;
}

Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
243 244
void OrbitThreader::autophaseCavities(const IndexMap::value_t &activeSet,
                                      const std::set<std::string> &visitedElements) {
245 246
    if (Options::autoPhase == 0) return;

Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
247 248 249 250
    IndexMap::value_t::const_iterator it = activeSet.begin();
    const IndexMap::value_t::const_iterator end = activeSet.end();

    for (; it != end; ++ it) {
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
251 252 253
        if (((*it)->getType() == ElementBase::TRAVELINGWAVE ||
             (*it)->getType() == ElementBase::RFCAVITY) &&
            visitedElements.find((*it)->getName()) == visitedElements.end()) {
254 255 256 257 258 259 260 261 262

            Vector_t initialR = itsOpalBeamline_m.transformToLocalCS(*it, r_m);
            Vector_t initialP = itsOpalBeamline_m.rotateToLocalCS(*it, p_m);

            CavityAutophaser ap(reference_m, *it);
            ap.getPhaseAtMaxEnergy(initialR,
                                   initialP,
                                   time_m,
                                   dt_m);
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
263 264 265 266 267 268 269 270 271 272 273 274
        }
    }
}


double OrbitThreader::getMaxDesignEnergy(const IndexMap::value_t &elementSet) const
{
    IndexMap::value_t::const_iterator it = elementSet.begin();
    const IndexMap::value_t::const_iterator end = elementSet.end();

    double designEnergy = 0.0;
    for (; it != end; ++ it) {
275 276
        if ((*it)->getType() == ElementBase::TRAVELINGWAVE ||
            (*it)->getType() == ElementBase::RFCAVITY) {
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
277 278 279 280 281 282 283 284
            const RFCavity *element = static_cast<const RFCavity *>((*it).get());
            designEnergy = std::max(designEnergy, element->getDesignEnergy());
        }
    }

    return designEnergy;
}

285
void OrbitThreader::trackBack(double maxDrift) {
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
286 287 288 289 290 291 292
    dt_m *= -1;
    double initialPathLength = pathLength_m;

    Vector_t nextR = r_m / (Physics::c * dt_m);
    integrator_m.push(nextR, p_m, dt_m);
    nextR *= Physics::c * dt_m;

293 294
    maxDrift = std::min(maxDrift, distTrackBack_m);
    while (std::abs(initialPathLength - pathLength_m) < distTrackBack_m) {
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
295 296
        auto elementSet = itsOpalBeamline_m.getElements(nextR);

297
        integrate(elementSet, 1000, maxDrift);
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331

        nextR = r_m / (Physics::c * dt_m);
        integrator_m.push(nextR, p_m, dt_m);
        nextR *= Physics::c * dt_m;
    }

    dt_m *= -1;
}

void OrbitThreader::registerElement(const IndexMap::value_t &elementSet,
                                    double start,
                                    const Vector_t &R,
                                    const Vector_t &P) {

    IndexMap::value_t::const_iterator it = elementSet.begin();
    const IndexMap::value_t::const_iterator end = elementSet.end();

    for (; it != end; ++ it) {
        bool found = false;
        std::string name = (*it)->getName();
        auto prior = elementRegistry_m.equal_range(name);

        for (auto pit = prior.first; pit != prior.second; ++ pit) {
            if (std::abs((*pit).second.endField_m - start) < 1e-10) {
                found = true;
                (*pit).second.endField_m = pathLength_m;
                break;
            }
        }

        if (found) continue;

        Vector_t initialR = itsOpalBeamline_m.transformToLocalCS(*it, R);
        Vector_t initialP = itsOpalBeamline_m.rotateToLocalCS(*it, P);
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
332
        double elementEdge = start - initialR(2) * euclidean_norm(initialP) / initialP(2);
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383

        elementPosition ep = {start, pathLength_m, elementEdge};
        elementRegistry_m.insert(std::make_pair(name, ep));
    }
}

void OrbitThreader::processElementRegister() {
    std::map<std::string, std::set<elementPosition, elementPositionComp> > tmpRegistry;

    for (auto it = elementRegistry_m.begin(); it != elementRegistry_m.end(); ++ it) {
        const std::string &name = (*it).first;
        elementPosition &ep = (*it).second;

        auto prior = tmpRegistry.find(name);
        if (prior == tmpRegistry.end()) {
            std::set<elementPosition, elementPositionComp> tmpSet;
            tmpSet.insert(ep);
            tmpRegistry.insert(std::make_pair(name, tmpSet));
            continue;
        }

        std::set<elementPosition, elementPositionComp> &set = (*prior).second;
        set.insert(ep);
    }

    auto allElements = itsOpalBeamline_m.getElementByType(ElementBase::ANY);
    FieldList::iterator it = allElements.begin();
    const FieldList::iterator end = allElements.end();
    for (; it != end; ++ it) {
        std::string name = (*it).getElement()->getName();
        auto trit = tmpRegistry.find(name);
        if (trit == tmpRegistry.end()) continue;

        std::queue<std::pair<double, double> > range;
        std::set<elementPosition, elementPositionComp> &set = (*trit).second;

        for (auto sit = set.begin(); sit != set.end(); ++ sit) {
            range.push(std::make_pair((*sit).elementEdge_m, (*sit).endField_m));
        }
        (*it).getElement()->setActionRange(range);
    }
}

void OrbitThreader::setDesignEnergy(FieldList &allElements, const std::set<std::string> &visitedElements) {
    double kineticEnergyeV = reference_m.getM() * (sqrt(dot(p_m, p_m) + 1.0) - 1.0);

    FieldList::iterator it = allElements.begin();
    const FieldList::iterator end = allElements.end();
    for (; it != end; ++ it) {
        std::shared_ptr<Component> element = (*it).getElement();
        if (visitedElements.find(element->getName()) == visitedElements.end() &&
384 385
            !(element->getType() == ElementBase::RFCAVITY ||
              element->getType() == ElementBase::TRAVELINGWAVE)) {
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
386 387 388 389

            element->setDesignEnergy(kineticEnergyeV);
        }
    }
390
}
391

kraus's avatar
kraus committed
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
void OrbitThreader::computeMaximalImplicitDrift2() {
    FieldList allElements = itsOpalBeamline_m.getElementByType(ElementBase::ANY);
    FieldList::iterator it = allElements.begin();
    const FieldList::iterator end = allElements.end();
    globalBoundingBox_m.lowerLeftCorner = Vector_t(std::numeric_limits<double>::max());
    globalBoundingBox_m.upperRightCorner = Vector_t(-std::numeric_limits<double>::max());

    for (; it != end; ++ it) {
        if (it->getElement()->getType() == ElementBase::MARKER) {
            continue;
        }
        ElementBase::BoundingBox other = it->getBoundingBoxInLabCoords();
        globalBoundingBox_m.getCombinedBoundingBox(other);
    }
}

408 409 410
double OrbitThreader::computeMaximalImplicitDrift() {
    FieldList allElements = itsOpalBeamline_m.getElementByType(ElementBase::ANY);
    double maxDrift = 0.0;
kraus's avatar
kraus committed
411 412 413 414 415 416 417 418

    MarkerRep start("#S");
    CoordinateSystemTrafo toEdge(r_m, getQuaternion(p_m, Vector_t(0, 0, 1)));
    start.setElementLength(0.0);
    start.setCSTrafoGlobal2Local(toEdge);
    std::shared_ptr<Component> startPtr(static_cast<Marker*>(start.clone()));
    allElements.push_front(ClassicField(startPtr, 0.0, 0.0));

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
    FieldList::iterator it = allElements.begin();
    const FieldList::iterator end = allElements.end();
    for (; it != end; ++ it) {
        auto element1 = it->getElement();
        const auto &toEdge = element1->getCSTrafoGlobal2Local();
        auto toEnd = element1->getEdgeToEnd() * toEdge;
        Vector_t end1 = toEnd.transformFrom(Vector_t(0, 0, 0));
        Vector_t directionEnd = toEnd.rotateFrom(Vector_t(0, 0, 1));
        if (element1->getType() == ElementBase::RBEND ||
            element1->getType() == ElementBase::SBEND ||
            element1->getType() == ElementBase::RBEND3D ) {
            auto toBegin = element1->getEdgeToBegin() * toEdge;

            BendBase *bend = static_cast<BendBase*>(element1.get());
            double angleRelativeToFace = bend->getEntranceAngle() - bend->getBendAngle();
            directionEnd = toBegin.rotateFrom(Vector_t(sin(angleRelativeToFace), 0, cos(angleRelativeToFace)));
        }

        double minDistanceLocal = std::numeric_limits<double>::max();
        FieldList::iterator it2 = allElements.begin();
        for (; it2 != end; ++ it2) {
            if (it == it2) continue;

            auto element2 = it2->getElement();
            const auto &toEdge = element2->getCSTrafoGlobal2Local();
            auto toBegin = element2->getEdgeToBegin() * toEdge;
kraus's avatar
kraus committed
445
            auto toEnd = element2->getEdgeToEnd() * toEdge;
446
            Vector_t begin2 = toBegin.transformFrom(Vector_t(0, 0, 0));
kraus's avatar
kraus committed
447
            Vector_t end2 = toEnd.transformFrom(Vector_t(0, 0, 0));
448 449 450 451 452 453 454 455 456 457 458 459
            Vector_t directionBegin = toBegin.rotateFrom(Vector_t(0, 0, 1));
            if (element2->getType() == ElementBase::RBEND ||
                element2->getType() == ElementBase::SBEND ||
                element2->getType() == ElementBase::RBEND3D ) {
                BendBase *bend = static_cast<BendBase*>(element2.get());
                double E1 = bend->getEntranceAngle();
                directionBegin = toBegin.rotateFrom(Vector_t(sin(E1), 0, cos(E1)));
            }


            double distance = euclidean_norm(begin2 - end1);
            double directionProjection = dot(directionEnd, directionBegin);
kraus's avatar
kraus committed
460 461 462 463 464
            bool overlapping = dot(begin2 - end1, directionBegin) < 0.0? true: false;

            if (!overlapping &&
                directionProjection > 0.999 &&
                minDistanceLocal > distance) {
465 466 467 468
                minDistanceLocal = distance;
            }
        }

kraus's avatar
kraus committed
469 470
        if (maxDrift < minDistanceLocal &&
            minDistanceLocal != std::numeric_limits<double>::max()) {
471 472 473 474
            maxDrift = minDistanceLocal;
        }
    }

475
    maxDrift = std::min(maxIntegSteps_m * std::abs(dt_m) * Physics::c, maxDrift);
kraus's avatar
kraus committed
476

477
    return maxDrift;
kraus's avatar
kraus committed
478
}