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

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

extern Inform *gmsg;

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

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

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

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

40 41 42 43 44 45 46
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);
47

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

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

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;

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

67 68 69 70 71 72
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
73

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

76 77
    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
78

79 80 81 82 83 84
    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
85

86 87 88
        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
89

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

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

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

    return rtv;
}

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

    FieldList::iterator fprev;
gsell's avatar
gsell committed
109 110 111
    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)
112
        if(flit->getElement()->getType() == ElementBase::MONITOR) {
gsell's avatar
gsell committed
113 114 115
            double spos = (max + min) / 2.;
            if(!nomonitors && spos < (*flit).getStart()) {
                if(!(*flit).isOn() && max > (*flit).getStart()) {
kraus's avatar
kraus committed
116
                    (*flit).setOn(kineticEnergy);
gsell's avatar
gsell committed
117 118 119 120
                }
            }

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

125 126 127 128 129 130 131 132 133
            //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
134
        }
135

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


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

}

150 151
void OpalBeamline::switchElementsOff(const double &min, ElementBase::ElementType eltype) {
    if(eltype == ElementBase::ANY) {
gsell's avatar
gsell committed
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
        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() {
173 174 175 176
    if (elements_m.size() == 0) {
        prepared_m = true;
        return;
    }
177 178 179 180 181
    prepared_m = true;
}

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

gsell's avatar
gsell committed
183

184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
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
206 207
    }

208 209 210 211
    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
212 213
        }
    }
214 215
    return elements_of_requested_type;
}
gsell's avatar
gsell committed
216

217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
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) {
                double edgeA = a.getElement()->getAttribute("ELEMEDGE");
                double edgeB = b.getElement()->getAttribute("ELEMEDGE");

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

                double beginThisPathLength = element->getAttribute("ELEMEDGE");
                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
275
                }
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290

                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
291 292 293 294
            }
        }
    }

295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
    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();
        double beginThisPathLength = element->getAttribute("ELEMEDGE");
        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
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

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

            // FieldList::iterator priorDipole = partiallyInsideDipole(it, elements_m.begin(), elements_m.end(), minOrder);

            // if (priorDipole != it) {
            //     Bend * bendElement = static_cast<Bend*>((*priorDipole).getElement().get());
            //     double pathDifference = beginThisPathLength - bendElement->getAttribute("ELEMEDGE");

            //     auto secant = bendElement->getDesignPathSecant(pathDifference, thisLength);
            //     Vector_t position = (*priorDipole).getCoordTransformationTo().transformFrom(secant.first);
            //     Vector_t orientation = (*priorDipole).getCoordTransformationTo().rotateFrom(secant.second);

            //     beginThis3D = currentCoordTrafo.transformTo(position);
            //     rotation = getQuaternion(orientation,
            //                              currentCoordTrafo.rotateFrom(Vector_t(0, 0, 1)));

            //     CoordinateSystemTrafo fromLastToThis(beginThis3D, rotation);
            //     fromLastToThis *= currentCoordTrafo;
            //     Vector_t origin = fromLastToThis.getOrigin();
            //     Vector_t end = origin + thisLength * fromLastToThis.rotateFrom(Vector_t(0,0,1));
            // }

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

        (*it).fixPosition();
    }

    elements_m.sort(ClassicField::SortAsc);
}

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

    elements_m.sort([](const ClassicField& a, const ClassicField& b) {
            return a.getElement()->getAttribute("ELEMEDGE") < b.getElement()->getAttribute("ELEMEDGE");
            //return a.order_m < b.order_m;
        });

    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)));
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
        } 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);
447
        }
gsell's avatar
gsell committed
448 449
    }

450
    it = elements_m.begin();
gsell's avatar
gsell committed
451

452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
    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;
    std::string fileName = OpalData::getInstance()->getInputBasename() + "_ElementPositions.gpl";
    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
477
            }
478 479
            gpl << std::setw(18) << corners.front()(0)
                << std::setw(18) << -corners.front()(1) << "\n\n";
gsell's avatar
gsell committed
480 481 482
        }
    }

483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 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 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
    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;
    std::string fileName = OpalData::getInstance()->getInputBasename() + "_ElementPositions.txt";
    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
572
    }
573 574
    elements_m.sort(ClassicField::SortAsc);
    mesh.write(OpalData::getInstance()->getInputBasename());
gsell's avatar
gsell committed
575 576
}

577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
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
608

609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
    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
626
    }
627 628 629 630 631 632 633 634 635 636

    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
637 638
}

639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 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();
    std::ofstream pos(OpalData::getInstance()->getInputBasename() + "_3D.opal");

    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
664

665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
        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
698
    }
699 700 701 702 703 704

    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
705 706
}

707 708 709 710 711
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
712

713 714 715 716 717 718 719 720 721 722 723 724
    FieldList::iterator prior = it;
    -- prior;

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

        if ((*prior).getEnd() > /*(*it).getStart()*/ (*it).getElement()->getAttribute("ELEMEDGE") &&
            (element->getType() == ElementBase::SBEND ||
             element->getType() == ElementBase::RBEND)) {

            if ((*prior).order_m >= minOrder)
                return prior;
gsell's avatar
gsell committed
725
        }
726 727 728

        if (prior == begin) break;
        -- prior;
gsell's avatar
gsell committed
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

    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()->getAttribute("ELEMEDGE") > (*next).getStart() &&
            (*it).getElement()->getAttribute("ELEMEDGE") < (*next).getEnd()) {

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

        ++ next;

        if (next == end) break;
    }

    return it;
kraus's avatar
kraus committed
754
}
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771

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