OpalBeamline.cpp 32.4 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
#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>
gsell's avatar
gsell committed
12 13 14 15
using namespace std;

OpalBeamline::OpalBeamline():
    elements_m(),
16
    prepared_m(false),
17 18 19 20 21 22 23 24 25 26
    containsSource_m(false)
{
}

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

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

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

37 38 39 40 41 42 43
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);
44

45 46
        if (element->isInside(r)) {
            elementSet.insert(element);
gsell's avatar
gsell committed
47 48 49
        }
    }

50
    return elementSet;
gsell's avatar
gsell committed
51 52 53 54 55 56 57 58 59 60
}

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;

61 62
    return rtv;
}
gsell's avatar
gsell committed
63

64 65 66 67 68 69
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
70

71
    std::set<std::shared_ptr<Component>> elements = getElements(position);
72

73 74
    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
75

76 77 78 79
    for (; it != end; ++ it) {
        ElementBase::ElementType type = (*it)->getType();
        if (type == ElementBase::MONITOR ||
            type == ElementBase::MARKER ||
80
            type == ElementBase::CCOLLIMATOR ||
81
            type == ElementBase::DIAGNOSTIC) continue;
gsell's avatar
gsell committed
82

83 84 85
        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
86

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

89 90
        Ef += rotateFromLocalCS(*it, localE);
        Bf += rotateFromLocalCS(*it, localB);
gsell's avatar
gsell committed
91 92
    }

93 94 95
    //         if(section.hasWake()) {
    //             rtv |= BEAMLINE_WAKE;
    //         }
96
    //         if(section.hasParticleMatterInteraction()) {
97
    //             rtv |= BEAMLINE_PARTICLEMATTERINTERACTION;
98
    //         }
gsell's avatar
gsell committed
99 100 101 102

    return rtv;
}

kraus's avatar
kraus committed
103
void OpalBeamline::switchElements(const double &min, const double &max, const double &kineticEnergy, const bool &nomonitors) {
104 105

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

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

122 123 124 125 126 127 128 129 130
            //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
131
        }
132

133
	fprev = flit;
gsell's avatar
gsell committed
134 135 136 137 138 139 140
    }
}


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

}

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

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

gsell's avatar
gsell committed
180

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

205 206 207 208
    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
209 210
        }
    }
211 212
    return elements_of_requested_type;
}
gsell's avatar
gsell committed
213

214 215 216 217 218 219 220 221 222 223 224
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) {
225 226 227 228 229 230
                double edgeA = 0.0, edgeB = 0.0;
                if (a.getElement()->isElementPositionSet())
                    edgeA = a.getElement()->getElementPosition();

                if (b.getElement()->isElementPositionSet())
                    edgeB = b.getElement()->getElementPosition();
231 232 233 234 235 236 237 238 239 240 241 242 243 244

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

245
                double beginThisPathLength = element->getElementPosition();
246 247 248 249 250 251 252 253 254 255 256 257
                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));
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
258
                effectiveRotationAxis /= euclidean_norm(effectiveRotationAxis);
259 260 261 262 263 264 265 266 267 268 269 270 271

                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));
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
272
                    double distanceEntryHETruePath = euclidean_norm(truePath.front());
273
                    double distanceExitHETruePath = euclidean_norm(rotationAboutZ.rotate(truePath.back()) - exitHardEdge);
274 275
                    double pathLengthTruePath = (*it).getEnd() - (*it).getStart();
                    arcLength = pathLengthTruePath - distanceEntryHETruePath - distanceExitHETruePath;
gsell's avatar
gsell committed
276
                }
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291

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

296 297 298 299 300 301 302 303 304 305
    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();
306
        double beginThisPathLength = element->getElementPosition();
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
        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),
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
325 326 327
                                        sin(-0.5 * rotationAngleAboutZ) * Vector_t(0, 0, 1));

            Vector_t effectiveRotationAxis = rotationAboutZ.rotate(Vector_t(0, -1, 0));
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
328
            effectiveRotationAxis /= euclidean_norm(effectiveRotationAxis);
329 330

            Quaternion_t rotationAboutAxis(cos(0.5 * bendAngle),
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
331
                                           sin(0.5 * bendAngle) * effectiveRotationAxis);
332
            Quaternion halfRotationAboutAxis(cos(0.25 * bendAngle),
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
333
                                             sin(0.25 * bendAngle) * effectiveRotationAxis);
334 335 336 337 338 339 340

            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)),
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
341
                                                   sin(0.5 * (0.5 * bendAngle - entranceAngle)) * effectiveRotationAxis);
342
                Vector_t exitHardEdge = thisLength * directionExitHardEdge.rotate(Vector_t(0, 0, 1));
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
343
                double distanceEntryHETruePath = euclidean_norm(truePath.front());
344
                double distanceExitHETruePath = euclidean_norm(rotationAboutZ.rotate(truePath.back()) - exitHardEdge);
345 346
                double pathLengthTruePath = (*it).getEnd() - (*it).getStart();
                arcLength = pathLengthTruePath - distanceEntryHETruePath - distanceExitHETruePath;
gsell's avatar
gsell committed
347
            }
348 349 350 351 352 353 354 355 356

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

            endPriorPathLength = beginThisPathLength + arcLength;
        } else {
Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
357
            // Quaternion rotation(1, 0, 0, 0);
358

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

361 362 363
            // if (priorDipole != it) {
            //     Bend * bendElement = static_cast<Bend*>((*priorDipole).getElement().get());
            //     double pathDifference = beginThisPathLength - bendElement->getElementPosition();
364

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

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

373 374 375 376 377
            //     CoordinateSystemTrafo fromLastToThis(beginThis3D, rotation);
            //     fromLastToThis *= currentCoordTrafo;
            //     Vector_t origin = fromLastToThis.getOrigin();
            //     Vector_t end = origin + thisLength * fromLastToThis.rotateFrom(Vector_t(0,0,1));
            // }
378 379 380 381 382

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

Christof Metzger-Kraus's avatar
Christof Metzger-Kraus committed
383
            CoordinateSystemTrafo fromLastToThis(beginThis3D, rotationAboutZ);// * rotation);
384 385

            (*it).setCoordTransformationTo(fromLastToThis * currentCoordTrafo);
gsell's avatar
gsell committed
386
        }
387 388 389 390 391 392 393 394

        (*it).fixPosition();
    }

    elements_m.sort(ClassicField::SortAsc);
}

void OpalBeamline::plot3DLattice() {
395 396
    auto opal = OpalData::getInstance();
    if (opal->isOptimizerRun() || Ippl::myNode() != 0) return;
397 398

    elements_m.sort([](const ClassicField& a, const ClassicField& b) {
399 400 401 402 403 404 405 406
            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;
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
        });

    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)));
429
            }
430
        } else {
431
            CoordinateSystemTrafo toEnd = element->getEdgeToEnd() * toBegin;
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
            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);
456
        }
gsell's avatar
gsell committed
457 458
    }

459
    std::ofstream gpl;
460
    std::string fileName = "data/" + OpalData::getInstance()->getInputBasename() + "_ElementPositions.gpl";
461 462 463 464 465 466 467
    if (Options::openMode == Options::APPEND && boost::filesystem::exists(fileName)) {
        gpl.open(fileName, std::ios_base::app);
    } else {
        gpl.open(fileName);
    }
    gpl.precision(8);

468
    it = elements_m.begin();
469 470 471 472 473 474 475 476 477 478 479
    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
480
            }
481 482
            gpl << std::setw(18) << corners.front()(0)
                << std::setw(18) << -corners.front()(1) << "\n\n";
gsell's avatar
gsell committed
483 484 485
        }
    }

486 487 488 489
    elements_m.sort(ClassicField::SortAsc);
}

void OpalBeamline::save3DLattice() {
490
    if (Ippl::myNode() != 0 || OpalData::getInstance()->isOptimizerRun()) return;
491 492 493 494 495 496 497 498 499

    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;
500
    std::string fileName = "data/" + OpalData::getInstance()->getInputBasename() + "_ElementPositions.txt";
501 502 503 504 505 506 507 508 509
    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();
510 511 512
        CoordinateSystemTrafo toBegin = element->getEdgeToBegin() * (*it).getCoordTransformationTo();
        CoordinateSystemTrafo toEnd = element->getEdgeToEnd() * (*it).getCoordTransformationTo();
        Vector_t entry3D = toBegin.getOrigin();
513 514 515 516 517 518 519 520 521
        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();
522 523
            CoordinateSystemTrafo toEnd = bendElement->getBeginToEnd_local() * (*it).getCoordTransformationTo();
            Vector_t exit3D = toEnd.getOrigin();
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

            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
578
    }
579 580
    elements_m.sort(ClassicField::SortAsc);
    mesh.write(OpalData::getInstance()->getInputBasename());
gsell's avatar
gsell committed
581 582
}

583 584 585 586 587 588 589 590 591 592 593 594 595 596
namespace {
    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;
597 598

        in.get(testBit);
599 600 601 602 603 604 605 606 607 608 609 610 611
        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;
            }
gsell's avatar
gsell committed
612

613 614
            in.get(testBit);
        }
615

616 617
        source = boost::regex_replace(source, cCommentExpr, commentFormat);
        source = boost::regex_replace(source, lineEnd, lineEndFormat, boost::match_default | boost::format_all);
618

619
        return source;
gsell's avatar
gsell committed
620
    }
621

622 623 624 625 626 627 628 629 630 631 632 633
    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;
        }
634

635 636
        return numDigits;
    }
637

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

641 642 643 644
        snprintf(buf, 64, "%.*f", getMinimalSignificantDigits(num, maxDigits), num);

        return std::string(buf);
    }
gsell's avatar
gsell committed
645 646
}

647
void OpalBeamline::save3DInput() {
648
    if (Ippl::myNode() != 0 || OpalData::getInstance()->isOptimizerRun()) return;
649 650 651 652 653

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

    std::string input = parseInput();
654
    std::ofstream pos("data/" + OpalData::getInstance()->getInputBasename() + "_3D.opal");
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671

    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
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 698 699 700 701 702 703 704 705
        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
706
    }
707 708 709 710 711 712

    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
713 714
}

715 716 717 718 719
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
720

721 722 723 724 725 726
    FieldList::iterator prior = it;
    -- prior;

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

727 728 729 730 731 732
        if ((*prior).getEnd() > /*(*it).getStart()*/ (*it).getElement()->getElementPosition() &&
            (element->getType() == ElementBase::SBEND ||
             element->getType() == ElementBase::RBEND)) {

            if ((*prior).order_m >= minOrder)
                return prior;
gsell's avatar
gsell committed
733
        }
734 735 736

        if (prior == begin) break;
        -- prior;
gsell's avatar
gsell committed
737
    }
738

739 740 741 742
    if (it == end) return it;
    FieldList::iterator next = it;
    ++ next;
    if (next == end) return it;
743

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

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

752 753
            if ((*next).order_m >= minOrder)
                return next;
754
        }
755

756 757 758
        ++ next;

        if (next == end) break;
759 760 761
    }

    return it;
kraus's avatar
kraus committed
762
}
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779

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