OrbitThreader.cpp 17 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 = "data/" + OpalData::getInstance()->getInputBasename() + "_DesignPath.dat";
52 53
        if (OpalData::getInstance()->getOpenMode() == OpalData::OPENMODE::WRITE ||
            !boost::filesystem::exists(fileName)) {
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
            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);
        }

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

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

void OrbitThreader::execute() {
    double initialPathLength = pathLength_m;
86 87 88 89 90 91 92
    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
93 94 95
    Vector_t nextR = r_m / (Physics::c * dt_m);
    integrator_m.push(nextR, p_m, dt_m);
    nextR *= Physics::c * dt_m;
96

Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
97 98 99 100 101 102
    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
103
            autophaseCavities(elementSet, visitedElements);
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
104 105 106 107 108
        }

        double initialS = pathLength_m;
        Vector_t initialR = r_m;
        Vector_t initialP = p_m;
109
        integrate(elementSet, maxIntegSteps_m, 2 * maxDistance);
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
110 111 112 113

        registerElement(elementSet, initialS,  initialR, initialP);

        if (errorFlag_m == HITMATERIAL) {
114 115 116
            // 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
117 118 119 120 121 122 123 124 125 126 127 128 129
        }

        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) {
130
            nextR = r_m / (Physics::c * dt_m);
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
131 132 133 134 135
            integrator_m.push(nextR, p_m, dt_m);
            nextR *= Physics::c * dt_m;

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

kraus's avatar
kraus committed
139
    imap_m.tidyUp(zstop_m);
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
140
    *gmsg << level1 << "\n" << imap_m << endl;
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
141 142 143 144 145
    imap_m.saveSDDS(initialPathLength);

    processElementRegister();
}

146
void OrbitThreader::integrate(const IndexMap::value_t &activeSet, size_t /*maxSteps*/, double maxDrift) {
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
147
    static size_t step = 0;
148 149
    CoordinateSystemTrafo labToBeamline = itsOpalBeamline_m.getCSTrafoLab2Local();
    const double oldPathLength = pathLength_m;
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
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
    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);
        }

179 180 181 182
        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
183
            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
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
                     << 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
207
        pathLength_m += std::copysign(euclidean_norm(r_m - oldR), dt_m);
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
208 209 210 211 212 213 214
        ++ 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;

215
        if ((activeSet.size() == 0 && std::abs(pathLength_m - oldPathLength) > maxDrift) ||
216 217
            (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
218 219 220 221
            errorFlag_m = EOL;
            return;
        }

222
    } while (activeSet == itsOpalBeamline_m.getElements(nextR));
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
223 224 225 226 227 228 229
}

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) {
230 231
        if ((*it)->getType() == ElementBase::TRAVELINGWAVE ||
            (*it)->getType() == ElementBase::RFCAVITY) {
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
232 233 234 235 236 237 238
            return true;
        }
    }

    return false;
}

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

Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
243 244 245 246
    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
247 248 249
        if (((*it)->getType() == ElementBase::TRAVELINGWAVE ||
             (*it)->getType() == ElementBase::RFCAVITY) &&
            visitedElements.find((*it)->getName()) == visitedElements.end()) {
250 251 252 253 254 255 256 257 258

            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
259 260 261 262 263 264 265 266 267 268 269 270
        }
    }
}


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) {
271 272
        if ((*it)->getType() == ElementBase::TRAVELINGWAVE ||
            (*it)->getType() == ElementBase::RFCAVITY) {
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
273 274 275 276 277 278 279 280
            const RFCavity *element = static_cast<const RFCavity *>((*it).get());
            designEnergy = std::max(designEnergy, element->getDesignEnergy());
        }
    }

    return designEnergy;
}

281
void OrbitThreader::trackBack(double maxDrift) {
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
282 283 284 285 286 287 288
    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;

289 290
    maxDrift = std::min(maxDrift, distTrackBack_m);
    while (std::abs(initialPathLength - pathLength_m) < distTrackBack_m) {
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
291 292
        auto elementSet = itsOpalBeamline_m.getElements(nextR);

293
        integrate(elementSet, 1000, maxDrift);
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
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

        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
328
        double elementEdge = start - initialR(2) * euclidean_norm(initialP) / initialP(2);
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
329 330 331 332 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

        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() &&
380 381
            !(element->getType() == ElementBase::RFCAVITY ||
              element->getType() == ElementBase::TRAVELINGWAVE)) {
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
382 383 384 385

            element->setDesignEnergy(kineticEnergyeV);
        }
    }
386
}
387 388 389 390

double OrbitThreader::computeMaximalImplicitDrift() {
    FieldList allElements = itsOpalBeamline_m.getElementByType(ElementBase::ANY);
    double maxDrift = 0.0;
kraus's avatar
kraus committed
391 392 393 394 395 396 397 398

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

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
    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
426
            auto toEnd = element2->getEdgeToEnd() * toEdge;
427
            Vector_t begin2 = toBegin.transformFrom(Vector_t(0, 0, 0));
kraus's avatar
kraus committed
428
            Vector_t end2 = toEnd.transformFrom(Vector_t(0, 0, 0));
429 430 431 432 433 434 435 436 437 438 439 440
            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
441 442 443 444 445
            bool overlapping = dot(begin2 - end1, directionBegin) < 0.0? true: false;

            if (!overlapping &&
                directionProjection > 0.999 &&
                minDistanceLocal > distance) {
446 447 448 449
                minDistanceLocal = distance;
            }
        }

kraus's avatar
kraus committed
450 451
        if (maxDrift < minDistanceLocal &&
            minDistanceLocal != std::numeric_limits<double>::max()) {
452 453 454 455
            maxDrift = minDistanceLocal;
        }
    }

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

458
    return maxDrift;
459
}