ClosedOrbitFinder.h 34.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
//
// Class ClosedOrbitFinder
//   This class finds a closed orbit of a cyclotron for a given energy.
//   The algorithm is based on the paper of M. M. Gordon: "Computation of
//   closed orbits and basic focusing properties for sector-focused cyclotrons
//   and the design of 'cyclops'" (1983)
//   As template arguments one chooses the type of the variables and the
//   integrator for the ODEs. The supported steppers can be found on
//   http://www.boost.org/ where it is part of the library Odeint.
//
// Copyright (c) 2014, Matthias Frey, ETH Zürich
// All rights reserved
//
// Implemented as part of the Semester thesis by Matthias Frey
// "Matched Distributions in Cyclotrons"
//
// This file is part of OPAL.
//
// OPAL is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// You should have received a copy of the GNU General Public License
// along with OPAL. If not, see <https://www.gnu.org/licenses/>.
//
27 28 29
#ifndef CLOSEDORBITFINDER_H
#define CLOSEDORBITFINDER_H

30
#include <algorithm>
31 32 33
#include <array>
#include <cmath>
#include <functional>
adelmann's avatar
adelmann committed
34
#include <limits>
35
#include <numeric>
adelmann's avatar
adelmann committed
36
#include <string>
37
#include <utility>
38 39
#include <vector>

40
#include "Utilities/Options.h"
41 42 43
#include "Utilities/Options.h"
#include "Utilities/OpalException.h"

frey_m's avatar
frey_m committed
44 45
#include "AbstractObjects/OpalData.h"

46
#include "AbsBeamline/Cyclotron.h"
frey_m's avatar
frey_m committed
47

48 49
// include headers for integration
#include <boost/numeric/odeint/integrate/integrate_n_steps.hpp>
frey_m's avatar
frey_m committed
50 51 52
#include <boost/filesystem.hpp>

extern Inform *gmsg;
53 54 55 56

template<typename Value_type, typename Size_type, class Stepper>
class ClosedOrbitFinder
{
57 58 59 60 61 62 63 64 65
    public:
        /// Type of variables
        typedef Value_type value_type;
        /// Type for specifying sizes
        typedef Size_type size_type;
        /// Type of container for storing quantities (path length, orbit, etc.)
        typedef std::vector<value_type> container_type;
        /// Type for holding state of ODE values
        typedef std::vector<value_type> state_type;
snuverink_j's avatar
snuverink_j committed
66

frey_m's avatar
frey_m committed
67
        typedef std::function<void(const state_type&, state_type&, const double)> function_t;
68 69 70

        /// Sets the initial values for the integration and calls findOrbit().
        /*!
71
         * @param E0 is the potential energy (particle energy at rest) [MeV].
adelmann's avatar
adelmann committed
72
         * @param N specifies the number of splits (2pi/N), i.e number of integration steps
73
         * @param cycl is the cyclotron element
74 75
         * @param domain is a boolean (default: true). If "true" the closed orbit is computed over a single sector,
         * otherwise over 2*pi.
76 77
         * @param Nsectors is an int (default: 1). Number of sectors that the field map is averaged over
         * in order to avoid first harmonic. Only valid if domain is false
78
         */
frey_m's avatar
frey_m committed
79
        ClosedOrbitFinder(value_type E0, size_type N,
80
                          Cyclotron* cycl, bool domain = true, int Nsectors = 1);
81 82

        /// Returns the inverse bending radius (size of container N+1)
83
        container_type getInverseBendingRadius(const value_type& angle = 0);
84 85

        /// Returns the step lengths of the path (size of container N+1)
86
        container_type getPathLength(const value_type& angle = 0);
87 88

        /// Returns the field index (size of container N+1)
89
        container_type getFieldIndex(const value_type& angle = 0);
90 91 92 93

        /// Returns the radial and vertical tunes (in that order)
        std::pair<value_type,value_type> getTunes();

94 95 96 97 98 99 100
        /// Returns the closed orbit (size of container N+1) starting at specific angle (only makes sense when computing
        /// the closed orbit for a whole turn) (default value: 0°).
        /// Attention: It computes the starting index of the array. If it's not an integer it just cuts the floating point
        /// part, i.e. it takes the next starting index below. There's no interpolation of the radius.
        /*!
         * @param angle is the start angle for the output. Has to be within [0°,360°[ (default: 0°).
         */
101 102
        container_type getOrbit(value_type angle = 0);

103 104 105 106 107 108
        /// Returns the momentum of the orbit (size of container N+1)starting at specific angle (only makes sense when
        /// computing the closed orbit for a whole turn) (default value: 0°), \f$ \left[ p_{r} \right] = \si{m}\f$.
        /// Attention: It computes the starting index of the array. If it's not an integer it just cuts the floating point
        /// part, i.e. it takes the next starting index below. There's no interpolation of the momentum.
        /*!
         * @param angle is the start angle for the output. Has to be within [0°,360°[ (default: 0°).
109
         * @returns the momentum in \f$ \beta * \gamma \f$ units
110
         */
111
        container_type getMomentum(value_type angle = 0);
112 113 114 115

        /// Returns the average orbit radius
        value_type getAverageRadius();

adelmann's avatar
adelmann committed
116 117
        /// Returns the frequency error
        value_type getFrequencyError();
118 119 120 121 122 123 124 125

        /// Returns true if a closed orbit could be found
        bool isConverged();

        /// Computes the closed orbit
        /*!
         * @param accuracy specifies the accuracy of the closed orbit
         * @param maxit is the maximal number of iterations done for finding the closed orbit
frey_m's avatar
frey_m committed
126
         * @param ekin energy for which to find closed orbit (in tune mode: upper limit of range)
frey_m's avatar
frey_m committed
127
         * @param dE step increase [MeV]
128
         * @param rguess initial radius guess in [mm]
frey_m's avatar
frey_m committed
129
         * @param isTuneMode comptute tunes of all energies in one sweep
130
         */
131 132 133 134
        bool findOrbit(value_type accuracy, size_type maxit,
                       value_type ekin,
                       value_type dE = 1.0, value_type rguess = -1.0,
                       bool isTuneMode = false);
135

136
        /// Fills in the values of h_m, ds_m, fidx_m.
137
        void computeOrbitProperties(const value_type& E);
138

139
    private:
140 141 142 143 144 145 146 147
        /// This function is called by the function getTunes().
        /*! Transfer matrix Y = [y11, y12; y21, y22] (see Gordon paper for more details).
         * @param y are the positions (elements y11 and y12 of Y)
         * @param py2 is the momentum of the second solution (element y22 of Y)
         * @param ncross is the number of sign changes (\#crossings of zero-line)
         */
        value_type computeTune(const std::array<value_type,2>&, value_type, size_type);

frey_m's avatar
frey_m committed
148 149 150
        // Compute closed orbit for given energy
        bool findOrbitOfEnergy_m(const value_type&, container_type&, value_type&,
                                 const value_type&, size_type);
snuverink_j's avatar
snuverink_j committed
151

adelmann's avatar
adelmann committed
152
        /// This function computes nzcross_ which is used to compute the tune in z-direction and the frequency error
153
//         void computeVerticalOscillations();
snuverink_j's avatar
snuverink_j committed
154

155 156
        /// This function rotates the calculated closed orbit finder properties to the initial angle
        container_type rotate(value_type angle, container_type& orbitProperty);
157 158 159 160 161

        /// Stores current position in horizontal direction for the solutions of the ODE with different initial values
        std::array<value_type,2> x_m; // x_m = [x1, x2]
        /// Stores current momenta in horizontal direction for the solutions of the ODE with different initial values
        std::array<value_type,2> px_m; // px_m = [px1, px2]
frey_m's avatar
frey_m committed
162
        /// Stores current position in vertical direction for the solutions of the ODE with different initial values
163
        std::array<value_type,2> z_m; // z_m = [z1, z2]
frey_m's avatar
frey_m committed
164
        /// Stores current momenta in vertical direction for the solutions of the ODE with different initial values
165 166 167 168 169 170 171 172
        std::array<value_type,2> pz_m; // pz_m = [pz1, pz2]

        /// Stores the inverse bending radius
        container_type h_m;
        /// Stores the step length
        container_type ds_m;
        /// Stores the radial orbit (size: N_m+1)
        container_type r_m;
173 174
        /// Stores the vertical oribt (size: N_m+1)
        container_type vz_m;
175 176
        /// Stores the radial momentum
        container_type pr_m;
177 178
        /// Stores the vertical momentum
        container_type vpz_m;
179 180 181 182 183 184 185 186
        /// Stores the field index
        container_type fidx_m;

        /// Counts the number of zero-line crossings in horizontal direction (used for computing horizontal tune)
        size_type nxcross_m;
        /// Counts the number of zero-line crossings in vertical direction (used for computing vertical tune)
        size_type nzcross_m; //#crossings of zero-line in x- and z-direction

187
        /// Is the rest mass [MeV / c**2]
188
        value_type E0_m;
snuverink_j's avatar
snuverink_j committed
189

190
        /// Is the nominal orbital frequency
191 192 193
        /* (see paper of Dr. C. Baumgarten: "Transverse-Longitudinal
         * Coupling by Space Charge in Cyclotrons" (2012), formula (1))
         */
194
        value_type wo_m;
adelmann's avatar
adelmann committed
195
        /// Number of integration steps
196 197 198 199 200 201 202 203 204 205
        size_type N_m;
        /// Is the angle step size
        value_type dtheta_m;

        /// Is the average radius
        value_type ravg_m;

        /// Is the phase
        value_type phase_m;

206
        /**
207 208 209 210
         * Stores the last orbit value (since we have to return to the beginning to check the convergence in the
         * findOrbit() function. This last value is then deleted from the array but is stored in lastOrbitVal_m to
         * compute the vertical oscillations)
         */
snuverink_j's avatar
snuverink_j committed
211
        /* value_type lastOrbitVal_m; */
212

213 214 215 216 217
        /**
         * Stores the last momentum value (since we have to return to the beginning to check the convergence in the
         * findOrbit() function. This last value is then deleted from the array but is stored in lastMomentumVal_m to
         * compute the vertical oscillations)
         */
snuverink_j's avatar
snuverink_j committed
218
        /* value_type lastMomentumVal_m; */
219 220

        /**
221 222 223
         * Boolean which is true by default. "true": orbit integration over one sector only, "false": integration
         * over 2*pi
         */
adelmann's avatar
adelmann committed
224
        bool domain_m;
225 226 227 228 229
        /**
         * Number of sectors to average the field map over
         * in order to avoid first harmonic. Only valid if domain is false
         */
        int  nSectors_m;
230

231 232
        /// Defines the stepper for integration of the ODE's
        Stepper stepper_m;
snuverink_j's avatar
snuverink_j committed
233

234
        /*!
snuverink_j's avatar
snuverink_j committed
235
         * This quantity is defined in the paper "Transverse-Longitudinal Coupling by Space Charge in Cyclotrons"
236 237 238 239
         * of Dr. Christian Baumgarten (2012)
         * The lambda function takes the orbital frequency \f$ \omega_{o} \f$ (also defined in paper) as input argument.
         */
        std::function<double(double)> acon_m = [](double wo) { return Physics::c / wo; };
snuverink_j's avatar
snuverink_j committed
240

241 242 243 244 245 246 247
        /// Cyclotron unit \f$ \left[T\right] \f$ (Tesla)
        /*!
         * The lambda function takes the orbital frequency \f$ \omega_{o} \f$ as input argument.
         */
        std::function<double(double, double)> bcon_m = [](double e0, double wo) {
            return e0 * 1.0e7 / (/* physics::q0 */ 1.0 * Physics::c * Physics::c / wo);
        };
snuverink_j's avatar
snuverink_j committed
248

249
        Cyclotron* cycl_m;
250 251 252 253 254 255
};

// -----------------------------------------------------------------------------------------------------------------------
// PUBLIC MEMBER FUNCTIONS
// -----------------------------------------------------------------------------------------------------------------------

256 257 258
template<typename Value_type, typename Size_type, class Stepper>
ClosedOrbitFinder<Value_type,
                  Size_type,
frey_m's avatar
frey_m committed
259
                  Stepper>::ClosedOrbitFinder(value_type E0,
260
                                              size_type N, Cyclotron* cycl,
261
                                              bool domain, int nSectors)
262 263 264
    : nxcross_m(0)
    , nzcross_m(0)
    , E0_m(E0)
265
    , wo_m(cycl->getRfFrequ(0)*1E6/cycl->getCyclHarm()*2.0*Physics::pi)
266 267 268 269
    , N_m(N)
    , dtheta_m(Physics::two_pi/value_type(N))
    , ravg_m(0)
    , phase_m(0)
snuverink_j's avatar
snuverink_j committed
270 271
    /* , lastOrbitVal_m(0.0) */
    /* , lastMomentumVal_m(0.0) */
272
    , domain_m(domain)
273
    , nSectors_m(nSectors)
274
    , stepper_m()
275
    , cycl_m(cycl)
276
{
snuverink_j's avatar
snuverink_j committed
277

278
    if ( cycl_m->getFMLowE() > cycl_m->getFMHighE() )
frey_m's avatar
frey_m committed
279 280
        throw OpalException("ClosedOrbitFinder::ClosedOrbitFinder()",
                            "Incorrect cyclotron energy (MeV) bounds: Maximum cyclotron energy smaller than minimum cyclotron energy.");
snuverink_j's avatar
snuverink_j committed
281

adelmann's avatar
adelmann committed
282 283
    // if domain_m = true --> integrate over a single sector
    if (domain_m) {
284
        N_m /=  cycl_m->getSymmetry();
adelmann's avatar
adelmann committed
285
    }
snuverink_j's avatar
snuverink_j committed
286

frey_m's avatar
frey_m committed
287 288
    cycl_m->read(cycl_m->getFieldFlag(cycl_m->getCyclotronType()),
                 cycl_m->getBScale());
289

290 291 292 293 294
    // reserve storage for the orbit and momentum (--> size = 0, capacity = N_m+1)
    /*
     * we need N+1 storage, since dtheta = 2pi/N (and not 2pi/(N-1)) that's why we need N+1 integration steps
     * to return to the origin (but the return size is N_m)
     */
adelmann's avatar
adelmann committed
295 296
    r_m.reserve(N_m + 1);
    pr_m.reserve(N_m + 1);
297 298
    vz_m.reserve(N_m + 1);
    vpz_m.reserve(N_m + 1);
299

300
    // reserve memory of N_m for the properties (--> size = 0, capacity = N_m)
adelmann's avatar
adelmann committed
301 302 303
    h_m.reserve(N_m);
    ds_m.reserve(N_m);
    fidx_m.reserve(N_m);
304 305 306
}

template<typename Value_type, typename Size_type, class Stepper>
307
inline typename ClosedOrbitFinder<Value_type, Size_type, Stepper>::container_type
308
    ClosedOrbitFinder<Value_type, Size_type, Stepper>::getInverseBendingRadius(const value_type& angle)
309
{
310 311 312 313
    if (angle != 0.0)
        return rotate(angle, h_m);
    else
        return h_m;
314 315 316
}

template<typename Value_type, typename Size_type, class Stepper>
317
inline typename ClosedOrbitFinder<Value_type, Size_type, Stepper>::container_type
318
    ClosedOrbitFinder<Value_type, Size_type, Stepper>::getPathLength(const value_type& angle)
319
{
320 321 322 323
    if (angle != 0.0)
        return rotate(angle, ds_m);
    else
        return ds_m;
324 325 326
}

template<typename Value_type, typename Size_type, class Stepper>
327
inline typename ClosedOrbitFinder<Value_type, Size_type, Stepper>::container_type
328
    ClosedOrbitFinder<Value_type, Size_type, Stepper>::getFieldIndex(const value_type& angle)
329
{
330 331
    if (angle != 0.0)
        return rotate(angle, fidx_m);
frey_m's avatar
frey_m committed
332
    return fidx_m;
333 334 335
}

template<typename Value_type, typename Size_type, class Stepper>
336 337 338
std::pair<Value_type,Value_type> ClosedOrbitFinder<Value_type, Size_type, Stepper>::getTunes() {
    // compute radial tune
    value_type nur = computeTune(x_m,px_m[1],nxcross_m);
339

340 341 342 343
    // compute vertical tune
    value_type nuz = computeTune(z_m,pz_m[1],nzcross_m);

    return std::make_pair(nur,nuz);
344 345 346
}

template<typename Value_type, typename Size_type, class Stepper>
347
inline typename ClosedOrbitFinder<Value_type, Size_type, Stepper>::container_type
348
    ClosedOrbitFinder<Value_type, Size_type, Stepper>::getOrbit(value_type angle)
349
{
350 351 352 353
    if (angle != 0.0)
        return rotate(angle, r_m);
    else
        return r_m;
354 355 356 357
}

template<typename Value_type, typename Size_type, class Stepper>
inline typename ClosedOrbitFinder<Value_type, Size_type, Stepper>::container_type
358
    ClosedOrbitFinder<Value_type, Size_type, Stepper>::getMomentum(value_type angle)
359 360
{
    container_type pr = pr_m;
snuverink_j's avatar
snuverink_j committed
361

362 363
    if (angle != 0.0)
        pr = rotate(angle, pr);
snuverink_j's avatar
snuverink_j committed
364

365 366
    // change units from meters to \beta * \gamma
    /* in Gordon paper:
snuverink_j's avatar
snuverink_j committed
367
     *
368
     * p = \gamma * \beta * a
snuverink_j's avatar
snuverink_j committed
369
     *
370
     * where a = c / \omega_{0} with \omega_{0} = 2 * \pi * \nu_{0} = 2 * \pi * \nu_{rf} / h
snuverink_j's avatar
snuverink_j committed
371
     *
372 373 374
     * c: speed of light
     * h: harmonic number
     * v_{rf}: nomial rf frequency
snuverink_j's avatar
snuverink_j committed
375
     *
376
     * Units:
snuverink_j's avatar
snuverink_j committed
377
     *
378
     * [a] = m --> [p] = m
snuverink_j's avatar
snuverink_j committed
379
     *
380
     * The momentum in \beta * \gamma is obtained by dividing by "a"
381
     */
382
    value_type factor =  1.0 / acon_m(wo_m);
383
    std::for_each(pr.begin(), pr.end(), [factor](value_type& p) { p *= factor; });
snuverink_j's avatar
snuverink_j committed
384

385
    return pr;
386 387 388
}

template<typename Value_type, typename Size_type, class Stepper>
389 390 391
inline typename ClosedOrbitFinder<Value_type, Size_type, Stepper>::value_type
    ClosedOrbitFinder<Value_type, Size_type, Stepper>::getAverageRadius()
{
392
    return ravg_m;
393 394 395
}

template<typename Value_type, typename Size_type, class Stepper>
396 397
typename ClosedOrbitFinder<Value_type, Size_type, Stepper>::value_type
    ClosedOrbitFinder<Value_type, Size_type, Stepper>::getFrequencyError()
398
{
399
    return phase_m;
400 401 402 403 404 405
}

// -----------------------------------------------------------------------------------------------------------------------
// PRIVATE MEMBER FUNCTIONS
// -----------------------------------------------------------------------------------------------------------------------

frey_m's avatar
frey_m committed
406 407


408
template<typename Value_type, typename Size_type, class Stepper>
409 410
bool ClosedOrbitFinder<Value_type, Size_type, Stepper>::findOrbit(value_type accuracy,
                                                                  size_type maxit,
frey_m's avatar
frey_m committed
411
                                                                  value_type ekin,
frey_m's avatar
frey_m committed
412
                                                                  value_type dE,
frey_m's avatar
frey_m committed
413 414
                                                                  value_type rguess,
                                                                  bool isTuneMode)
415
{
416 417 418 419
    /* REMARK TO GORDON
     * q' = 1/b = 1/bcon
     * a' = a = acon
     */
420

421 422 423
    // resize vectors (--> size = N_m+1, capacity = N_m+1), note: we do N_m+1 integration steps
    r_m.resize(N_m+1);
    pr_m.resize(N_m+1);
424 425
    vz_m.resize(N_m+1);
    vpz_m.resize(N_m+1);
426

427 428
    // store acon locally
    value_type acon = acon_m(wo_m);            // [acon] = m
429 430
    // amplitude of error; Gordon, formula (18) (a = a')
    value_type error = std::numeric_limits<value_type>::max();
431 432 433 434

    /*
     * Christian:
     * N = 1440 ---> N = 720 ---> dtheta = 2PI/720 --> nsteps = 721
435
     *
436
     * 0, 2, 4, ... ---> jeden zweiten berechnene: 1, 3, 5, ... interpolieren --> 1440 Werte
437
     *
438 439
     * Matthias:
     * N = 1440 --> dtheta = 2PI/1440 --> nsteps = 1441
440
     *
441
     * 0, 1, 2, 3, 4, 5, ... --> 1440 Werte
442
     *
443
     */
444

445 446 447
    value_type E;     // starting energy
    value_type E_fin; // final    energy

frey_m's avatar
frey_m committed
448
    if ( isTuneMode ) {
449 450 451 452 453
        E     = cycl_m->getFMLowE();
        E_fin = cycl_m->getFMHighE();
    } else {
        E     = ekin;
        E_fin = ekin;
frey_m's avatar
frey_m committed
454
    }
Andreas Adelmann's avatar
Andreas Adelmann committed
455

frey_m's avatar
frey_m committed
456 457 458 459
    namespace fs = boost::filesystem;
    fs::path dir = OpalData::getInstance()->getInputBasename();
    dir = dir.parent_path() / "data";
    std::string tunefile = (dir / "tunes.dat").string();
460

frey_m's avatar
frey_m committed
461 462
    if ( isTuneMode ) {
        std::ofstream out(tunefile, std::ios::out);
463

frey_m's avatar
frey_m committed
464
        out << std::left
465
            << std::setw(15) << "# energy[MeV]"
466 467
            << std::setw(15) << "radius_ini[m]"
            << std::setw(15) << "radius_avg[m]"
frey_m's avatar
frey_m committed
468 469 470 471
            << std::setw(15) << "nu_r"
            << std::setw(15) << "nu_z"
            << std::endl;
    }
472 473 474 475
    // initial guess
    container_type init;
    enum Guess {NONE, FIRST, SECOND};
    Guess guess = NONE;
476 477
    value_type rn1, pn1; // normalised r, pr value of previous closed orbit
    value_type rn2, pn2; // normalised r, pr value of second to previous closed orbit
478

479 480 481
    // iterate until suggested energy (start with minimum energy)
    // increase energy by dE
    for (; E <= E_fin ; E+=dE) {
frey_m's avatar
frey_m committed
482
        error = std::numeric_limits<value_type>::max();
483 484 485 486 487 488

        // energy dependent values
        value_type en     = E / E0_m;        // en = E/E0 = E/(mc^2) (E0 is potential energy)
        value_type gamma  = en + 1.0;
        value_type gamma2 = gamma * gamma;   // = gamma^2
        value_type beta   = std::sqrt(1.0 - 1.0 / gamma2);
489
        value_type p = acon_m(wo_m) * std::sqrt(en * (2.0 + en));  // momentum [p] = m; Gordon, formula (3)
490 491 492 493 494 495 496 497 498 499 500 501 502 503

        if (guess == NONE) {
            // set initial values for radius and radial momentum for lowest energy Emin
            // orbit, [r] = m;  Gordon, formula (20)
            // radial momentum; Gordon, formula (20)
            //      r            pr   z    pz
            init = {beta * acon, 0.0, 0.0, 1.0};
            if (rguess >= 0.0) {
                init[0] = rguess * 0.001;
            }
            guess = FIRST;
        } else if (guess == FIRST) {
            // new initial values based on previous one, formula (21)
            init[0] = (beta*acon) * rn1;
504
            init[1] = p*pn1;
505 506 507 508
            guess = SECOND;
        } else if (guess == SECOND) {
            // second extrapolation, formula (21)
            init[0] = (beta*acon) * (rn1 + (rn1-rn2));
509
            init[1] = p*(pn1 + (pn1-pn2));
510 511 512 513 514 515 516
        }

        std::fill(  r_m.begin(),   r_m.end(), 0);
        std::fill( pr_m.begin(),  pr_m.end(), 0);
        std::fill( vz_m.begin(),  vz_m.end(), 0);
        std::fill(vpz_m.begin(), vpz_m.end(), 0);

517
        // (re-)set inital values for r and pr
518 519 520
        r_m[0]   = init[0];
        pr_m[0]  = init[1];
        vz_m[0]  = init[2];
521
        vpz_m[0] = init[3];
522

frey_m's avatar
frey_m committed
523
        if ( !this->findOrbitOfEnergy_m(E, init, error, accuracy, maxit) ) {
524
            *gmsg << "ClosedOrbitFinder didn't converge for energy " + std::to_string(E) + " MeV." << endl;
525
            guess = NONE;
526
            continue;
frey_m's avatar
frey_m committed
527
        }
528 529
        // store for next initial guess
        rn2 = rn1;
530 531 532
        pn2 = pn1;
        rn1 = r_m[0] / (acon * beta);
        pn1 = pr_m[0] / p;
533

frey_m's avatar
frey_m committed
534
        if ( isTuneMode ) {
535

536 537 538
            this->computeOrbitProperties(E);
            value_type reo = this->getOrbit(   cycl_m->getPHIinit())[0];
            value_type peo = this->getMomentum(cycl_m->getPHIinit())[0];
frey_m's avatar
frey_m committed
539 540
            std::pair<value_type , value_type > tunes = this->getTunes();

541 542
            *gmsg << std::left
                  << "* ----------------------------" << endl
frey_m's avatar
frey_m committed
543 544
                  << "* Closed orbit info (Gordon units):" << endl
                  << "*" << endl
545 546 547 548
                  << "* kinetic energy:   " << std::setw(12) << E      << " [MeV]" << endl
                  << "* average radius:   " << std::setw(12) << ravg_m << " [m]" << endl
                  << "* initial radius:   " << std::setw(12) << reo    << " [m]" << endl
                  << "* initial momentum: " << std::setw(12) << peo    << " [Beta Gamma]" << endl
frey_m's avatar
frey_m committed
549 550 551 552
                  << "* frequency error:  " << phase_m        << endl
                  << "* horizontal tune:  " << tunes.first    << endl
                  << "* vertical tune:    " << tunes.second   << endl
                  << "* ----------------------------" << endl << endl;
553

frey_m's avatar
frey_m committed
554 555 556 557
            std::ofstream out(tunefile, std::ios::app);
            out << std::left
                << std::setw(15) << E
                << std::setw(15) << reo
558
                << std::setw(15) << ravg_m
frey_m's avatar
frey_m committed
559 560 561 562
                << std::setw(15) << tunes.first
                << std::setw(15) << tunes.second << std::endl;
            out.close();
        }
563
    }
564

565 566 567
    /* store last entry, since it is needed in computeVerticalOscillations(), because we have to do the same
     * number of integrations steps there.
     */
snuverink_j's avatar
snuverink_j committed
568 569
    /* lastOrbitVal_m    = r_m[N_m];        // needed in computeVerticalOscillations() */
    /* lastMomentumVal_m = pr_m[N_m];       // needed in computeVerticalOscillations() */
570

571 572 573
    // remove last entry (since we don't have to store [0,2pi], but [0,2pi[)  --> size = N_m, capacity = N_m+1
    r_m.pop_back();
    pr_m.pop_back();
574

575 576 577 578 579
    /* domain_m = true --> only integrated over a single sector
     * --> multiply by cycl_m->getSymmetry() to get correct phase_m
     */
    if (domain_m)
        phase_m *= cycl_m->getSymmetry();
580

581 582 583
    // returns true if converged, otherwise false
    return error < accuracy;
}
584

frey_m's avatar
frey_m committed
585 586 587 588 589 590 591 592
template<typename Value_type, typename Size_type, class Stepper>
bool ClosedOrbitFinder<Value_type, Size_type, Stepper>::findOrbitOfEnergy_m(
    const value_type& E,
    container_type& init,
    value_type& error,
    const value_type& accuracy,
    size_type maxit)
{
593 594 595
    /* *gmsg << "rguess : " << init[0] << endl; */
    /* *gmsg << "prguess: " << init[1] << endl; */

frey_m's avatar
frey_m committed
596 597
    value_type bint, brint, btint;
    value_type invbcon = 1.0 / bcon_m(E0_m, wo_m);      // [bcon] = MeV*s/(C*m^2) = 10^6 T = 10^7 kG (kilo Gauss)
snuverink_j's avatar
snuverink_j committed
598

frey_m's avatar
frey_m committed
599 600 601 602 603 604
    value_type xold = 0.0;                              // for counting nxcross
    value_type zold = 0.0;                              // for counting nzcross

    // index for reaching next element of the arrays r and pr (no nicer way found yet)
    size_type idx = 0;
    // observer for storing the current value after each ODE step (e.g. Runge-Kutta step) into the containers of r and pr
605
    auto store = [&](state_type& y, const value_type /*t*/)
frey_m's avatar
frey_m committed
606
    {
607 608 609
        r_m[idx]   = y[0];
        pr_m[idx]  = y[1];
        vz_m[idx]  = y[6];
frey_m's avatar
frey_m committed
610 611 612 613 614
        vpz_m[idx] = y[7];

        // count number of crossings (excluding starting point --> idx>0)
        nxcross_m += (idx > 0) * (y[4] * xold < 0);
        xold = y[4];
snuverink_j's avatar
snuverink_j committed
615

frey_m's avatar
frey_m committed
616 617 618
        // number of times z2 changes sign
        nzcross_m += (idx > 0) * (y[10] * zold < 0);
        zold = y[10];
snuverink_j's avatar
snuverink_j committed
619

frey_m's avatar
frey_m committed
620 621
        ++idx;
    };
snuverink_j's avatar
snuverink_j committed
622

frey_m's avatar
frey_m committed
623 624 625 626
    // define initial state container for integration: y = {r, pr, x1, px1, x2, px2,
    //                                                      z, pz, z1, pz1, z2, pz2,
    //                                                      phase}
    state_type y(11);
snuverink_j's avatar
snuverink_j committed
627

frey_m's avatar
frey_m committed
628 629 630 631 632 633
    // difference of last and first value of r (1. element) and pr (2. element)
    container_type err(2);
    // correction term for initial values: r = r + dr, pr = pr + dpr; Gordon, formula (17)
    container_type delta = {0.0, 0.0};
    // if niterations > maxit --> stop iteration
    size_type niterations = 0;
snuverink_j's avatar
snuverink_j committed
634

frey_m's avatar
frey_m committed
635
    // energy dependent values
636 637
    value_type en     = E / E0_m;                      // en = E/E0 = E/(mc^2) (E0 is potential energy)
    value_type gamma  = en + 1.0;
frey_m's avatar
frey_m committed
638
    value_type p = acon_m(wo_m) * std::sqrt(en * (2.0 + en));     // momentum [p] = m; Gordon, formula (3)
639 640
    value_type gamma2    = gamma * gamma;           // = gamma^2
    value_type invgamma4 = 1.0 / (gamma2 * gamma2); // = 1/gamma^4
641 642
    value_type p2 = p * p;                              // p^2 = p*p

frey_m's avatar
frey_m committed
643 644
    // helper constants
    value_type pr2;                                     // squared radial momentum (pr^2 = pr*pr)
645
    value_type ptheta, invptheta;                       // azimuthal momentum
frey_m's avatar
frey_m committed
646 647 648 649 650 651 652

    // define the six ODEs (using lambda function)
    function_t orbit_integration = [&](const state_type &y,
                                       state_type &dydt,
                                       const double theta)
    {
        pr2 = y[1] * y[1];
653 654
        if (p2 < pr2) {
            //*gmsg << theta << " " << p2 << " " << pr2 << endl;
655
            throw OpalException("ClosedOrbitFinder::findOrbitOfEnergy_m()",
frey_m's avatar
frey_m committed
656
                                "p_{r}^2 > p^{2} (defined in Gordon paper) --> Square root of negative number.");
657
        }
frey_m's avatar
frey_m committed
658
        // Gordon, formula (5c)
659
        ptheta    = std::sqrt(p2 - pr2);
frey_m's avatar
frey_m committed
660
        invptheta = 1.0 / ptheta;
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
        // average field over the number of sectors
        brint=0.0, btint=0.0, bint=0.0;
        for (int i = 0; i<nSectors_m; i++) {
            double angle = theta + i * Physics::two_pi / nSectors_m;
            double tmpbr, tmpbt, tmpb;
            // interpolate values of magnetic field
            cycl_m->apply(y[0], y[6], angle, tmpbr, tmpbt, tmpb);
            brint += tmpbr;
            btint += tmpbt;
            bint  += tmpb;
        }
        brint /= nSectors_m;
        btint /= nSectors_m;
        bint  /= nSectors_m;
        // multiply by 1 / b
snuverink_j's avatar
snuverink_j committed
676
        bint  *= invbcon;
frey_m's avatar
frey_m committed
677 678 679 680 681
        brint *= invbcon;
        btint *= invbcon;

        // Gordon, formula (5a)
        dydt[0] = y[0] * y[1] * invptheta;
682
        // Gordon, formula (5b) (typo in paper! second equal sign is a minus)
frey_m's avatar
frey_m committed
683 684 685
        dydt[1] = ptheta - y[0] * bint;
        // Gordon, formulas (9a) and (9b)
        for (size_type i = 2; i < 5; i += 2) {
686
            dydt[i]   = (y[1] * y[i] + y[0] * p2 * y[i+1] * invptheta * invptheta) * invptheta;
frey_m's avatar
frey_m committed
687 688
            dydt[i+1] = - y[1] * y[i+1] * invptheta - (bint + y[0] * brint) * y[i];
        }
689

frey_m's avatar
frey_m committed
690 691
        // Gordon, formulas (22a) and (22b)
        for (size_type i = 6; i < 12; i += 2) {
692
            dydt[i]   = y[0] * y[i+1] * invptheta;
frey_m's avatar
frey_m committed
693 694 695 696
            dydt[i+1] = (y[0] * brint - y[1] * invptheta * btint) * y[i];
        }

        // integrate phase
697
        dydt[12] = y[0] * invptheta * gamma - 1;
698

frey_m's avatar
frey_m committed
699 700
    };

701
    // integrate until error smaller than user-defined accuracy
frey_m's avatar
frey_m committed
702
    do {
703
        // (re-)set initial values
704
        x_m[0]  = 1.0;               // x1;  Gordon, formula (10)
frey_m's avatar
frey_m committed
705
        px_m[0] = 0.0;               // px1; Gordon, formula (10)
706
        x_m[1]  = 0.0;               // x2;  Gordon, formula (10)
frey_m's avatar
frey_m committed
707 708 709 710 711 712 713 714 715
        px_m[1] = 1.0;               // px2; Gordon, formula (10)
        z_m[0]  = 1.0;
        pz_m[0] = 0.0;
        z_m[1]  = 0.0;
        pz_m[1] = 1.0;
        phase_m = 0.0;
        nxcross_m = 0;               // counts the number of crossings of x-axis (excluding first step)
        nzcross_m = 0;
        idx = 0;                     // index for looping over r and pr arrays
716

frey_m's avatar
frey_m committed
717 718 719 720 721 722 723 724
        // fill container with initial states
        y = {init[0],init[1],
             x_m[0], px_m[0], x_m[1], px_m[1],
             init[2], init[3],
             z_m[0], pz_m[0], z_m[1], pz_m[1],
             phase_m
        };

725
        try {
726
            // integrate from 0 to 2*pi / nSectors (one has to get back to the "origin")
727
            boost::numeric::odeint::integrate_n_steps(stepper_m, orbit_integration,y,0.0,dtheta_m,N_m,store);
728 729
        } catch(OpalException & ex) {
            *gmsg << ex.where() << " " << ex.what() << endl;
730 731 732
            break;
        }

frey_m's avatar
frey_m committed
733
        // write new state
734
        x_m[0]  = y[2];
frey_m's avatar
frey_m committed
735
        px_m[0] = y[3];
736
        x_m[1]  = y[4];
frey_m's avatar
frey_m committed
737
        px_m[1] = y[5];
738 739

        z_m[0]  = y[8];
frey_m's avatar
frey_m committed
740
        pz_m[0] = y[9];
741
        z_m[1]  = y[10];
frey_m's avatar
frey_m committed
742 743
        pz_m[1] = y[11];
        phase_m = y[12] * Physics::u_two_pi; // / (2.0 * Physics::pi);
744

frey_m's avatar
frey_m committed
745 746
        // compute error (compare values of orbit and momentum for theta = 0 and theta = 2*pi)
        // (Note: size = N_m+1 --> last entry is N_m)
747
        err[0] =  r_m[N_m] -  r_m[0];    // Gordon, formula (14)
frey_m's avatar
frey_m committed
748 749
        err[1] = pr_m[N_m] - pr_m[0];    // Gordon, formula (14)

750
        // correct initial values of r and pr
frey_m's avatar
frey_m committed
751
        value_type invdenom = 1.0 / (x_m[0] + px_m[1] - 2.0);
752 753
        delta[0] = ((px_m[1] - 1.0) * err[0] -  x_m[1] * err[1]) * invdenom; // dr;  Gordon, formula (16a)
        delta[1] = (( x_m[0] - 1.0) * err[1] - px_m[0] * err[0]) * invdenom; // dpr; Gordon, formula (16b)
frey_m's avatar
frey_m committed
754 755 756 757

        // improved initial values; Gordon, formula (17) (here it's used for higher energies)
        init[0] += delta[0];
        init[1] += delta[1];
758 759

        // compute amplitude of the error (Gordon, formula (18)
frey_m's avatar
frey_m committed
760
        error = std::sqrt(delta[0] * delta[0] + delta[1] * delta[1] * invgamma4) / r_m[0];
761 762 763 764 765

        // *gmsg << "iteration " << niterations << " error: " << error << endl;

    } while ((error > accuracy) && (niterations++ < maxit));

766
    if (error > accuracy)
767
        *gmsg << "findOrbit not converged after " << niterations << " iterations with error: " << error << ". Needed accuracy " << accuracy << endl;
768

frey_m's avatar
frey_m committed
769 770 771
    return (error < accuracy);
}

772
template<typename Value_type, typename Size_type, class Stepper>
773 774 775
Value_type ClosedOrbitFinder<Value_type, Size_type, Stepper>::computeTune(const std::array<value_type,2>& y,
                                                                          value_type py2, size_type ncross)
{
776
    // Y = [y1, y2; py1, py2]
777

778 779
    // cos(mu)
    value_type cos = 0.5 * (y[0] + py2);
snuverink_j's avatar
snuverink_j committed
780

781
    value_type mu;
782

783 784
    // sign of sin(mu) has to be equal to y2
    bool negative = std::signbit(y[1]);
785

786
    bool uneven = (ncross % 2);
787

788 789 790
    value_type abscos = std::fabs(cos);
    value_type muPrime;
    if (abscos > 1.0) {
791 792
        // store the number of crossings
        if (uneven)
793
            ncross = ncross + 1;
794

795
        // Gordon, formula (36b)
796
        muPrime = -std::acosh(abscos);    // mu'
797

798
    } else {
799
        muPrime = (uneven) ? std::acos(-cos) : std::acos(cos);    // mu'
800
        /* It has to be fulfilled: 0<= mu' <= pi
801 802 803 804 805
         * But since |cos(mu)| <= 1, we have
         * -1 <= cos(mu) <= 1 --> 0 <= mu <= pi (using above programmed line), such
         * that condition is already fulfilled.
         */
    }
806

807 808
    // Gordon, formula (36)
    mu = ncross * Physics::pi + muPrime;
809

810
    if (abscos < 1.0) {
811 812
        // if sign(y[1]) > 0 && sign(sin(mu)) < 0
        if (!negative && std::signbit(std::sin(mu))) {
813
            mu = ncross * Physics::pi - muPrime;
814
        } else if (negative && !std::signbit(std::sin(mu))) {
815
            mu = ncross * Physics::pi - muPrime + Physics::two_pi;
816 817
        }
    }
818

819
    // nu = mu/theta, where theta = integration domain
820

821
    /* domain_m = true --> only integrated over a single sector --> multiply by cycl_m->getSymmetry() to
adelmann's avatar
adelmann committed
822 823 824
     * get correct tune.
     */
    if (domain_m)
825
        mu *= cycl_m->getSymmetry();
826

827
    return mu * Physics::u_two_pi;
828 829 830
}

template<typename Value_type, typename Size_type, class Stepper>
831
void ClosedOrbitFinder<Value_type, Size_type, Stepper>::computeOrbitProperties(const value_type& E) {
832
    /*
833 834 835 836 837
     * The formulas for h, fidx and ds are from the paper:
     * "Tranverse-Longitudinal Coupling by Space Charge in Cyclotrons"
     * written by Dr. Christian Baumgarten (2012, PSI)
     * p. 6
     */
838

adelmann's avatar
adelmann committed
839
    // READ IN MAGNETIC FIELD: ONLY FOR STAND-ALONE PROGRAM
840
    value_type bint, brint, btint; // B, dB/dr, dB/dtheta
841

842
    value_type invbcon = 1.0 / bcon_m(E0_m, wo_m);
843
    value_type en = E / E0_m;                                  // en = E/E0 = E/(mc^2) (E0 is potential energy)
844
    value_type p = acon_m(wo_m) * std::sqrt(en * (2.0 + en));  // momentum [p] = m; Gordon, formula (3)
845
    value_type p2 = p * p;
846
    value_type theta = 0.0;                                    // angle for interpolating
847
    value_type ptheta;
848

849 850 851 852 853 854 855
    // resize of container (--> size = N_m, capacity = N_m)
    h_m.resize(N_m);
    fidx_m.resize(N_m);
    ds_m.resize(N_m);

    for (size_type i = 0; i < N_m; ++i) {
        // interpolate magnetic field
856
        cycl_m->apply(r_m[i], vz_m[i], theta, brint, btint, bint);
snuverink_j's avatar
snuverink_j committed
857
        bint  *= invbcon;
858 859
        brint *= invbcon;
        btint *= invbcon;
snuverink_j's avatar
snuverink_j committed
860

861 862 863 864
        // inverse bending radius
        h_m[i] = bint / p;

        // local field index
865
        if (p < pr_m[i])
snuverink_j's avatar
snuverink_j committed
866
            throw OpalException("ClosedOrbitFinder::computeOrbitProperties()",
867 868
                                "p_{r}^2 > p^{2} " + std::to_string(p) + " " + std::to_string(pr_m[i]) + " (defined in Gordon paper) --> Square root of negative number.");

869
        ptheta = std::sqrt(p2 - pr_m[i] * pr_m[i]);
870

871 872 873 874 875 876 877
        fidx_m[i] = (brint * ptheta - btint * pr_m[i] / r_m[i]) / p2; //(bint*bint);

        // path length element
        ds_m[i] = std::hypot(r_m[i] * pr_m[i] / ptheta,r_m[i]) * dtheta_m; // C++11 function

        // increase angle
        theta += dtheta_m;
878
    }
879 880 881

    // compute average radius
    ravg_m = std::accumulate(r_m.begin(),r_m.end(),0.0) / value_type(r_m.size());
882 883
}

snuverink_j's avatar
snuverink_j committed
884
template<typename Value_type, typename Size_type, class Stepper>
885 886 887 888
inline typename ClosedOrbitFinder<Value_type, Size_type, Stepper>::container_type
ClosedOrbitFinder<Value_type, Size_type, Stepper>::rotate(value_type angle, container_type &orbitProperty) {

    container_type orbitPropertyCopy = orbitProperty;
snuverink_j's avatar
snuverink_j committed
889

890 891 892 893 894 895 896 897
    // compute the number of steps per degree
    value_type deg_step = N_m / 360.0;

    // compute starting point
    size_type start = deg_step * angle;

    // copy end to start
    std::copy(orbitProperty.begin() + start, orbitProperty.end(), orbitPropertyCopy.begin());
snuverink_j's avatar
snuverink_j committed
898

899 900 901 902 903 904 905
    // copy start to end
    std::copy_n(orbitProperty.begin(), start, orbitPropertyCopy.end() - start);

    return orbitPropertyCopy;

}

Andreas Adelmann's avatar
Andreas Adelmann committed
906
#endif