OpalBeamline.cpp 32.9 KB
Newer Older
gsell's avatar
gsell committed
1
#include "Elements/OpalBeamline.h"
2
#include "Utilities/OpalException.h"
3 4 5 6
#include "Utilities/Options.h"
#include "Utilities/Util.h"
#include "AbstractObjects/OpalData.h"
#include "AbsBeamline/Bend.h"
7
#include "AbsBeamline/Collimator.h"
8 9 10 11 12 13
#include "Structure/MeshGenerator.h"

#include <boost/filesystem.hpp>
#include <boost/regex.hpp>
#include <fstream>
#include <regex>
gsell's avatar
gsell committed
14 15 16 17 18 19
using namespace std;

extern Inform *gmsg;

OpalBeamline::OpalBeamline():
    elements_m(),
20
    prepared_m(false),
21 22 23 24 25 26 27 28 29 30
    containsSource_m(false)
{
}

OpalBeamline::OpalBeamline(const Vector_t& origin,
                           const Quaternion& coordTransformationTo):
    elements_m(),
    prepared_m(false),
    containsSource_m(false),
    coordTransformationTo_m(origin, coordTransformationTo)
31
{
gsell's avatar
gsell committed
32 33 34 35 36 37 38 39 40
}

OpalBeamline::~OpalBeamline() {
    elements_m.clear();
}

CompVec OpalBeamline::dummy_list_m = CompVec();
OpalSection OpalBeamline::dummy_section_m = OpalSection(dummy_list_m, 0., 0.);

41 42 43 44 45 46 47
std::set<std::shared_ptr<Component>> OpalBeamline::getElements(const Vector_t &x) {
    std::set<std::shared_ptr<Component> > elementSet;
    FieldList::iterator it = elements_m.begin();
    const FieldList::iterator end = elements_m.end();
    for (; it != end; ++ it) {
        std::shared_ptr<Component> element = (*it).getElement();
        Vector_t r = (*it).getCoordTransformationTo().transformTo(x);
48

49 50
        if (element->isInside(r)) {
            elementSet.insert(element);
gsell's avatar
gsell committed
51 52 53
        }
    }

54
    return elementSet;
gsell's avatar
gsell committed
55 56 57 58 59 60 61 62 63 64
}

void OpalBeamline::getKFactors(const unsigned int &index, const Vector_t &pos, const long &sindex, const double &t, Vector_t &KR, Vector_t &KT) {

}

unsigned long OpalBeamline::getFieldAt(const unsigned int &index, const Vector_t &pos, const long &sindex, const double &t, Vector_t &E, Vector_t &B) {

    unsigned long rtv = 0x00;

65 66
    return rtv;
}
gsell's avatar
gsell committed
67

68 69 70 71 72 73
unsigned long OpalBeamline::getFieldAt(const Vector_t &position,
                                       const Vector_t &momentum,
                                       const double &t,
                                       Vector_t &Ef,
                                       Vector_t &Bf) {
    unsigned long rtv = 0x00;
gsell's avatar
gsell committed
74

75
    std::set<std::shared_ptr<Component>> elements = getElements(position);
76

77 78
    std::set<std::shared_ptr<Component>>::const_iterator it = elements.begin();
    const std::set<std::shared_ptr<Component>>::const_iterator end = elements.end();
gsell's avatar
gsell committed
79

80 81 82 83 84 85
    for (; it != end; ++ it) {
        ElementBase::ElementType type = (*it)->getType();
        if (type == ElementBase::MONITOR ||
            type == ElementBase::MARKER ||
            type == ElementBase::COLLIMATOR ||
            type == ElementBase::DIAGNOSTIC) continue;
gsell's avatar
gsell committed
86

87 88 89
        Vector_t localR = transformToLocalCS(*it, position);
        Vector_t localP = rotateToLocalCS(*it, momentum);
        Vector_t localE(0.0), localB(0.0);
gsell's avatar
gsell committed
90

91
        (*it)->applyToReferenceParticle(localR, localP, t, localE, localB);
gsell's avatar
gsell committed
92

93 94
        Ef += rotateFromLocalCS(*it, localE);
        Bf += rotateFromLocalCS(*it, localB);
gsell's avatar
gsell committed
95 96
    }

97 98 99
    //         if(section.hasWake()) {
    //             rtv |= BEAMLINE_WAKE;
    //         }
100 101
    //         if(section.hasParticleMaterInteraction()) {
    //             rtv |= BEAMLINE_PARTICLEMATERINTERACTION;
102
    //         }
gsell's avatar
gsell committed
103 104 105 106

    return rtv;
}

kraus's avatar
kraus committed
107
void OpalBeamline::switchElements(const double &min, const double &max, const double &kineticEnergy, const bool &nomonitors) {
108 109

    FieldList::iterator fprev;
gsell's avatar
gsell committed
110 111 112
    for(FieldList::iterator flit = elements_m.begin(); flit != elements_m.end(); ++ flit) {
        // don't set online monitors if the centroid of the bunch is allready inside monitor
        // or if explicitly not desired (eg during auto phasing)
113
        if(flit->getElement()->getType() == ElementBase::MONITOR) {
gsell's avatar
gsell committed
114 115 116
            double spos = (max + min) / 2.;
            if(!nomonitors && spos < (*flit).getStart()) {
                if(!(*flit).isOn() && max > (*flit).getStart()) {
kraus's avatar
kraus committed
117
                    (*flit).setOn(kineticEnergy);
gsell's avatar
gsell committed
118 119 120 121
                }
            }

        } else {
122
            if(!(*flit).isOn() && max > (*flit).getStart() && min < (*flit).getEnd()) {
kraus's avatar
kraus committed
123
                (*flit).setOn(kineticEnergy);
gsell's avatar
gsell committed
124
            }
125

126 127 128 129 130 131 132 133 134
            //check if multiple degraders follow one another with no other elements in between
            //if element is off and it is a degrader
            if (!(*flit).isOn() && flit->getElement()->getType() == ElementBase::DEGRADER) {
                //check if previous element: is on, is a degrader, ends where new element starts
                if ((*fprev).isOn() && fprev->getElement()->getType() == ElementBase::DEGRADER &&
                    ((*fprev).getEnd() + 0.01 > (*flit).getStart()) ) {
                    (*flit).setOn(kineticEnergy);
                }
            }
gsell's avatar
gsell committed
135
        }
136

137
	fprev = flit;
gsell's avatar
gsell committed
138 139 140 141 142 143 144
    }
}


void OpalBeamline::switchAllElements() {
    for(FieldList::iterator flit = elements_m.begin(); flit != elements_m.end(); ++ flit) {
        if(!(*flit).isOn()) {
kraus's avatar
kraus committed
145
            (*flit).setOn(-1.0);
gsell's avatar
gsell committed
146 147 148 149 150
        }
    }

}

151 152
void OpalBeamline::switchElementsOff(const double &min, ElementBase::ElementType eltype) {
    if(eltype == ElementBase::ANY) {
gsell's avatar
gsell committed
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
        for(FieldList::iterator flit = elements_m.begin(); flit != elements_m.end(); ++ flit) {
            if((*flit).isOn() && min >= (*flit).getEnd()) {
                (*flit).setOff();
            }

        }
    } else {
        for(FieldList::iterator flit = elements_m.begin(); flit != elements_m.end(); ++ flit) {
            if((*flit).isOn() && min >= (*flit).getEnd() && (*flit).getElement()->getType() == eltype) {
                (*flit).setOff();
            }
        }
    }
}

void OpalBeamline::switchElementsOff() {
    for(FieldList::iterator flit = elements_m.begin(); flit != elements_m.end(); ++ flit)
        (*flit).setOff();
}

void OpalBeamline::prepareSections() {
174 175 176 177
    if (elements_m.size() == 0) {
        prepared_m = true;
        return;
    }
178 179 180 181 182
    prepared_m = true;
}

void OpalBeamline::print(Inform &msg) const {
}
183

gsell's avatar
gsell committed
184

185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
double OpalBeamline::calcBeamlineLength() {
    return 0.0;
}

void OpalBeamline::swap(OpalBeamline & rhs) {
    std::swap(elements_m, rhs.elements_m);
    std::swap(prepared_m, rhs.prepared_m);
    std::swap(coordTransformationTo_m, rhs.coordTransformationTo_m);
}

void OpalBeamline::merge(OpalBeamline &rhs) {
    elements_m.insert(elements_m.end(),
                      rhs.elements_m.begin(),
                      rhs.elements_m.end());
    prepared_m = false;
    containsSource_m = containsSource_m || rhs.containsSource_m;
}


FieldList OpalBeamline::getElementByType(ElementBase::ElementType type) {
    if (type == ElementBase::ANY) {
        return elements_m;
gsell's avatar
gsell committed
207 208
    }

209 210 211 212
    FieldList elements_of_requested_type;
    for(FieldList::iterator fit = elements_m.begin(); fit != elements_m.end(); ++ fit) {
        if((*fit).getElement()->getType() == type) {
            elements_of_requested_type.push_back((*fit));
gsell's avatar
gsell committed
213 214
        }
    }
215 216
    return elements_of_requested_type;
}
gsell's avatar
gsell committed
217

218 219 220 221 222 223 224 225 226 227 228
void OpalBeamline::compute3DLattice() {
    static unsigned int order = 0;
    FieldList::iterator it = elements_m.begin();
    const FieldList::iterator end = elements_m.end();

    unsigned int minOrder = order;
    {
        double endPriorPathLength = 0.0;
        CoordinateSystemTrafo currentCoordTrafo = coordTransformationTo_m;

        elements_m.sort([](const ClassicField& a, const ClassicField& b) {
229 230 231 232 233 234
                double edgeA = 0.0, edgeB = 0.0;
                if (a.getElement()->isElementPositionSet())
                    edgeA = a.getElement()->getElementPosition();

                if (b.getElement()->isElementPositionSet())
                    edgeB = b.getElement()->getElementPosition();
235 236 237 238 239 240 241 242 243 244 245 246 247 248

                return edgeA < edgeB;
            });
        it = elements_m.begin();
        for (; it != end; ++ it) {
            if ((*it).isPositioned()) {
                continue;
            }
            (*it).order_m = minOrder;
            std::shared_ptr<Component> element = (*it).getElement();
            if (element->getType() == ElementBase::SBEND ||
                element->getType() == ElementBase::RBEND ||
                element->getType() == ElementBase::RBEND3D) {

249
                double beginThisPathLength = element->getElementPosition();
250 251 252 253 254 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
                Vector_t beginThis3D(0, 0, beginThisPathLength - endPriorPathLength);
                BendBase * bendElement = static_cast<BendBase*>(element.get());
                double thisLength = bendElement->getChordLength();
                double bendAngle = bendElement->getBendAngle();
                double entranceAngle = bendElement->getEntranceAngle();
                double arcLength = (thisLength * std::abs(bendAngle) / (2 * sin(std::abs(bendAngle) / 2)));

                double rotationAngleAboutZ = bendElement->getRotationAboutZ();
                Quaternion_t rotationAboutZ(cos(0.5 * rotationAngleAboutZ),
                                            sin(-0.5 * rotationAngleAboutZ) * Vector_t(0, 0, 1));

                Vector_t effectiveRotationAxis = rotationAboutZ.rotate(Vector_t(0, -1, 0));
                effectiveRotationAxis /= euclidian_norm(effectiveRotationAxis);

                Quaternion_t rotationAboutAxis(cos(0.5 * bendAngle),
                                               sin(0.5 * bendAngle) * effectiveRotationAxis);
                Quaternion_t halfRotationAboutAxis(cos(0.25 * bendAngle),
                                                   sin(0.25 * bendAngle) * effectiveRotationAxis);
                Quaternion_t entryFaceRotation(cos(0.5 * entranceAngle),
                                               sin(0.5 * entranceAngle) * effectiveRotationAxis);

                if (!Options::idealized) {
                    std::vector<Vector_t> truePath = bendElement->getDesignPath();
                    Quaternion_t directionExitHardEdge(cos(0.5 * (0.5 * bendAngle - entranceAngle)),
                                                       sin(0.5 * (0.5 * bendAngle - entranceAngle)) * effectiveRotationAxis);
                    Vector_t exitHardEdge = thisLength * directionExitHardEdge.rotate(Vector_t(0, 0, 1));
                    double distanceEntryHETruePath = euclidian_norm(truePath.front());
                    double distanceExitHETruePath = euclidian_norm(truePath.back() - exitHardEdge);
                    double pathLengthTruePath = (*it).getEnd() - (*it).getStart();
                    arcLength = pathLengthTruePath - distanceEntryHETruePath - distanceExitHETruePath;
gsell's avatar
gsell committed
280
                }
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295

                Vector_t chord = thisLength * halfRotationAboutAxis.rotate(Vector_t(0, 0, 1));
                Vector_t endThis3D = beginThis3D + chord;
                double endThisPathLength = beginThisPathLength + arcLength;

                CoordinateSystemTrafo fromEndLastToBeginThis(beginThis3D,
                                                             (entryFaceRotation * rotationAboutZ).conjugate());
                CoordinateSystemTrafo fromEndLastToEndThis(endThis3D,
                                                           rotationAboutAxis.conjugate());

                (*it).setCoordTransformationTo(fromEndLastToBeginThis * currentCoordTrafo);

                currentCoordTrafo = (fromEndLastToEndThis * currentCoordTrafo);

                endPriorPathLength = endThisPathLength;
gsell's avatar
gsell committed
296 297 298 299
            }
        }
    }

300 301 302 303 304 305 306 307 308 309
    double endPriorPathLength = 0.0;
    CoordinateSystemTrafo currentCoordTrafo = coordTransformationTo_m;

    it = elements_m.begin();
    for (; it != end; ++ it) {
        if ((*it).isPositioned()) continue;

        (*it).order_m = order ++;

        std::shared_ptr<Component> element = (*it).getElement();
310
        double beginThisPathLength = element->getElementPosition();
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
        double thisLength = element->getElementLength();
        Vector_t beginThis3D(0, 0, beginThisPathLength - endPriorPathLength);

        if (element->getType() == ElementBase::MONITOR) {
            beginThis3D(2) -= 0.5 * thisLength;
        }

        Vector_t endThis3D;
        if (element->getType() == ElementBase::SBEND ||
            element->getType() == ElementBase::RBEND ||
            element->getType() == ElementBase::RBEND3D) {

            BendBase * bendElement = static_cast<BendBase*>(element.get());
            thisLength = bendElement->getChordLength();
            double bendAngle = bendElement->getBendAngle();

            double rotationAngleAboutZ = bendElement->getRotationAboutZ();
            Quaternion_t rotationAboutZ(cos(0.5 * rotationAngleAboutZ),
                                        sin(0.5 * rotationAngleAboutZ) * Vector_t(0, 0, 1));

            Vector_t rotationAxis = rotationAboutZ.rotate(Vector_t(0, -1, 0));
            rotationAxis /= euclidian_norm(rotationAxis);
            Quaternion_t rotationAboutAxis(cos(0.5 * bendAngle),
                                           sin(0.5 * bendAngle) * rotationAxis);
            Quaternion halfRotationAboutAxis(cos(0.25 * bendAngle),
                                             sin(0.25 * bendAngle) * rotationAxis);

            double arcLength = (thisLength * std::abs(bendAngle) /
                                (2 * sin(bendAngle / 2)));
            if (!Options::idealized) {
                std::vector<Vector_t> truePath = bendElement->getDesignPath();
                double entranceAngle = bendElement->getEntranceAngle();
                Quaternion_t directionExitHardEdge(cos(0.5 * (0.5 * bendAngle - entranceAngle)),
                                                   sin(0.5 * (0.5 * bendAngle - entranceAngle)) * rotationAxis);
                Vector_t exitHardEdge = thisLength * directionExitHardEdge.rotate(Vector_t(0, 0, 1));
                double distanceEntryHETruePath = euclidian_norm(truePath.front());
                double distanceExitHETruePath = euclidian_norm(truePath.back() - exitHardEdge);
                double pathLengthTruePath = (*it).getEnd() - (*it).getStart();
                arcLength = pathLengthTruePath - distanceEntryHETruePath - distanceExitHETruePath;
gsell's avatar
gsell committed
350
            }
351 352 353 354 355 356 357 358 359 360 361

            endThis3D = (beginThis3D +
                         halfRotationAboutAxis.rotate(Vector_t(0, 0, thisLength)));
            CoordinateSystemTrafo fromEndLastToEndThis(endThis3D,
                                                       rotationAboutAxis.conjugate());
            currentCoordTrafo = fromEndLastToEndThis * currentCoordTrafo;

            endPriorPathLength = beginThisPathLength + arcLength;
        } else {
            Quaternion rotation(1, 0, 0, 0);

362 363 364
            if (element->getType() == ElementBase::COLLIMATOR) {
                FieldList::iterator priorDipole = partiallyInsideDipole(it, elements_m.begin(), elements_m.end(), minOrder);
                Collimator *col = static_cast<Collimator*>((*it).getElement().get());
365

366 367 368
                if (priorDipole != it && col->getWarpFlag()) {
                    Bend * bendElement = static_cast<Bend*>((*priorDipole).getElement().get());
                    double pathDifference = beginThisPathLength - bendElement->getElementPosition();
369

370 371
                    auto designPath = bendElement->getPartialDesignPath(pathDifference, thisLength);
                    Vector_t orientation = designPath[1] - designPath[0];
372

373 374
                    rotation = getQuaternion(orientation,
                                             Vector_t(0, 0, 1));
375

376 377
                    CoordinateSystemTrafo cst(designPath.front(), rotation);
                    (*it).setCoordTransformationTo(cst);
378

379 380 381 382 383 384 385 386 387 388
                    for (auto it = designPath.begin(); it != designPath.end(); ++ it) {
                        (*it) = cst.transformTo(*it);
                    }

                    col->setWarpCurve(designPath);

                    *gmsg << __DBGMSG__ << cst.transformFrom(Vector_t(0.0)) << "\t" << cst.rotateFrom(Vector_t(0, 0, 1)) << "\t" << minOrder << endl;
                    continue;
                }
            }
389 390 391 392 393 394 395
            double rotationAngleAboutZ = (*it).getElement()->getRotationAboutZ();
            Quaternion_t rotationAboutZ(cos(0.5 * rotationAngleAboutZ),
                                        sin(-0.5 * rotationAngleAboutZ) * Vector_t(0, 0, 1));

            CoordinateSystemTrafo fromLastToThis(beginThis3D, rotationAboutZ * rotation);

            (*it).setCoordTransformationTo(fromLastToThis * currentCoordTrafo);
gsell's avatar
gsell committed
396
        }
397 398 399 400 401 402 403 404 405 406 407

        (*it).fixPosition();
    }

    elements_m.sort(ClassicField::SortAsc);
}

void OpalBeamline::plot3DLattice() {
    if (Ippl::myNode() != 0) return;

    elements_m.sort([](const ClassicField& a, const ClassicField& b) {
408 409 410 411 412 413 414 415
            double edgeA = 0.0, edgeB = 0.0;
            if (a.getElement()->isElementPositionSet())
                edgeA = a.getElement()->getElementPosition();

            if (b.getElement()->isElementPositionSet())
                edgeB = b.getElement()->getElementPosition();

            return edgeA < edgeB;
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
        });

    FieldList::iterator it = elements_m.begin();
    FieldList::iterator end = elements_m.end();

    Quaternion rotDiagonal(0.5, 0.5 * Vector_t(-1, 1, -1));

    Vector_t origin = rotDiagonal.rotate(coordTransformationTo_m.getOrigin());
    Vector_t direction = rotDiagonal.rotate(coordTransformationTo_m.rotateFrom(Vector_t(0, 0, 1)));
    Vector_t minX = Vector_t(999999.9), maxX(-999999.9);
    std::map<std::string, std::vector<Vector_t > > elementCorners;

    for (; it != end; ++ it) {
        std::shared_ptr<Component> element = (*it).getElement();
        CoordinateSystemTrafo toBegin = (*it).getCoordTransformationTo();
        std::vector<Vector_t> corners;

        if (element->getType() == ElementBase::RBEND || element->getType() == ElementBase::SBEND) {
            std::vector<Vector_t> outline = static_cast<const Bend*>(element.get())->getOutline();

            for (auto point: outline) {
                corners.push_back(rotDiagonal.rotate(toBegin.transformFrom(point)));
438
            }
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
        } else {
            CoordinateSystemTrafo toEnd = element->getBeginToEnd() * toBegin;
            auto aperture = element->getAperture();
            double elementHeightFront = aperture.second[0];
            double elementHeightBack = aperture.second[0] * aperture.second[2];

            corners.push_back(rotDiagonal.rotate(toEnd.transformFrom(Vector_t(0.0))));
            corners.push_back(rotDiagonal.rotate(toBegin.transformFrom(Vector_t(0))));
            corners.push_back(rotDiagonal.rotate(toBegin.transformFrom(-elementHeightFront * Vector_t(1, 0, 0))));
            corners.push_back(rotDiagonal.rotate(toEnd.transformFrom(-elementHeightBack * Vector_t(1, 0, 0))));
            corners.push_back(rotDiagonal.rotate(toEnd.transformFrom(Vector_t(0.0))));
            corners.push_back(rotDiagonal.rotate(toEnd.transformFrom(elementHeightBack * Vector_t(1, 0, 0))));
            corners.push_back(rotDiagonal.rotate(toBegin.transformFrom(elementHeightFront * Vector_t(1, 0, 0))));
            corners.push_back(rotDiagonal.rotate(toBegin.transformFrom(Vector_t(0))));
        }

        elementCorners.insert(std::make_pair(element->getName(), corners));
        const unsigned int numCorners = corners.size();
        for (unsigned int i = 0 ; i < numCorners; ++ i) {
            const Vector_t & X = corners[i];

            if (X(0) < minX(0)) minX(0) = X(0);
            else if (X(0) > maxX(0)) maxX(0) = X(0);

            if (X(1) < minX(1)) minX(1) = X(1);
            else if (X(1) > maxX(1)) maxX(1) = X(1);
465
        }
gsell's avatar
gsell committed
466 467
    }

468
    it = elements_m.begin();
gsell's avatar
gsell committed
469

470 471 472 473 474 475
    double tau = (minX(0) - origin(0) - 0.3) / direction(0);
    origin += tau * direction;
    if (origin(0) < minX(0)) minX(0) = origin(0);
    if (origin(1) < minX(1)) minX(1) = origin(1);

    std::ofstream gpl;
476
    std::string fileName = "data/" + OpalData::getInstance()->getInputBasename() + "_ElementPositions.gpl";
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
    if (Options::openMode == Options::APPEND && boost::filesystem::exists(fileName)) {
        gpl.open(fileName, std::ios_base::app);
    } else {
        gpl.open(fileName);
    }
    gpl.precision(8);

    for (; it != end; ++ it) {
        std::shared_ptr<Component> element = (*it).getElement();

        if (element->getType() != ElementBase::DRIFT) {
            const std::vector<Vector_t> &corners = elementCorners[element->getName()];
            const unsigned int numCorners = corners.size();

            gpl << "# " << element->getName() << "\n";
            for (unsigned int i = 0; i < numCorners; ++ i) {
                gpl << std::setw(18) << corners[i](0)
                    << std::setw(18) << -corners[i](1) << "\n";
gsell's avatar
gsell committed
495
            }
496 497
            gpl << std::setw(18) << corners.front()(0)
                << std::setw(18) << -corners.front()(1) << "\n\n";
gsell's avatar
gsell committed
498 499 500
        }
    }

501 502 503 504 505 506 507 508 509 510 511 512 513 514
    elements_m.sort(ClassicField::SortAsc);
}

void OpalBeamline::save3DLattice() {
    if (Ippl::myNode() != 0) return;

    elements_m.sort([](const ClassicField& a, const ClassicField& b) {
            return a.order_m < b.order_m;
        });

    FieldList::iterator it = elements_m.begin();
    FieldList::iterator end = elements_m.end();

    std::ofstream pos;
515
    std::string fileName = "data/" + OpalData::getInstance()->getInputBasename() + "_ElementPositions.txt";
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
    if (Options::openMode == Options::APPEND && boost::filesystem::exists(fileName)) {
        pos.open(fileName, std::ios_base::app);
    } else {
        pos.open(fileName);
    }

    MeshGenerator mesh;
    for (; it != end; ++ it) {
        std::shared_ptr<Component> element = (*it).getElement();
        CoordinateSystemTrafo toEnd = element->getBeginToEnd() * (*it).getCoordTransformationTo();
        Vector_t entry3D = (*it).getCoordTransformationTo().getOrigin();
        Vector_t exit3D = toEnd.getOrigin();

        mesh.add(*(element.get()));

        if (element->getType() == ElementBase::SBEND ||
            element->getType() == ElementBase::RBEND) {

            Bend * bendElement = static_cast<Bend*>(element.get());
            std::vector<Vector_t> designPath = bendElement->getDesignPath();

            unsigned int size = designPath.size();
            unsigned int minNumSteps = std::max(20.0,
                                                std::abs(bendElement->getBendAngle() / Physics::pi * 180));
            unsigned int frequency = std::floor((double)size / minNumSteps);

            pos << std::setw(30) << std::left << std::string("\"ENTRY EDGE: ") + element->getName() + std::string("\"")
                << std::setw(18) << std::setprecision(10) << entry3D(2)
                << std::setw(18) << std::setprecision(10) << entry3D(0)
                << std::setw(18) << std::setprecision(10) << entry3D(1)
                << "\n";

            Vector_t position = (*it).getCoordTransformationTo().transformFrom(designPath.front());
            pos << std::setw(30) << std::left << std::string("\"BEGIN: ") + element->getName() + std::string("\"")
                << std::setw(18) << std::setprecision(10) << position(2)
                << std::setw(18) << std::setprecision(10) << position(0)
                << std::setw(18) << std::setprecision(10) << position(1)
                << std::endl;

            for (unsigned int i = frequency; i + 1 < size; i += frequency) {

                Vector_t position = (*it).getCoordTransformationTo().transformFrom(designPath[i]);
                pos << std::setw(30) << std::left << std::string("\"MID: ") + element->getName() + std::string("\"")
                    << std::setw(18) << std::setprecision(10) << position(2)
                    << std::setw(18) << std::setprecision(10) << position(0)
                    << std::setw(18) << std::setprecision(10) << position(1)
                    << endl;
            }

            position = (*it).getCoordTransformationTo().transformFrom(designPath.back());
            pos << std::setw(30) << std::left << std::string("\"END: ") + element->getName() + std::string("\"")
                << std::setw(18) << std::setprecision(10) << position(2)
                << std::setw(18) << std::setprecision(10) << position(0)
                << std::setw(18) << std::setprecision(10) << position(1)
                << std::endl;

            pos << std::setw(30) << std::left << std::string("\"EXIT EDGE: ") + element->getName() + std::string("\"")
                << std::setw(18) << std::setprecision(10) << exit3D(2)
                << std::setw(18) << std::setprecision(10) << exit3D(0)
                << std::setw(18) << std::setprecision(10) << exit3D(1)
                << std::endl;
        } else {
            pos << std::setw(30) << std::left << std::string("\"BEGIN: ") + element->getName() + std::string("\"")
                << std::setw(18) << std::setprecision(10) << entry3D(2)
                << std::setw(18) << std::setprecision(10) << entry3D(0)
                << std::setw(18) << std::setprecision(10) << entry3D(1)
                << "\n";

            pos << std::setw(30) << std::left << std::string("\"END: ") + element->getName() + std::string("\"")
                << std::setw(18) << std::setprecision(10) << exit3D(2)
                << std::setw(18) << std::setprecision(10) << exit3D(0)
                << std::setw(18) << std::setprecision(10) << exit3D(1)
                << std::endl;
        }
gsell's avatar
gsell committed
590
    }
591 592
    elements_m.sort(ClassicField::SortAsc);
    mesh.write(OpalData::getInstance()->getInputBasename());
gsell's avatar
gsell committed
593 594
}

595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
std::string parseInput() {

    std::ifstream in(OpalData::getInstance()->getInputFn());
    std::string source("");
    std::string str;
    char testBit;
    const std::string commentFormat("");
    const boost::regex empty("^[ \t]*$");
    const boost::regex lineEnd(";");
    const std::string lineEndFormat(";\n");
    const boost::regex cppCommentExpr("//.*");
    const boost::regex cCommentExpr("/\\*.*?\\*/"); // "/\\*(?>[^*/]+|\\*[^/]|/[^*])*(?>(?R)(?>[^*/]+|\\*[^/]|/[^*])*)*\\*/"
    bool priorEmpty = true;

    in.get(testBit);
    while (!in.eof()) {
        in.putback(testBit);

        std::getline(in, str);
        str = boost::regex_replace(str, cppCommentExpr, commentFormat);
        str = boost::regex_replace(str, empty, commentFormat);
        if (str.size() > 0) {
            source += str;// + '\n';
            priorEmpty = false;
        } else if (!priorEmpty) {
            source += "##EMPTY_LINE##";
            priorEmpty = true;
        }

        in.get(testBit);
    }
gsell's avatar
gsell committed
626

627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
    source = boost::regex_replace(source, cCommentExpr, commentFormat);
    source = boost::regex_replace(source, lineEnd, lineEndFormat, boost::match_default | boost::format_all);

    return source;
}

unsigned int getMinimalSignificantDigits(double num, const unsigned int maxDigits) {
    char buf[32];
    snprintf(buf, 32, "%.*f", maxDigits + 1, num);
    string numStr(buf);
    unsigned int length = numStr.length();

    unsigned int numDigits = maxDigits;
    unsigned int i = 2;
    while (i < maxDigits + 1 && numStr[length - i] == '0') {
        --numDigits;
        ++ i;
gsell's avatar
gsell committed
644
    }
645 646 647 648 649 650 651 652 653 654

    return numDigits;
}

std::string round2string(double num, const unsigned int maxDigits) {
    char buf[64];

    snprintf(buf, 64, "%.*f", getMinimalSignificantDigits(num, maxDigits), num);

    return std::string(buf);
gsell's avatar
gsell committed
655 656
}

657 658 659 660 661 662 663
void OpalBeamline::save3DInput() {
    if (Ippl::myNode() != 0) return;

    FieldList::iterator it = elements_m.begin();
    FieldList::iterator end = elements_m.end();

    std::string input = parseInput();
664
    std::ofstream pos("data/" + OpalData::getInstance()->getInputBasename() + "_3D.opal");
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681

    for (; it != end; ++ it) {
        std::string element = (*it).getElement()->getName();
        const boost::regex replacePSI("(" + element + "\\s*:[^\\n]*)PSI\\s*=[^,;]*,?", boost::regex::icase);
        input = boost::regex_replace(input, replacePSI, "\\1\\2");

        const boost::regex replaceELEMEDGE("(" + element + "\\s*:[^\\n]*)ELEMEDGE\\s*=[^,;]*(.)", boost::regex::icase);

        CoordinateSystemTrafo cst = (*it).getCoordTransformationTo();
        Vector_t origin = cst.getOrigin();
        Vector_t orient = Util::getTaitBryantAngles(cst.getRotation().conjugate(), element);
        for (unsigned int d = 0; d < 3; ++ d)
            orient(d) *= Physics::rad2deg;

        std::string x = (std::abs(origin(0)) > 1e-10? "X = " + round2string(origin(0), 10) + ", ": "");
        std::string y = (std::abs(origin(1)) > 1e-10? "Y = " + round2string(origin(1), 10) + ", ": "");
        std::string z = (std::abs(origin(2)) > 1e-10? "Z = " + round2string(origin(2), 10) + ", ": "");
gsell's avatar
gsell committed
682

683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
        std::string theta = (orient(0) > 1e-10? "THETA = " + round2string(orient(0), 6) + " * PI / 180, ": "");
        std::string phi = (orient(1) > 1e-10? "PHI = " + round2string(orient(1), 6) + " * PI / 180, ": "");
        std::string psi = (orient(2) > 1e-10? "PSI = " + round2string(orient(2), 6) + " * PI / 180, ": "");
        std::string coordTrafo = x + y + z + theta + phi + psi;
        if (coordTrafo.length() > 2) {
            coordTrafo = coordTrafo.substr(0, coordTrafo.length() - 2); // remove last ', '
        }

        std::string position = ("\\1" + coordTrafo + "\\2");

        input = boost::regex_replace(input, replaceELEMEDGE, position);

        if ((*it).getElement()->getType() == ElementBase::RBEND ||
            (*it).getElement()->getType() == ElementBase::SBEND) {
            const Bend* dipole = static_cast<const Bend*>((*it).getElement().get());
            double angle = dipole->getBendAngle();
            double E1 = dipole->getEntranceAngle();
            double E2 = dipole->getExitAngle();

            const boost::regex angleR("(" + element + "\\s*:[^\\n]*ANGLE\\s*=)[^,;]*(.)");
            const std::string angleF("\\1 " + round2string(angle * 180 / Physics::pi, 6) + " / 180 * PI\\2");
            const boost::regex E1R("(" + element + "\\s*:[^\\n]*E1\\s*=)[^,;]*(.)");
            const std::string E1F("\\1 " + round2string(E1 * 180 / Physics::pi, 6) + " / 180 * PI\\2");
            const boost::regex E2R("(" + element + "\\s*:[^\\n]*E2\\s*=)[^,;]*(.)");
            const std::string E2F("\\1 " + round2string(E2 * 180 / Physics::pi, 6) + " / 180 * PI\\2");
            const boost::regex noRotation("(" + element + "\\s*:[^\\n]*),\\s*ROTATION\\s*=[^,;]*(.)");
            const std::string noRotationFormat("\\1\\2  ");

            input = boost::regex_replace(input, angleR, angleF);
            input = boost::regex_replace(input, E1R, E1F);
            input = boost::regex_replace(input, E2R, E2F);
            input = boost::regex_replace(input, noRotation, noRotationFormat);
        }
gsell's avatar
gsell committed
716
    }
717 718 719 720 721 722

    const boost::regex empty("##EMPTY_LINE##");
    const std::string emptyFormat("\n");
    input = boost::regex_replace(input, empty, emptyFormat);

    pos << input << std::endl;
gsell's avatar
gsell committed
723 724
}

725 726 727 728 729
FieldList::iterator OpalBeamline::partiallyInsideDipole(const FieldList::iterator &it,
                                                        const FieldList::iterator &begin,
                                                        const FieldList::iterator &end,
                                                        const unsigned int &minOrder) {
    if (it == begin) return it;
gsell's avatar
gsell committed
730

731 732 733 734 735 736
    FieldList::iterator prior = it;
    -- prior;

    while (true) {
        std::shared_ptr<Component> element = (*prior).getElement();

737 738 739 740
        if (element->getType() == ElementBase::SBEND ||
            element->getType() == ElementBase::RBEND) {
            *gmsg << __DBGMSG__ << element->getName() << "\t" << element->getElementPosition() << "\t" << (*prior).getEnd() << "\t"
                  << (*it).getElement()->getName() << "\t" << (*it).getElement()->getElementPosition() << endl;
gsell's avatar
gsell committed
741
        }
742 743 744

        if (prior == begin) break;
        -- prior;
gsell's avatar
gsell committed
745
    }
746 747

    while (true) {
748
        std::shared_ptr<Component> element = (*prior).getElement();
749

750 751 752 753
        if (element->getType() == ElementBase::SBEND ||
            element->getType() == ElementBase::RBEND) {
            *gmsg << __DBGMSG__ << element->getName() << "\t" << (*prior).getEnd() << "\t"
                  << (*it).getElement()->getName() << "\t" << (*it).getElement()->getElementPosition() << endl;
754 755
        }

756 757 758 759 760 761 762
        if ((*prior).getEnd() < (*it).getElement()->getElementPosition()) break;

        if (element->getType() == ElementBase::SBEND ||
            element->getType() == ElementBase::RBEND) {

            return prior;
        }
763

764 765
        if (prior == begin) break;
        -- prior;
766 767 768
    }

    return it;
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792

    // if (it == end) return it;
    // FieldList::iterator next = it;
    // ++ next;
    // if (next == end) return it;

    // while (true) {
    //     std::shared_ptr<Component> element = (*next).getElement();

    //     if ((element->getType() == ElementBase::SBEND ||
    //          element->getType() == ElementBase::RBEND) &&
    //         (*it).getElement()->getElementPosition() > (*next).getStart() &&
    //         (*it).getElement()->getElementPosition() < (*next).getEnd()) {

    //         if ((*next).order_m >= minOrder)
    //             return next;
    //     }

    //     ++ next;

    //     if (next == end) break;
    // }

    // return it;
kraus's avatar
kraus committed
793
}
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810

void OpalBeamline::activateElements() {
    auto it = elements_m.begin();
    const auto end = elements_m.end();

    double designEnergy = 0.0;
    for (; it != end; ++ it) {
        std::shared_ptr<Component> element = (*it).getElement();
        if (element->getType() == ElementBase::SBEND ||
            element->getType() == ElementBase::RBEND) {
            Bend * bendElement = static_cast<Bend*>(element.get());
            designEnergy = bendElement->getDesignEnergy() * 1e-6;
        }
        (*it).setOn(designEnergy);
        // element->goOnline(designEnergy);
    }
}