diff --git a/docs/source/_ext/pygments_mad_lexer.py b/docs/source/_ext/pygments_mad_lexer.py new file mode 100644 index 000000000..0e96615e5 --- /dev/null +++ b/docs/source/_ext/pygments_mad_lexer.py @@ -0,0 +1,30 @@ +# -- Custom Lexer ------------------------------------------------------------ +from pygments.lexers.scripting import LuaLexer +from pygments.token import Comment, Operator + + +class MadLexer(LuaLexer): + """ + Exactly the same as the Lua Lexer, except for the following changes: + New name, aliases, filenames and url (also removed mimetypes) + The comment can also be ! + The character "\\" is now an accepted operator. + """ + + name = 'MAD' + url = "https://mad.web.cern.ch/mad/" + aliases = ['mad'] + filenames = ['*.mad'] + mimetypes = [] + + tokens = { + **LuaLexer.tokens, + 'ws': [ + (r'(?:!.*$)', Comment.Single), + *LuaLexer.tokens["ws"], + ], + 'base': [ + (r'\\', Operator), + *LuaLexer.tokens["base"], + ], + } \ No newline at end of file diff --git a/docs/source/alignments.rst b/docs/source/alignments.rst new file mode 100644 index 000000000..7e25acc00 --- /dev/null +++ b/docs/source/alignments.rst @@ -0,0 +1,5 @@ +.. _ch.phy.align: + +Misalignments +============= + diff --git a/docs/source/aperture.rst b/docs/source/aperture.rst new file mode 100644 index 000000000..47730154a --- /dev/null +++ b/docs/source/aperture.rst @@ -0,0 +1,4 @@ +.. _ch.phy.aper: + +Aperture +======== diff --git a/docs/source/beam.rst b/docs/source/beam.rst new file mode 100644 index 000000000..04cc87dab --- /dev/null +++ b/docs/source/beam.rst @@ -0,0 +1,231 @@ +Beams +===== +.. _ch.gen.beam: + +The ``beam`` object is the *root object* of beams that store information relative to particles and particle beams. It also provides a simple interface to the particles and nuclei database. + +The ``beam`` module extends the :doc:`typeid ` module with the ``is_beam`` *function*, which returns ``true`` if its argument is a ``beam`` object, ``false`` otherwise. + +Attributes +---------- + +The ``beam`` *object* provides the following attributes: + +**particle** + A *string* specifying the name of the particle. (default: ``"positron"``). + +**mass** + A *number* specifying the energy-mass of the particle [GeV]. (default: ``emass``). + +**charge** + A *number* specifying the charge of the particle in [q] unit of ``qelect``. [#f1]_ (default: ``1``). + +**spin** + A *number* specifying the spin of the particle. (default: ``0``). + +**emrad** + A *lambda* returning the electromagnetic radius of the particle [m], + + :math:`\mathrm{emrad} = \mathrm{krad\_GeV}\times\mathrm{charge}^2/\mathrm{mass}` where :math:`\mathrm{krad\_GeV} = 10^{-9} (4 \pi\varepsilon_0)^{-1} q`. + +**aphot** + A *lambda* returning the average number of photon emitted per bending unit, + + :math:`\mathrm{aphot} = \mathrm{kpht\_GeV}\times\mathrm{charge}^2*\mathrm{betgam}` where :math:`\mathrm{kpht\_GeV}` :math:`= \frac{5}{2\sqrt{3}}`. + +**energy** + A *number* specifying the particle energy [GeV]. (default: ``1``). + +**pc** + A *lambda* returning the particle momentum times the speed of light [GeV], + + :math:`\mathrm{pc} = (\mathrm{energy}^2 - \mathrm{mass}^2)^{\frac{1}{2}}`. + +**beta** + A *lambda* returning the particle relativistic :math:`\beta=\frac{v}{c}`, + + :math:`\mathrm{beta} = (1 - (\mathrm{mass}/\mathrm{energy})^2)^{\frac{1}{2}}`. + +**gamma** + A *lambda* returning the particle Lorentz factor :math:`\gamma=(1-\beta^2)^{-\frac{1}{2}}`, + + :math:`\mathrm{gamma} = \mathrm{energy}/\mathrm{mass}`. + +**betgam** + A *lambda* returning the product :math:`\beta\gamma`, + + :math:`\mathrm{betgam} = (\mathrm{gamma}^2 - 1)^\frac{1}{2}`. + +**pc2** + A *lambda* returning :math:`\mathrm{pc}^2`, avoiding the square root. + +**beta2** + A *lambda* returning :math:`\mathrm{beta}^2`, avoiding the square root. + +**betgam2** + A *lambda* returning :math:`\mathrm{betgam}^2`, avoiding the square root. + +**brho** + A *lambda* returning the magnetic rigidity [T.m], + + :literal:`brho = GeV_c * pc/|charge|` where ``GeV_c`` = :math:`10^{9}/c` + +**ex** + A *number* specifying the horizontal emittance :math:`\epsilon_x` [m]. (default: ``1``). + +**ey** + A *number* specifying the vertical emittance :math:`\epsilon_y` [m]. (default: ``1``). + +**et** + A *number* specifying the longitudinal emittance :math:`\epsilon_t` [m]. (default: :literal:`1e-3`). + +**exn** + A *lambda* returning the normalized horizontal emittance [m], + + :literal:`exn = ex * betgam`. + +**eyn** + A *lambda* returning the normalized vertical emittance [m], + + :literal:`eyn = ey * betgam`. + +**etn** + A *lambda* returning the normalized longitudinal emittance [m], + + :literal:`etn = et * betgam`. + +**nbunch** + A *number* specifying the number of particle bunches in the machine. (default: ``0``). + +**npart** + A *number* specifying the number of particles per bunch. (default: ``0``). + +**sigt** + A *number* specifying the bunch length in :math:`c \sigma_t`. (default: ``1``). + +**sige** + A *number* specifying the relative energy spread in :math:`\sigma_E/E` [GeV]. (default: :literal:`1e-3`). + + +The ``beam`` *object* also implements a special protect-and-update mechanism for its attributes to ensure consistency and precedence between the physical quantities stored internally: + +#. The following attributes are *read-only*, i.e. writing to them triggers an error: + ``mass, charge, spin, emrad, aphot`` + +#. The following attributes are *read-write*, i.e. hold values, with their accepted numerical ranges: + ``particle, energy`` :math:`>` ``mass``, + ``ex`` :math:`>0`, ``ey`` :math:`>0`, ``et`` :math:`>0`, + ``nbunch`` :math:`>0`, ``npart`` :math:`>0`, ``sigt`` :math:`>0`, ``sige`` :math:`>0`. + +#. The following attributes are *read-update*, i.e. setting these attributes update the ``energy``, with their accepted numerical ranges: + ``pc`` :math:`>0`, :math:`0.9>` ``beta`` :math:`>0`, ``gamma`` :math:`>1`, ``betgam`` :math:`>0.1`, ``brho`` :math:`>0`, + ``pc2``, ``beta2``, ``betgam2``. +#. The following attributes are *read-update*, i.e. setting these attributes update the emittances ``ex``, ``ey``, and ``et`` repectively, with their accepted numerical ranges: + ``exn`` :math:`>0`, ``eyn`` :math:`>0`, ``etn`` :math:`>0`. + + +Methods +------- + +The ``beam`` object provides the following methods: + +**new_particle** + A *method* ``(particle, mass, charge, [spin])`` creating new particles or nuclei and store them in the particles database. The arguments specify in order the new ``particle``'s name, energy-``mass`` [GeV], ``charge`` [q], and ``spin`` (default: ``0``). These arguments can also be grouped into a *table* with same attribute names as the argument names and passed as the solely argument. + +**set_variables** + A *method* ``(set)`` returning ``self`` with the attributes set to the pairs (*key*, *value*) contained in ``set``. This method overrides the original one to implement the special protect-and-update mechanism, but the order of the updates is undefined. It also creates new particle on-the-fly if the ``mass`` and the ``charge`` are defined, and then select it. Shortcut ``setvar``. + +**showdb** + A *method* ``([file])`` displaying the content of the particles database to ``file`` (default: ``io.stdout``). + + +Metamethods +----------- + +The ``beam`` object provides the following metamethods: + +**__init** + A *metamethod* ``()`` returning ``self`` after having processed the attributes with the special protect-and-update mechanism, where the order of the updates is undefined. It also creates new particle on-the-fly if the ``mass`` and the ``charge`` are defined, and then select it. + +**__newindex** + A *metamethod* ``(key, val)`` called by the assignment operator ``[key]=val`` to create new attributes for the pairs (*key*, *value*) or to update the underlying physical quantity of the ``beam`` objects. + + +The following attribute is stored with metamethods in the metatable, but has different purpose: + + +**__beam** + A unique private *reference* that characterizes beams. + + +Particles database +------------------ + +The ``beam`` *object* manages the particles database, which is shared by all ``beam`` instances. The default set of supported particles is: + electron, positron, proton, antiproton, neutron, antineutron, ion, muon, + antimuon, deuteron, antideuteron, negmuon (=muon), posmuon (=antimuon). + +New particles can be added to the database, either explicitly using the ``new_particle`` method, or by creating or updating a beam *object* and specifying all the attributes of a particle, i.e. ``particle``'s name, ``charge``, ``mass``, and (optional) ``spin``: + +.. code-block:: lua + + local beam in MAD + local nmass, pmass, mumass in MAD.constant + + -- create a new particle + beam:new_particle{ particle='mymuon', mass=mumass, charge=-1, spin=1/2 } + + -- create a new beam and a new nucleus + local pbbeam = beam { particle='pb208', mass=82*pmass+126*nmass, charge=82 } + +The particles database can be displayed with the ``showdb`` method at any time from any beam: + +.. code-block:: lua + + beam:showdb() -- check that both, mymuon and pb208 are in the database. + + +Particle charges +---------------- + +The physics of \MAD is aware of particle charges. To enable the compatibility with codes like MAD-X that ignores the particle charges, the global option ``nocharge`` can be used to control the behavior of created beams as shown by the following example: + +.. code-block:: lua + + local beam, option in MAD + local beam1 = beam { particle="electron" } -- beam with negative charge + print(beam1.charge, option.nocharge) -- display: -1 false + + option.nocharge = true -- disable particle charges + local beam2 = beam { particle="electron" } -- beam with negative charge + print(beam2.charge, option.nocharge) -- display: 1 true + + -- beam1 was created before nocharge activation... + print(beam1.charge, option.nocharge) -- display: -1 true + +This approach ensures consistency of beams behavior during their entire lifetime. [#f2]_ + +Examples +-------- + + + +.. code-block:: lua + + local beam in MAD + local lhcb1, lhcb2 in MADX + local nmass, pmass, amass in MAD.constant + local pbmass = 82*pmass+126*nmass + + -- attach a new beam with a new particle to lhcb1 and lhcb2. + lhc1.beam = beam 'Pb208' { particle='pb208', mass=pbmass, charge=82 } + lhc2.beam = lhc1.beam -- let sequences share the same beam... + + -- print Pb208 nuclei energy-mass in GeV and unified atomic mass. + print(lhcb1.beam.mass, lhcb1.beam.mass/amass) + + +.. rubric:: Footnotes + +.. [#f1] The ``qelect`` value is defined in the :doc:`constants` module.`` +.. [#f2] The option ``rbarc`` in MAD-X is too volatile and does not ensure such consistency... diff --git a/docs/source/beta0.rst b/docs/source/beta0.rst new file mode 100644 index 000000000..3db9f5f18 --- /dev/null +++ b/docs/source/beta0.rst @@ -0,0 +1,48 @@ +Beta0 Blocks +============ +.. _ch.gen.beta0: + + + +The ``beta0`` object is the *root object* of beta0 blocks that store information relative to the phase space at given positions, e.g. initial conditions, Poincaré section. + +The ``beta0`` module extends the :doc:`typeid ` module with the ``is_beta0`` *function*, which returns ``true`` if its argument is a ``beta0`` object, ``false`` otherwise. + +Attributes +---------- + +The ``beta0`` *object* provides the following attributes: + +**particle** + A *string* specifying the name of the particle. (default: ``"positron"``). + + +Methods +------- + +The ``beta0`` object provides the following methods: + +**showdb** + A *method* ``([file])`` displaying the content of the particles database to ``file`` (default: ``io.stdout``). + + +Metamethods +----------- + +The ``beta0`` object provides the following metamethods: + +**__init** + A *metamethod* ``()`` returning \SLF after having processed the attributes with the special protect-and-update mechanism, where the order of the updates is undefined. It also creates new particle on-the-fly if the ``mass`` and the ``charge`` are defined, and then select it. + + + + +**__beta0** + A unique private *reference* that characterizes beta0 blocks. + + +Examples +-------- + +.. rubric:: Footnotes + diff --git a/docs/source/cffi.rst b/docs/source/cffi.rst new file mode 100644 index 000000000..824ea2b35 --- /dev/null +++ b/docs/source/cffi.rst @@ -0,0 +1,4 @@ +.. _ch.prg.cffi: + +Using C FFI +=========== \ No newline at end of file diff --git a/docs/source/cofind.rst b/docs/source/cofind.rst new file mode 100644 index 000000000..c013bf69b --- /dev/null +++ b/docs/source/cofind.rst @@ -0,0 +1,239 @@ +Cofind +====== +.. _ch.cmd.cofind: + +The ``cofind`` command (i.e. closed orbit finder) provides a simple interface to find a closed orbit using the Newton algorithm on top of the ``track`` command. + +Command synopsis +---------------- + + + +.. code-block:: lua + :caption: Synopsis of the ``cofind`` command with default setup. + :name: fig-cofind-synop + + mtbl, mflw = cofind} { + sequence=sequ, -- sequence (required) + beam=nil, -- beam (or sequence.beam, required) + range=nil, -- range of tracking (or sequence.range) + dir=nil, -- s-direction of tracking (1 or -1) + s0=nil, -- initial s-position offset [m] + X0=nil, -- initial coordinates (or damap, or beta block) + O0=nil, -- initial coordinates of reference orbit + deltap=nil, -- initial deltap(s) + nturn=nil, -- number of turns to track + nslice=nil, -- number of slices (or weights) for each element + mapdef=true, -- setup for damap (or list of, true => {}) + method=nil, -- method or order for integration (1 to 8) + model=nil, -- model for integration ('DKD' or 'TKT') + ptcmodel=nil, -- use strict PTC thick model (override option) + implicit=nil, -- slice implicit elements too (e.g. plots) + misalign=nil, -- consider misalignment + fringe=nil, -- enable fringe fields (see element.flags.fringe) + radiate=nil, -- radiate at slices + totalpath=nil, -- variable 't' is the totalpath + save=false, -- create mtable and save results + title=nil, -- title of mtable (default seq.name) + observe=nil, -- save only in observed elements (every n turns) + savesel=nil, -- save selector (predicate) + savemap=nil, -- save damap in the column __map + atentry=nil, -- action called when entering an element + atslice=nil, -- action called after each element slices + atexit=nil, -- action called when exiting an element + ataper=nil, -- action called when checking for aperture + atsave=nil, -- action called when saving in mtable + atdebug=fnil, -- action called when debugging the element maps + codiff=1e-10, -- finite differences step for jacobian + coiter=20, -- maximum number of iterations + cotol=1e-8, -- closed orbit tolerance (i.e.~|dX|) + X1=0, -- optional final coordinates translation + info=nil, -- information level (output on terminal) + debug=nil, -- debug information level (output on terminal) + usrdef=nil, -- user defined data attached to the mflow + mflow=nil, -- mflow, exclusive with other attributes + } + +The ``cofind`` command format is summarized in :numref:`fig-cofind-synop`, including the default setup of the attributes. Most of these attributes are set to :const:`nil` by default, meaning that ``cofind`` relies on the ``track`` command defaults. + +The ``cofind`` command supports the following attributes: + +.. _cofind.attr: + **sequence** + The *sequence* to track. (no default, required). + Example: ``sequence = lhcb1``. + + **beam** + The reference *beam* for the tracking. If no beam is provided, the command looks for a beam attached to the sequence, i.e. the attribute ``seq.beam``. + Example: ``beam = beam 'lhcbeam' { beam-attributes }``. [#f1]_ + + **range** + A *range* specifying the span of the sequence track. If no range is provided, the command looks for a range attached to the sequence, i.e. the attribute . (default: :const:`nil`). + Example: ``range = "S.DS.L8.B1/E.DS.R8.B1"``. + + **dir** + The :math:`s`-direction of the tracking: ``1`` forward, ``-1`` backward. (default: :const:`nil`). + Example: ``dir = - 1``. + + **s0** + A *number* specifying the initial :math:`s`-position offset. (default: :const:`nil`). + Example: ``s0 = 5000``. + + **X0** + A *mappable* (or a list of *mappable*) specifying initial coordinates ``{x,px,y,py, t,pt}``, damap, or beta block for each tracked object, i.e. particle or damap. The beta blocks are converted to damaps, while the coordinates are converted to damaps only if ``mapdef`` is specified, but both will use ``mapdef`` to setup the damap constructor. Each tracked object may also contain a ``beam`` to override the reference beam, and a *logical* ``nosave`` to discard this object from being saved in the mtable. (default: :const:`nil`). + Example: ``X0 = { x=1e- 3, px=- 1e- 5 }``. + + **O0** + A *mappable* specifying initial coordinates ``{x,px,y,py,t,pt}`` of the reference orbit around which X0 definitions take place. If it has the attribute ``cofind == true``, it will be used as an initial guess to search for the reference closed orbit. (default: ``0`` ). + Example: ``O0 = { x=1e- 4, px=- 2e- 5, y=- 2e- 4, py=1e- 5 }``. + + **deltap** + A *number* (or list of *number*) specifying the initial :math:`\delta_p` to convert (using the beam) and add to the ``pt`` of each tracked particle or damap. (default::const:`nil`). + Example: ``s0 = 5000``. + + **nturn** + A *number* specifying the number of turn to track. (default: :const:`nil`). + Example: ``nturn = 2``. + + **nstep** + A *number* specifying the number of element to track. A negative value will track all elements. (default: :const:`nil`). + Example: ``nstep = 1``. + + **nslice** + A *number* specifying the number of slices or an *iterable* of increasing relative positions or a *callable* ``(elm, mflw, lw)`` returning one of the two previous kind of positions to track in the elements. The arguments of the callable are in order, the current element, the tracked map flow, and the length weight of the step. This attribute can be locally overridden by the element. (default: :const:`nil`). + Example: ``nslice = 5``. + + **mapdef** + A *logical* or a *damap* specification as defined by the :doc:`DAmap ` module to track DA maps instead of particles coordinates. A value of ``true`` is equivalent to invoke the *damap* constructor with ``{}`` as argument. A value of ``false`` or :const:`nil` disable the use of damaps and force ``cofind`` to replace each particles or damaps by seven particles to approximate their Jacobian by finite difference. (default: ``true``). + Example: ``mapdef = { xy=2, pt=5 }``. + + **method** + A *number* specifying the order of integration from 1 to 8, or a *string* specifying a special method of integration. Odd orders are rounded to the next even order to select the corresponding Yoshida or Boole integration schemes. The special methods are ``simple`` (equiv. to ``DKD`` order 2), ``collim`` (equiv. to ``MKM`` order 2), and ``teapot`` (Teapot splitting order 2). (default: :const:`nil`). + Example: ``method = 'teapot'``. + + **model** + A *string* specifying the integration model, either ``'DKD'`` for *Drift-Kick-Drift* thin lens integration or ``'TKT'`` for *Thick-Kick-Thick* thick lens integration. [#f2]_ (default: :const:`nil`) + Example: ``model = 'DKD'``. + + **ptcmodel** + A *logical* indicating to use strict PTC model. [#f3]_ (default: :const:`nil`) + Example: ``ptcmodel = true``. + + **implicit** + A *logical* indicating that implicit elements must be sliced too, e.g. for smooth plotting. (default: :const:`nil`). + Example: ``implicit = true``. + + **misalign** + A *logical* indicating that misalignment must be considered. (default: :const:`nil`). + Example: ``misalign = true``. + + **fringe** + A *logical* indicating that fringe fields must be considered or a *number* specifying a bit mask to apply to all elements fringe flags defined by the element module. The value ``true`` is equivalent to the bit mask , i.e. allow all elements (default) fringe fields. (default: :const:`nil`). + Example: ``fringe = false``. + + **radiate** + A *logical* enabling or disabling the radiation or the *string* specifying the ``'average'`` type of radiation during the closed orbit search. The value ``true`` is equivalent to ``'average'`` and the value ``'quantum'`` is converted to ``'average'``. (default: :const:`nil`). + Example: ``radiate = 'average'``. + + **totalpath** + A *logical* indicating to use the totalpath for the fifth variable ``'t'`` instead of the local path. (default: :const:`nil`). + Example: ``totalpath = true``. + + **save** + A *logical* specifying to create a *mtable* and record tracking information at the observation points. The ``save`` attribute can also be a *string* specifying saving positions in the observed elements: ``"atentry"``, ``"atslice"``, ``"atexit"`` (i.e. ``true``), ``"atbound"`` (i.e. entry and exit), ``"atbody"`` (i.e. slices and exit) and ``"atall"``. (default: ``false``). + Example: ``save = false``. + + **title** + A *string* specifying the title of the *mtable*. If no title is provided, the command looks for the name of the sequence, i.e. the attribute ``seq.name``. (default: :const:`nil`). + Example: ``title = "track around IP5"``. + + **observe** + A *number* specifying the observation points to consider for recording the tracking information. A zero value will consider all elements, while a positive value will consider selected elements only, checked with method :meth:`:is_observed`, every :math:`>0` turns. (default: :const:`nil`). + Example: ``observe = 1``. + + **savesel** + A *callable* ``(elm, mflw, lw, islc)`` acting as a predicate on selected elements for observation, i.e. the element is discarded if the predicate returns ``false``. The arguments are in order, the current element, the tracked map flow, the length weight of the slice and the slice index. (default: :const:`nil`) + Example: ``savesel = \LMB e -> mylist[e.name] ~= nil``. + + **savemap** + A *logical* indicating to save the damap in the column ``__map`` of the *mtable*. (default: :const:`nil`). + Example: ``savemap = true``. + + **atentry** + A *callable* ``(elm, mflw, 0, - 1)`` invoked at element entry. The arguments are in order, the current element, the tracked map flow, zero length and the slice index ``-1``. (default: :const:`nil`). + Example: ``atentry = myaction``. + + **atslice** + A *callable* ``(elm, mflw, lw, islc)`` invoked at element slice. The arguments are in order, the current element, the tracked map flow, the length weight of the slice and the slice index. (default: :const:`nil`). + Example: ``atslice = myaction``. + + **atexit** + A *callable* ``(elm, mflw, 0, - 2)`` invoked at element exit. The arguments are in order, the current element, the tracked map flow, zero length and the slice index . (default: :const:`nil`). + Example: ``atexit = myaction``. + + **ataper** + A *callable* ``(elm, mflw, lw, islc)`` invoked at element aperture checks, by default at last slice. The arguments are in order, the current element, the tracked map flow, the length weight of the slice and the slice index. If a particle or a damap hits the aperture, then its ``status~=~"lost"`` and it is removed from the list of tracked items. (default: :const:`fnil`). + Example: ``ataper = myaction``. + + **atsave** + A *callable* ``(elm, mflw, lw, islc)`` invoked at element saving steps, by default at exit. The arguments are in order, the current element, the tracked map flow, the length weight of the slice and the slice index. (default: :const:`nil`). + Example: ``atsave = myaction``. + + **atdebug** + A *callable* ``(elm, mflw, lw, [msg], [...])`` invoked at the entry and exit of element maps during the integration steps, i.e. within the slices. The arguments are in order, the current element, the tracked map flow, the length weight of the integration step and a *string* specifying a debugging message, e.g. ``"map_name:0"`` for entry and ``":1"`` for exit. If the level ``debug`` :math:`\geq 4` and ``atdebug`` is not specified, the default *function* ``mdump`` is used. In some cases, extra arguments could be passed to the method. (default: :const:`fnil`). + Example: ``atdebug = myaction``. + + **codiff** + A *number* specifying the finite difference step to approximate the Jacobian when damaps are disabled. If ``codiff`` is larger than :math:`100\times`\ ``cotol``, it will be adjusted to ``cotol`` :math:`/100` and a warning will be emitted. (default: ``1e- 8``). + Example: ``codiff = 1e- 8``. + + **coiter** + A *number* specifying the maximum number of iteration. If this threshold is reached, all the remaining tracked objects are tagged as ``"unstable"``. (default: 20). + Example: ``coiter = 5``. + + **cotol** + A *number* specifying the closed orbit tolerance. If all coordinates update of a particle or a damap are smaller than ``cotol``, then it is tagged as ``"stable"``. (default: ``1e-8``). + Example: ``cotol = 1e- 6``. + + **X1** + A *mappable* specifying the coordinates ``{x,px,y,py,t,pt}`` to *subtract* to the final coordinates of the particles or the damaps. (default: ``0``). + Example: ``X1 = { t=100, pt=10 }``. + + **info** + A *number* specifying the information level to control the verbosity of the output on the console. (default: :const:`nil`). + Example: ``info = 2``. + + **debug** + A *number* specifying the debug level to perform extra assertions and to control the verbosity of the output on the console. (default: :const:`nil`). + Example: ``debug = 2``. + + **usrdef** + Any user defined data that will be attached to the tracked map flow, which is internally passed to the elements method ``:track`` and to their underlying maps. (default: :const:`nil`). + Example: ``usrdef = { myvar=somevalue }``. + + **mflow** + A *mflow* containing the current state of a ``track`` command. If a map flow is provided, all attributes are discarded except ``nstep``, ``info`` and ``debug``, as the command was already set up upon its creation. (default: :const:`nil`). + Example: ``mflow = mflow0``. + +The ``cofind`` command stops when all particles or damap are tagged as ``"stable"``, ``"unstable"``, ``"singular"`` or ``"lost"``. The ``cofind`` command returns the following objects in this order: + + **mtbl** + A *mtable* corresponding to the TFS table of the ``track`` command where the ``status`` column may also contain the new values ``"stable"``, ``"unstable"`` or ``"singular"``. + + **mflw** + A *mflow* corresponding to the map flow of the ``track`` command. The particles or damaps ``status`` are tagged and ordered by ``"stable"``, ``"unstable"``, ``"singular"``, ``"lost"`` and ``id``. + +Cofind mtable +------------- +.. _sec.cofind.mtable: + +The ``cofind`` command returns the ``track`` *mtable* unmodified except for the ``status`` column. The tracked objects id will appear once per iteration at the ``\$end`` marker, and other defined observation points if any, until they are removed from the list of tracked objects. + +Examples +-------- + +TODO + +.. [#f1] Initial coordinates ``X0`` may override it by providing a beam per particle or damap. +.. [#f2] The ``TKT`` scheme (Yoshida) is automatically converted to the ``MKM`` scheme (Boole) when appropriate. +.. [#f3] In all cases, MAD-NG uses PTC setup ``time=true, exact=true``. diff --git a/docs/source/commands.rst b/docs/source/commands.rst new file mode 100644 index 000000000..4b38ee878 --- /dev/null +++ b/docs/source/commands.rst @@ -0,0 +1,9 @@ +.. _ch.prg.cmd: + +Commands +======== + + +Adding Commands +--------------- + diff --git a/docs/source/conf.py b/docs/source/conf.py index c39a7c34b..0266f70a0 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -4,6 +4,10 @@ # Configuration file for the Sphinx documentation builder. # For the full list of built-in configuration values, see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html +from pygments_mad_lexer import MadLexer + +from sphinx.highlighting import lexers +lexers['mad'] = MadLexer() # -- Project information ----------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information @@ -18,14 +22,17 @@ # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration primary_domain = "mad" #Use .. default-domain:: c to change to c then .. default-domain:: mad to change back to mad -extensions = ["customRoles", "sphinx-mad-domain"] +extensions = [ + "customRoles", + "sphinx-mad-domain", + ] source_suffix = { '.rst': 'restructuredtext', - '.mad': 'lua', } -highlight_language = "lua" +highlight_language = "mad" +numfig = True templates_path = ['_templates'] exclude_patterns = [] @@ -53,11 +60,65 @@ # -- Options for latexpdf output ---------------------------------------------- latex_toplevel_sectioning = 'part' +latex_docclass = { + 'manual': 'cernrep', + 'howto': 'cernrep' +} latex_elements = { 'preamble': ''' + \\usepackage{nameref} % For getting chapter name + + \\renewcommand\sphinxtableofcontentshook{} \\addto\\captionsenglish{\\renewcommand{\\contentsname}{Table of contents}} + + %table spacing + %\\setlength{\\tabcolsep}{10pt} % Default value: 6pt + %\\renewcommand{\\arraystretch}{1.5} % Default value: 1 + + %Change the title formats + \\titleformat{\\chapter }{\\normalfont\\LARGE\\bfseries}{Chapter \\thechapter . }{1em}{} + \\titlespacing*{\\chapter}{0pt}{-20pt}{10pt} + \\titleformat{\\section }{\\normalfont\\Large\\bfseries}{\\thesection }{1em}{} + \\titleformat{\\subsection }{\\normalfont\\large\\bfseries}{\\thesubsection }{1em}{} + \\titleformat{\\subsubsection}{\\normalfont\\large\\bfseries}{\\thesubsubsection}{1em}{} + + \\makeatletter + %Changes headers and footers + \\fancypagestyle{normal}{ % After page 3 + \\fancyhf{} + \\fancyhead[R]{\\thepage} + \\fancyhead[L]{\\it{\\thechapter . \\MakeUppercase{\\@currentlabelname}}} + \\renewcommand{\\headrulewidth}{1pt} + \\renewcommand{\\footrulewidth}{0pt} + } + \\fancypagestyle{plain}{ % for up to page 3 + \\fancyhf{} + \\fancyhead[R]{\\thepage} + } + \\makeatother ''', + 'fncychap': '', + 'sphinxsetup': "InnerLinkColor={rgb}{0,0,1}, OuterLinkColor={rgb}{0,0,1}",#'verbatimwithframe = false', #Remove border around code blocks + 'tableofcontents': '\\tableofcontents', + 'maketitle': """ + \\institute{ + Accelerator Beam Physics,\\\\ + CERN, Meyrin, Switzerland.} + + \\begin{abstract} + The Methodical Accelerator Design -- Next Generation application is an all-in-one standalone versatile tool for particle accelerator design, modeling, and optimization, and for beam dynamics and optics studies. Its general purpose scripting language is based on the simple yet powerful Lua programming language (with a few extensions) and embeds the state-of-art Just-In-Time compiler LuaJIT. Its physics is based on symplectic integration of differential maps made out of GTPSA (Generalized Truncated Power Series). The physics of the transport maps and the normal form analysis were both strongly inspired by the PTC/FPP library from E. Forest. MAD-NG development started in 2016 by the author as a side project of MAD-X, hence MAD-X users should quickly become familiar with its ecosystem, e.g. lattices definition. + \\begin{center} + \\texttt{http://cern.ch/mad} + \\end{center} + \\end{abstract} + + \\keywords{Methodical Accelerator Design; Accelerator beam physics; Scientific computing; JIT compiler; C and Lua programming.} + + \\maketitle""", + 'extraclassoptions': "oneside" } +latex_table_style = ['booktabs'] +latex_additional_files = ["latex_additional_files/" + x for x in os.listdir("latex_additional_files/")] # -- Options for MAN output ------------------------------------------------- diff --git a/docs/source/correct.rst b/docs/source/correct.rst new file mode 100644 index 000000000..d21c8b9b0 --- /dev/null +++ b/docs/source/correct.rst @@ -0,0 +1,210 @@ +Correct +======= +.. _ch.cmd.correct: + +The ``correct`` command (i.e. orbit correction) provides a simple interface to compute the orbit steering correction and setup the kickers of the sequences from the analysis of their ``track`` and ``twiss`` mtables. + +.. code-block:: + :caption: Synopsis of the ``correct`` command with default setup. + :name: fig-correct-synop + + mlst = correct { + sequence=nil, -- sequence(s) (required) + range=nil, -- sequence(s) range(s) (or sequence.range) + title=nil, -- title of mtable (default seq.name) + model=nil, -- mtable(s) with twiss functions (required) + orbit=nil, -- mtable(s) with measured orbit(s), or use model + target=nil, -- mtable(s) with target orbit(s), or zero orbit + kind='ring', --\ 'line' or 'ring' + plane='xy', --\ 'x', 'y' or 'xy' + method='micado',--\ 'LSQ', 'SVD' or 'MICADO' + ncor=0, -- number of correctors to consider by method, 0=all + tol=1e-5, -- rms tolerance on the orbit + units=1, -- units in [m] of the orbit + corcnd=false, -- precond of correctors using 'svdcnd' or 'pcacnd' + corcut=0, -- value to theshold singular values in precond + cortol=0, -- value to theshold correctors in svdcnd + corset=true, -- update correctors correction strengths + monon=false, -- fraction (0` module to find the orbit correction, namely ``solve``, ``ssolve`` or ``nsolve``. (default: ``'micado'``). + Example: ``method = 'svd'``. + + **ncor** + A *number* specifying the number of correctors to consider with the method ``micado``, zero meaning all available correctors. (default: ``0``). + Example: ``ncor = 4``. + + **tol** + A *number* specifying the rms tolerance on the residuals for the orbit correction. (default: 1e-6). + Example: ``tol = 1e- 6``. + + **unit** + A *number* specifying the unit of the ``orbit`` and ``target`` coordinates. (default: ``1`` [m]). + Example: ``units = 1e- 3`` [m], i.e. [mm]. + + **corcnd** + A *log* or a *string* specifying the method to use among ``svdcnd`` and ``pcacnd`` from the :doc:`linear algebra ` module for the preconditioning of the system. A ``true`` value corresponds to . (default: ``false``). + Example: ``corcnd = 'pcacnd'``. + + **corcut** + A *number* specifying the thresholds for the singular values to pass to the ``svdcnd`` and ``pcacnd`` method for the preconditioning of the system. (default: ``0``). + Example: ``cortol = 1e- 6``. + + **cortol** + A *number* specifying the thresholds for the correctors to pass to the ``svdcnd`` method for the preconditioning of the system. (default: ``0``). + Example: ``cortol = 1e- 8``. + + **corset** + A *log* specifying to update the correctors strengths for the corrected orbit. (default: ``true``). + Example: ``corset = false``. + + **monon** + A *number* specifying a fraction of available monitors selected from a uniform RNG. (default: ``false``). + Example: ``monon = 0.8``, keep 80% of the monitors. + + **moncut** + A *number* specifying a threshold in number of sigma to cut monitor considered as outliers. (default: ``false``). + Example: ``moncut = 2``, cut monitors above :math:`2\sigma`. + + **monerr** + A *number* in ``0..3`` specifying the type of monitor reading errors to consider: ``1`` use scaling errors ``msex`` and ``msey``, ``2`` use alignment errors ``mrex``, ``mrey`` and ``dpsi``, ``3`` use both. (default: ``false``). + Example: ``monerr = 3``. + + **info** + A *number* specifying the information level to control the verbosity of the output on the console. (default: ``nil``). + Example: ``info = 2``. + + **debug** + A *number*\ specifying the debug level to perform extra assertions and to control the verbosity of the output on the console. (default: ``nil``). + Example: ``debug = 2``. + + +The ``correct`` command returns the following object: + + ``mlst`` + A *mtable* (or a list of *mtable*) corresponding to the TFS table of the ``correct`` command. It is a list when multiple sequences are corrected together. + + +Correct mtable +-------------- +.. _sec.correct.mtable: + +The ``correct`` command returns a *mtable* where the information described hereafter is the default list of fields written to the TFS files. [#f1]_ + + + + **name** + The name of the command that created the ``"correct"``. + **type** + The type of the ``"correct"``. + **title** + The value of the command attribute ``title``. + **origin** + The origin of the application that created the ``"MAD 1.0.0 OSX 64"``. + **date** + The date of the creation of the ``"27/05/20"``. + **time** + The time of the creation of the ``"19:18:36"``. + **refcol** + The reference *column* for the *mtable* dictionnary, e.g. ``"name"``. + **range** + The value of the command attribute ``range``. [#f2]_ + **__seq** + The *sequence* from the command attribute ``sequence``. [#f3]_ .. _ref.track.mtbl1}: + + + + **name** + The name of the element. + **kind** + The kind of the element. + **s** + The :math:`s`-position at the end of the element slice. + **l** + The length from the start of the element to the end of the element slice. + **x_old** + The local coordinate :math:`x` at the :math:`s`-position before correction. + **y_old** + The local coordinate :math:`y` at the :math:`s`-position before correction. + **x** + The predicted local coordinate :math:`x` at the :math:`s`-position after correction. + **y** + The predicted local coordinate :math:`y` at the :math:`s`-position after correction. + **rx** + The predicted local residual :math:`r_x` at the :math:`s`-position after correction. + **ry** + The predicted local residual :math:`r_y` at the :math:`s`-position after correction. + **hkick_old** + The local horizontal kick at the :math:`s`-position before correction. + **vkick_old** + The local vertical kick at the :math:`s`-position before correction. + **hkick** + The predicted local horizontal kick at the :math:`s`-position after correction. + **vkick** + The predicted local vertical kick at the :math:`s`-position after correction. + **shared** + A *log* indicating if the element is shared with another sequence. + **eidx** + The index of the element in the sequence. + +Note that ``correct`` does not take into account the particles and damaps ``id``s present in the (augmented) ``track`` *mtable*, hence the provided tables should contain single particle or damap information. + +Examples +-------- + + + +.. rubric:: Footnotes + +.. [#f1] The output of mtable in TFS files can be fully customized by the user. +.. [#f2] This field is not saved in the TFS table by default. +.. [#f3] Fields and columns starting with two underscores are protected data and never saved to TFS files.\label{ref:track:mtbl1 diff --git a/docs/source/dynmap.rst b/docs/source/dynmap.rst new file mode 100644 index 000000000..ef05b9628 --- /dev/null +++ b/docs/source/dynmap.rst @@ -0,0 +1,4 @@ +.. _ch.phy.dynmap: + +Dynamic Maps +============ diff --git a/docs/source/elements.rst b/docs/source/elements.rst index 7ebb784c2..d370a53f9 100644 --- a/docs/source/elements.rst +++ b/docs/source/elements.rst @@ -1,9 +1,776 @@ Elements ======== +.. _ch.gen.elems: -Just a link +The ``element`` object is the *root object* of all elements used to model particle accelerators, including sequences and drifts. It provides most default values inherited by all elements. -.. _elm-misalign: +The ``element`` module extends the :doc:`typeid ` module with the ``is_element`` *function*, which returns ``true`` if its argument is an ``element`` object, ``false`` otherwise. + +Taxonomy +-------- + +The classes defined by the ``element`` module are organized according to the kinds and the roles of their instances. The classes defining the kinds are: + +**thin** + The *thin* elements have zero-length and their physics does not depend on it, i.e. the attribute ``l`` is discarded or forced to zero in the physics. + +**thick** + The *thick* elements have a length and their physics depends on it. Elements like ``sbend``, ``rbend``, ``quadrupole``, ``solenoid``, and ``elseparator`` trigger a runtime error if they have zero-length. Other thick elements will accept to have zero-length for compatibility with MAD-X [#f1]_ , but their physics will have to be adjusted. [#f2]_ + +**drift** + The *drift* elements have a length with a ``drift``-like physics if :math:`l\geq` ``minlen`` [#f3]_ otherwise they are discarded or ignored. Any space between elements with a length :math:`l\geq` ``minlen`` are represented by an ``implicit`` drift created on need by the :math:`s`-iterator of sequences and discarded afterward. + +**patch** + The *patch* elements have zero-length and the purpose of their physics is to change the reference frame. + +**extrn** + The *extern* elements are never part of sequences. If they are present in a sequence definition, they are expanded and replaced by their content, i.e. stay external to the lattice. + +**specl** + The *special* elements have special roles like *marking* places (i.e. ``maker``) or *branching* sequences (i.e. ``slink``). + +These classes are not supposed to be used directly, except for extending the hierarchy defined by the ``element`` module and schematically reproduced hereafter to help users understanding: + +.. code-block:: lua + + thin_element = element 'thin_element' { is_thin = true } + thick_element = element 'thick_element' { is_thick = true } + drift_element = element 'drift_element' { is_drift = true } + patch_element = element 'patch_element' { is_patch = true } + extrn_element = element 'extrn_element' { is_extern = true } + specl_element = element 'specl_element' { is_special = true } + + sequence = extrn_element 'sequence' { } + assembly = extrn_element 'assembly' { } + bline = extrn_element 'bline' { } + + marker = specl_element 'marker' { } + slink = specl_element 'slink' { } + + drift = drift_element 'drift' { } + collimator = drift_element 'collimator' { } + instrument = drift_element 'instrument' { } + placeholder = drift_element 'placeholder' { } + + sbend = thick_element 'sbend' { } + rbend = thick_element 'rbend' { } + quadrupole = thick_element 'quadrupole' { } + sextupole = thick_element 'sextupole' { } + octupole = thick_element 'octupole' { } + decapole = thick_element 'decapole' { } + dodecapole = thick_element 'dodecapole' { } + solenoid = thick_element 'solenoid' { } + tkicker = thick_element 'tkicker' { } + wiggler = thick_element 'wiggler' { } + elseparator = thick_element 'elseparator' { } + rfcavity = thick_element 'rfcavity' { } + genmap = thick_element 'genmap' { } + + beambeam = thin_element 'beambeam' { } + multipole = thin_element 'multipole' { } + + xrotation = patch_element 'xrotation' { } + yrotation = patch_element 'yrotation' { } + srotation = patch_element 'srotation' { } + translate = patch_element 'translate' { } + changeref = patch_element 'changeref' { } + changedir = patch_element 'changedir' { } + changenrj = patch_element 'changenrj' { } + + -- specializations + rfmultipole = rfcavity 'rfmultipole' { } + crabcavity = rfmultipole 'crabcavity' { } + + monitor = instrument 'monitor' { } + hmonitor = monitor 'hmonitor' { } + vmonitor = monitor 'vmonitor' { } + + kicker = tkicker 'kicker' { } + hkicker = kicker 'hkicker' { } + vkicker = kicker 'vkicker' { } + + +All the classes above, including ``element``, define the attributes ``kind = name`` and ``is_name = true`` where ``name`` correspond to the class name. These attributes help to identify the kind and the role of an element as shown in the following code excerpt: + +.. code-block:: lua + + local drift, hmonitor, sequence in MAD.element + local dft = drift {} + local bpm = hmonitor {} + local seq = sequence {} + print(dft.kind) -- display: drift + print(dft.is_drift) -- display: true + print(dft.is_drift_element) -- display: true + print(bpm.kind) -- display: hmonitor + print(bpm.is_hmonitor) -- display: true + print(bpm.is_monitor) -- display: true + print(bpm.is_instrument) -- display: true + print(bpm.is_drift_element) -- display: true + print(bpm.is_element) -- display: true + print(bpm.is_drift) -- display: true + print(bpm.is_thick_element) -- display: nil (not defined = false) + print(seq.kind) -- display: sequence + print(seq.is_element) -- display: true + print(seq.is_extrn_element) -- display: true + print(seq.is_thick_element) -- display: nil (not defined = false) + + +Attributes +---------- + +The ``element`` *object* provides the following attributes: + +**l** + A *number* specifying the physical length of the element on the design orbit [m]. (default: ``0``). + +**lrad** + A *number* specifying the field length of the element on the design orbit considered by the radiation [m]. (default: :literal:`lrad = \s -> s.l`). + +**angle** + A *number* specifying the bending angle :math:`\alpha` of the element [rad]. A positive angle represents a bend to the right, i.e. a :math:`-y`-rotation towards negative x values. (default: ``0``). + +**tilt** + A *number* specifying the physical tilt of the element [rad]. All the physical quantities defined by the element are in the tilted frame, except ``misalign`` that comes first when tracking through an element, see the :doc:`track ` command for details. (default: ``0``). + +**model** + A *string* specifying the integration model ``"DKD"`` or ``"TKT"`` to use when tracking through the element and overriding the command attribute, see the :doc:`track ` command for details. (default: ``cmd.model``). + +**method** + A *number* specifying the integration order 2, 4, 6, or 8 to use when tracking through the element and overriding the command attribute, see the :doc:`track ` command for details. (default: ``cmd.method``). + +**nslice** + A *number* specifying the number of slices or a *list* of increasing relative positions or a *callable* ``(elm, mflw, lw)`` returning one of the two previous kind of positions specification to use when tracking through the element and overriding the command attribute, see the :doc:`survey ` or the :doc:`track ` commands for details. (default: ``cmd.nslice``). + +**refpos** + A *string* holding one of ``"entry"``, ``"centre"`` or ``"exit"``, or a *number* specifying a position in [m] from the start of the element, all of them resulting in an offset to substract to the ``at`` attribute to find the :math:`s`-position of the element entry when inserted in a sequence, see :ref:`element positions` for details. (default: ``nil`` :math:`\equiv` ``seq.refer``). + +**aperture** + A *mappable* specifying aperture attributes, see :ref:`Aperture ` for details. \\ + (default: ``{kind='circle', 1}``). + +**apertype** + A *string* specifying the aperture type, see :ref:`Aperture ` for details. \\ + (default: :literal:`\s -> s.aperture.kind or 'circle'`). [#f4]_ + +**misalign** + A *mappable* specifying misalignment attributes, see :ref:`Misalignment ` for details. \\ + + + +The ``thick_element`` *object* adds the following multipolar and fringe fields attributes: + +**knl, ksl** + A *list* specifying respectively the **multipolar** and skew integrated strengths of the element [m\ :math:`^{-i+1}`]. (default: ). + +**dknl, dksl** + A *list* specifying respectively the multipolar and skew integrated strengths errors of the element [m\ :math:`^{-i+1}`]. (default: ). + +**e1, e2** + A *number* specifying respectively the horizontal angle of the pole faces at entry and exit of the element [rad]. A positive angle goes toward inside the element, see Figures ``_ and ``_. (default: ``0``). + +**h1, h2** + A *number* specifying respectively the horizontal curvature of the pole faces at entry and exit of the element [m\ :math:`^{-1}`]. A positive curvature goes toward inside the element. (default: ). + +**hgap** + A *number* specifying half of the vertical gap at the center of the pole faces of the element [m]. (default: ``0``). + +**fint** + A *number* specifying the fringe field integral at entrance of the element. (default: ``0``). + +**fintx** + A *number* specifying the fringe field integral at exit of the element. (default: ``fint``). + +**fringe** + A *number* specifying the bitmask to activate fringe fields of the element, see :ref:`Flags ` for details. (default: ``0``). + +**fringemax** + A *number* specifying the maximum order for multipolar fringe fields of the element. (default: ``2``). + +**kill_ent_fringe** + A *log* specifying to kill the entry fringe fields of the element. (default: ``false``). + +**kill_exi_fringe** + A *log* specifying to kill the entry fringe fields of the element. (default: ``false``). + +**f1, f2** + A *number* specifying quadrupolar fringe field first and second parameter of SAD. (default: ``0``). + + +Methods +------- + +The ``element`` object provides the following methods: + +**select** + A *method* ``([flg])`` to select the element for the flags ``flg`` (default: ``selected``). + +**deselect** + A *method* ``([flg])`` to deselect the element for the flags ``flg`` (default: ``selected``). + +**is_selected** + A *method* ``([flg])`` to test the element for the flags ``flg`` (default: ``selected``). + +**is_disabled** + A *method* ``()`` to test if the element is *disabled*, which is equivalent to call the method ``is_selected(disabled)``. + +**is_observed** + A *method* ``()`` to test if the element is *observed*, which is equivalent to call the method ``is_selected(observed)``. + +**is_implicit** + A *method* ``()`` to test if the element is *implicit*, which is equivalent to call the method ``is_selected(implicit)``. + + +The ``drift_element`` and ``thick_element`` objects provide the following extra methods, see :ref:`sub-elements ` for details about the ``sat`` attribute: + +**index_sat** + A *method* ``(sat, [cmp])`` returning the lowest index ``idx`` (starting from 1) of the first sub-element with a relative position from the element entry that compares ``true`` with the *number* ``sat`` using the optional \CALBLA{cmp(sat, self[idx].sat)} (default: ``"=="``), or ``#self+1``. In the presence of multiple equal positions, ``"<="`` (resp. ``">="``) will return the lowest index of the position while ``"<"`` (resp. ``">"``) the lowest index next to the position for ascending (resp. descending) order. + +**insert_sat** + A *method* ``(elm, [cmp])`` returning the element after inserting the sub-element ``elm`` at the index determined by ``:index_sat(elm.sat, [cmp])`` using the optional \CALBLA{cmp} (default: ``"<"``). + +**replace_sat** + A *method* ``(elm)`` returning the replaced sub-element found at the index determined by ``:index_sat(elm.sat)`` by the new sub-element ``elm``, or ``nil``. + +**remove_sat** + A *method* ``(sat)`` returning the removed sub-element found at the index determined by ``:index_sat(sat)``, or ``nil``. + + +Metamethods +----------- + +The ``element`` object provides the following metamethods: + +**__len** + A *metamethod* ``()`` overloading the length operator ``#`` to return the number of subelements in the *list* part of the element. + +**__add** + A *metamethod* ``(obj)`` overloading the binary operator ``+`` to build a ``bline`` object from the juxtaposition of two elements. + +**__mul** + A *metamethod* ``(n)`` overloading the binary operator ``*`` to build a ``bline`` object from the repetition of an element ``n`` times, i.e. one of the two operands must be a *number*. + +**__unm** + A *metamethod* ``(n)`` overloading the unary operator ``-`` to build a ``bline`` object from the turning of an element, i.e. reflect the element. + +**__tostring** + A *metamethod* ``()`` returning a *string* built from the element information, e.g. ``print(monitor 'bpm' {})`` display the *string* ``":monitor: 'bpm' memory-address`` + + +The operators overloading of elements allows to unify sequence and beamline definitions in a consistent and simple way, noting that ``sequence`` and ``bline`` are (external) elements too. + + + +**__elem** + A unique private *reference* that characterizes elements. + + +Elements +-------- + +Some elements define new attributes or override the default values provided by the *root object* ``element``. The following subsections describe the elements supported by \MAD. + +SBend +""""" + +The ``sbend`` element is a sector bending magnet with a curved reference system as shown in :numref:`fig-gen-sbend`, and defines or overrides the following attributes: + +**k0** + A ``number`` specifying the dipolar strength of the element [:math:`\mathrm{m}^{-1}`]. + (default: :literal:`k0 = \s -> s.angle/s.l`). [#f5]_ [#f6]_ + +**k0s** + A *number* specifying the dipolar skew strength of the element [m\ :math:`^{-1}`]. (default: ``0``). + +**k1, k1s** + A *number* specifying respectively the quadrupolar and skew strengths of the element [m\ :math:`^{-2}`]. (default: ``0``). + +**k2, k2s** + A *number* specifying respectively the sextupolar and skew strengths of the element [m\ :math:`^{-3}`]. (default: ``0``). + +**fringe** + Set to flag ``fringe.bend`` to activate the fringe fields by default, see :ref:`Flags ` for details. + +.. figure:: fig/elm_refsys_sbend.jpg + :name: fig-gen-sbend + :align: center + + Reference system for a sector bending magnet. + +RBend +""""" + +The ``rbend`` element is a rectangular bending magnet with a straight reference system as shown in :numref:`fig-gen-rbend`, and defines or overrides the following attributes: + +**k0** + A ``number`` specifying the dipolar strength of the element [:math:`\mathrm{m}^{-1}`]. + (default: :literal:`k0 = \s -> s.angle/s.l`). [#f5]_ [#f6]_ + +**k0s** + A *number* specifying the dipolar skew strength of the element [m\ :math:`^{-1}`]. (default: ``0``). + +**k1, k1s** + A *number* specifying respectively the quadrupolar and skew strengths of the element [m\ :math:`^{-2}`]. (default: ``0``). + +**k2, k2s** + A *number* specifying respectively the sextupolar and skew strengths of the element [m\ :math:`^{-3}`]. (default: ``0``). + +**fringe** + Set to flag ``fringe.bend`` to activate the fringe fields by default, see :ref:`Flags ` for details. + +**true_rbend** + A *log* specifying if this ``rbend`` element behaves like (``false``) a ``sbend`` element with parallel pole faces, i.e. :math:`e_1=e_2=\alpha/2` in Figure ``_ , or like (``true``) a rectangular bending magnet with a straight reference system as shown in Figure ``_ . (default: ``false``). [#f6]_ + +.. figure:: fig/elm_refsys_rbend.jpg + :name: fig-gen-rbend + :align: center + + Reference system for a rectangular bending magnet. + +Quadrupole +"""""""""" + +The ``quadrupole`` element is a straight focusing element and defines the following attributes: + +**k0, k0s** + A *number* specifying respectively the dipolar and skew strengths of the element [m\ :math:`^{-1}`]. (default: ``0``). + +**k1, k1s** + A *number* specifying respectively the quadrupolar and skew strengths of the element [m\ :math:`^{-2}`]. (default: ``0``). + +**k2, k2s** + A *number* specifying respectively the sextupolar and skew strengths of the element [m\ :math:`^{-3}`]. (default: ``0``). + + +Sextupole +""""""""" + +The ``sextupole`` element is a straight element and defines the following attributes: + +**k2, k2s** + A *number* specifying respectively the sextupolar and skew strengths of the element [m\ :math:`^{-3}`]. (default: ``0``). + + +Octupole +"""""""" + +The ``octupole`` element is a straight element and defines the following attributes: + +**k3, k3s** + A *number* specifying respectively the octupolar and skew strengths of the element [m\ :math:`^{-4}`]. (default: ``0``). + + +Decapole +"""""""" + +The ``decapole`` element is a straight element and defines the following attributes: + +**k4, k4s** + A *number* specifying respectively the decapolar and skew strength of the element [m\ :math:`^{-5}`]. (default: ``0``). + + +Dodecapole +"""""""""" + +The ``dodecapole`` element is a straight element and defines the following attributes: + +**k5, k5s** + A *number* specifying respectively the dodecapolar and skew strength of the element [m\ :math:`^{-6}`]. (default: ``0``). + + +Solenoid +"""""""" + +The ``solenoid`` element defines the following attributes: + +**ks, ksi** + A *number* specifying respectively the strength [rad/m] and the integrated strength [rad] of the element. A positive value points toward positive :math:`s`. (default: ``0``). + + +Multipole +""""""""" + +The ``multipole`` element is a thin element and defines the following attributes: + +**knl, ksl** + A *list* specifying respectively the multipolar and skew integrated strengths of the element [m\ :math:`^{-i+1}`]. (default: ``{}``). + +**dknl, dksl** + A *list* specifying respectively the multipolar and skew integrated strengths errors of the element [m\ :math:`^{-i+1}`]. (default: ``{}``). + + +TKicker +""""""" + +The ``tkicker`` element is the *root object* of kickers and defines or overrides the following attributes: + +**hkick** + A *number* specifying the horizontal strength of the element [m\ :math:`^{-1}`]. By convention, a kicker with a positive horizontal strength kicks in the direction of the reference orbit, e.g. ``hkick`` :math:`\equiv` ``- knl[1]``. (default: ``0``). + +**vkick** + A *number* specifying the vertical strength of the element [m\ :math:`^{-1}`]. By convention, a kicker with a positive vertical strength kicks toward the reference orbit, e.g. ``vkick`` :math:`\equiv` ``ksl[1]``}. (default: ``0``). + +**method** + Set to ``2`` if ``ptcmodel`` is not set to enforce pure momentum kick and avoid dipolar strength integration that would introduce dispersion. + + +Kicker, HKicker, VKicker +"""""""""""""""""""""""" + +The ``kicker`` element inheriting from the ``tkicker`` element, is the *root object* of kickers involved in the orbit correction and defines the following attributes: + +**chkick, cvkick** + A *number* specifying respectively the horizontal and vertical correction strength of the element set by the :doc:`correct ` command [m\ :math:`^{-1}`]. (default: ). + + +The ``hkicker`` (horizontal kicker) and ``vkicker`` (vertical kicker) elements define the following attribute: + +**kick** + A *number* specifying the strength of the element in its main direction [m\ :math:`^{-1}`]. (default: ). + + +Monitor, HMonitor, VMonitor +""""""""""""""""""""""""""" + +The ``monitor`` element is the root object of monitors involved in the orbit correction and defines the following attributes: + +**mredx, mredy** + A *number* specifying respectively the readout :math:`x`\ , :math:`y`\ -offset error of the element [m]. The offset is added to the beam position during orbit correction (after scaling). (default: ``0``). + +**mresx, mresy** + A *number* specifying respectively the readout :math:`x`\ ,:math:`y`\ -scaling error of the element. The scale factor multiplies the beam position by ``1+mres`` (before offset) during orbit correction. [#f7]_ (default: ``0``). + + +The ``hmonitor`` (horizontal monitor) and ``vmonitor`` (vertical monitor) elements are specialisations inheriting from the ``monitor`` element. + +RFCavity +"""""""" + +The ``rfcavity`` element defines the following attributes: + +**volt** + A *number* specifying the peak RF voltage of the element [MV]. (default: ``0``). + +**freq** + A *number* specifying a non-zero RF frequency of the element [MHz]. (default: ``0``). + +**lag** + A *number* specifying the RF phase lag of the element in unit of :math:`2\pi`. (default: ``0``). + +**harmon** + A *number* specifying the harmonic number of the element if ``freq`` is zero. (default: ``0``). + +**n_bessel** + A *number* specifying the transverse focussing effects order of the element. (default: ``0``). + +**totalpath** + A *log* specifying if the totalpath must be used in the element. (default: ``true``). + + +RFMultipole +""""""""""" + +The ``rfmultipole`` element defines the following attributes: + +**pnl, psl** + A *list* specifying respectively the multipolar and skew phases of the element [rad]. (default: :literal:`{}`). + +**dpnl, dpsl** + A *list* specifying respectively the multipolar and skew phases errors of the element [rad]. (default: :literal:`{}`). + + +ElSeparator +""""""""""" + +The ``elseparator`` element defines the following attributes: + +**ex, ey** + A *number* specifying respectively the electric field :math:`x`\ , :math:`y`\ -strength of the element [MV/m]. (default: ``0``). + +**exl, eyl** + A *number* specifying respectively the integrated electric field :math:`x`\ , :math:`y`\ -strength of the element [MV]. (default: ``0``). + + +Wiggler +""""""" + +The ``wiggler`` element defines the following attributes: NYI, TBD + +BeamBeam +"""""""" + +The ``beambeam`` element defines the following attributes: NYI, TBD + +GenMap +"""""" + +The ``genmap`` element defines the following attributes: [#f8]_ + +**damap** + A ``damap`` used for thick integration. + +**update** + A *callable* ``(elm, mflw, lw)`` invoked before each step of thick integration to update the ``damap``. (default: ``nil``) + +**nslice** + A *number* specifying the number of slices or a *list* of increasing relative positions or a *callable* ``(elm, mflw, lw)`` returning one of the two previous kind of positions specification to use when tracking through the element and overriding the command attribute, see the :doc:`survey ` or the :doc:`track ` commands for details. (default: ``1``). + + +SLink +""""" + +The ``slink`` element defines the following attributes: [#f9]_ + +**sequence** + A *sequence* to switch to right after exiting the element. (default: ``nil``) + +**range** + A *range* specifying the span over the sequence to switch to, as expected by the sequence method ``:siter``. (default: ``nil``). + +**nturn** + A *number* specifying the number of turn to track the sequence to switch to, as expected by the sequence method ``:siter``. (default: ``nil``). + +**dir** + A *number* specifying the :math:`s`-direction of the tracking of the sequence to switch to, as expected by the sequence method ``:siter``. (default: ``nil``). + +**update** + A *callable* ``(elm, mflw)`` invoked before retrieving the other attributes when entering the element. (default: ``nil``) + + +Translate +""""""""" + +The ``translate`` element is a patch element and defines the following attributes: + +**dx, dy, ds** + A *number* specifying respectively :math:`x`\ , :math:`y`\ , :math:`s`-translation of the reference frame [m]. (default: ``0``) + + +XRotation, YRotation, SRotation +""""""""""""""""""""""""""""""" + +The ``xrotation`` (rotation around :math:`x`-axis), ``yrotation`` (rotation around :math:`y`-axis) and ``srotation`` (rotation around :math:`s`-axis) elements are patches element and define the following attribute: + +**angle** + A *number* specifying the rotation angle around the axis of the element [rad]. (default: ``0``). + + +ChangeRef +""""""""" + +The ``changeref`` element is a patch element and defines the following attributes: + +**dx, dy, ds** + A *number* specifying respectively :math:`x`\ , :math:`y`\ , :math:`s`-translation of the reference frame [m]. (default: ``0``) + +**dtheta, dphi, dpsi** + A *number* specifying respectively :math:`y`\ , :math:`-x`\ , :math:`s`-rotation of the reference frame applied in this order after any translation [rad]. (default: ``0``) + + +ChangeDir +""""""""" + +The ``changedir`` element is a patch element that reverses the direction of the sequence during the tracking. + +ChangeNrj +""""""""" + +The ``changenrj`` element is a patch element and defines the following attributes: + +**dnrj** + A *number* specifying the change by :math:`\delta_E` of the *reference* beam energy [GeV]. The momenta of the particles or damaps belonging to the reference beam (i.e. not owning a beam) are updated, while other particles or damaps owning their beam are ignored. (default: ``0``) + +.. _sec.elm.flgs: + +Flags +----- + +The ``element`` module exposes the following *object* flags through ``MAD.element.flags`` to use in conjunction with the methods ``select`` and ``deselect``: [#f10]_ + +**none** + All bits zero. + +**selected** + Set if the element has been selected. + +**disabled** + Set if the element has been disabled, e.g. for orbit correction. + +**observed** + Set if the element has been selected for observation, e.g. for output to TFS table. + The ``$end`` markers are selected for observation by default, and commands with the ``observe`` attribute set to ``0`` discard this flag and consider all elements as selected for observation. + +**implicit** + Set if the element is implicit, like the temporary *implicit* drifts created on-the-fly by the ``sequence`` :math:`s`-iterator with indexes at half integers. This flag is used by commands with the ``implicit`` attribute. + +**playout** + Set if the element ``angle`` must be used by layout plot. This flag is useful to plot multiple sequence layouts around interaction points, like ``lhcb1`` and ``lhcb2`` around ``IP1`` and ``IP5``. + +.. _sec.elm.frng: + +Fringe fields +------------- + +The ``element`` module exposes the following flags through ``MAD.element.flags.fringe`` to *control* the elements fringe fields through their attribute ``fringe``, or to *restrict* the activated fringe fields with the commands attribute ``fringe``: [#f11]_ + +**none** + All bits zero. + +**bend** + Control the element fringe fields for bending fields. + +**mult** + Control the element fringe fields for multipolar fields up to ``fringemax`` order. + +**rfcav** + Control the element fringe fields for rfcavity fields. + +**qsad** + Control the element fringe fields for multipolar fields with extra terms for quadrupolar fields for compatibility with SAD. + +**comb** + Control the element fringe fields for combined bending and multipolar fields. + +**combqs** + Control the element fringe fields for combined bending and multipolar fields with extra terms for quadrupolar fields for compatibility with SAD. + +The ``thick_element`` provides a dozen of attributes to parametrize the aforementionned fringe fields. Note that in some future, part of these attributes may be grouped into a *mappable* to ensure a better consistency of their parametrization. + +.. _sec.elm.subelm: + +Sub-elements +------------ + +An element can have thin or thick sub-elements stored in its *list* part, hence the length operator ``#`` returns the number of them. The attribute ``sat`` of sub-elements, i.e. read ``s``\ ub-\ ``at``\ , is interpreted as their relative position from the entry of their enclosing main element, that is a fractional of its length. The positions of the sub-elements can be made absolute by dividing their ``sat`` attribute by the length of their main element using lambda expressions. The sub-elements are only considered and valid in the ``drift_element`` and ``thick_element`` kinds that implement the methods ``:index_sat``, ``:insert_sat``, ``:remove_sat``, and ``:replace_sat`` to manage sub-elements from their ``sat`` attribute. The sequence method ``:install`` updates the ``sat`` attribute of the elements installed as sub-elements if the *log* ``elements.subelem`` of the packed form is enabled, i.e. when the :math:`s`-position determined by the ``at``, ``from`` and ``refpos`` attributes falls inside a non-zero length element already installed in the sequence that is not an *implicit* drift. The physics of thick sub-elements will shield the physics of their enclosing main element along their length, unless they combine their attributes with those of their main element using lambda expressions to select some combined function physics. + +.. _sec.elm.aper: + +Aperture +-------- + +All the apertures are *mappable* defined by the following attributes in the tilted frame of an element, see the :doc:`track ` command for details: + +**kind** + A *string* specifying the aperture shape. (no default). + +**tilt** + A *number* specifying the tilt angle of the aperture [rad]. (default: ``0``). + +**xoff, yoff** + A *number* specifying the transverse :math:`x,y`\ -offset of the aperture [m]. (default: ``0``). + +**maper** + A *mappable* specifying a smaller aperture [#f12]_ than the ``polygon`` aperture to use before checking the polygon itself to speed up the test. The attributes ``tilt``, ``xoff`` and ``yoff`` are ignored and superseded by the ones of the ``polygon`` aperture. (default: ``nil``). + + +The supported aperture shapes are listed hereafter. The parameters defining the shapes are expected to be in the *list* part of the apertures and defines the top-right sector shape, except for the ``polygon``: + +**square** + A square shape with one parameter defining the side half-length. It is the default aperture check with limits set to ``1``. + +**rectangle** + A rectangular shape with two parameters defining the :math:`x`\ , :math:`y`\ -half lengths (default: ``1`` [m]). + +**circle** + A circular shape with one parameter defining the radius. + +**ellipse** + A elliptical shape with two parameters defining the :math:`x`\ , :math:`y`\ -radii. (default: ``1`` [m]). + +**rectcircle** + A rectangular shape intersected with a circular shape with three parameters defining the :math:`x`\ , :math:`y`\ -half lengths and the radius. (default: ``1`` [m]). + +**rectellipse** + A rectangular shape intersected with an elliptical shape with four parameters defining the :math:`x`\ , :math:`y`\ -half lengths and the :math:`x`\ , :math:`y`\ -radii. + +**racetrack** + A rectangular shape with corners rounded by an elliptical shape with four parameters defining the :math:`x`\ , :math:`y`\ -half lengths and the corners :math:`x`\ , :math:`y`\ -radii. + +**octagon** + A rectangular shape with corners truncated by a triangular shape with four parameters defining the :math:`x`\ , :math:`y`\ -half lengths and the triangle :math:`x`\ , :math:`y`\ -side lengths. An octagon can model hexagon or diamond shapes by equating the triangle lengths to the rectangle half-lengths. + +**polygon** + A polygonal shape defined by two vectors ``vx`` and ``vy`` holding the vertices coordinates. The polygon does not need to be convex, simple or closed, but in the latter case it will be closed automatically by joining the first and the last vertices. + +**bbox** + A 6D bounding box with six parameters defining the upper limits of the absolute values of the six coordinates. + + + + +.. code-block:: lua + + local quadrupole in MAD.element + local mq = quadrupole 'mq' { l=1, -- new class + aperture = { kind='racetrack', + tilt=pi/2, xoff=1e-3, yoff=5e-4, -- attributes + 0.06,0.06,0.01,0.01 } -- parameters + } + local mqdiam = quadrupole 'mqdiam' { l=1, -- new class + aperture = { kind='octagon', xoff=1e-3, yoff=1e-3, -- attributes + 0.06,0.04,0.06,0.04 } -- parameters + } + local mqpoly = quadrupole 'mqpoly' { l=1, -- new class + aperture = { kind='polygon', tilt=pi/2, xoff=1e-3, yoff=1e-3, -- attributes + vx=vector{0.05, ...}, vy=vector{0, ...}, -- parameters + aper={kind='circle', 0.05} -- 2nd aperture + } + +.. _sec.elm.misalign: Misalignment ------------- \ No newline at end of file +------------ + +The misalignments are *mappable* defined at the entry of an element by the following attributes, see the :doc:`track ` command for details: + +**dx, dy, ds** + A *number* specifying the :math:`x`\ , :math:`y`\ , :math:`s`\ -displacement at the element entry [m], see :numref:`fig-gen-dispxs` and :numref:`fig-gen-dispys` . (default: ``0``). + +**dtheta** + A *number* specifying the :math:`y`-rotation angle (azimuthal) at the element entry [rad], see :numref:`fig-gen-dispxs`. (default: ``0``). + +**dphi** + A *number* specifying the :math:`-x`-rotation angle (elevation) at the entry of the element [rad], see :numref:`fig-gen-dispxy` . (default: ``0``). + +**dpsi** + A *number* specifying the :math:`s`-rotation angle (roll) at the element entry [rad], see :numref:`fig-gen-dispxy` . (default: ``0``). + +Two kinds of misalignments are available for an element and summed beforehand: + + +* The *absolute* misalignments of the element versus its local reference frame, and specified by its ``misalign`` attribute. These misalignments are always considered. + +* The *relative* misalignments of the element versus a given sequence, and specified by the ``:misalign`` of ``sequence``. These misalignments can be considered or not depending of command settings. + +.. figure:: fig/elm_dsplmnt_xs.jpg + :name: fig-gen-dispxs + :align: center + + Displacements in the :math:`(x, s)` plane. + +.. figure:: fig/elm_dsplmnt_ys.jpg + :name: fig-gen-dispys + :align: center + + Displacements in the :math:`(y, s)` plane. + + +.. figure:: fig/elm_dsplmnt_xy.jpg + :name: fig-gen-dispxy + :align: center + + Displacements in the :math:`(x, y)` plane. + +.. rubric:: Footnotes + +.. [#f1] In MAD-X, zero-length ``sextupole`` and ``octupole`` are valid but may have surprising effects... +.. [#f2] E.g. zero-length ``sextupole`` must define their strength with ``knl[3]`` instead of ``k2`` to have the expected effect. +.. [#f3] By default ``minlen`` = :math:`10^{-12}` m. +.. [#f4] This attribute was introduced to ease the translation of MAD-X sequences and may disappear in some future. +.. [#f5] By default bending magnets are ideal bends, that is ``angle = k0*l`` +.. [#f6] For compatibility with MAD-X. +.. [#f7] This definition comes from MAD-X default zeroed values such that undefined attribute gives a scale of ``1``. +.. [#f8] This element is a generalization of the ``matrix`` element of MAD-X, to use with care! +.. [#f9] This element allows to switch between sequences during tracking, kind of ``if-then-else`` for tracking. +.. [#f10] Remember that flags are *not* inherited nor copied as they are qualifying the object itself. +.. [#f11] Those flags are *not* object flags, but fringe fields flags. +.. [#f12] It is the responsibility of the user to ensure that ``maper`` defines a smaller aperture than the polygon aperture. \ No newline at end of file diff --git a/docs/source/emit.rst b/docs/source/emit.rst new file mode 100644 index 000000000..5569dcd1f --- /dev/null +++ b/docs/source/emit.rst @@ -0,0 +1,8 @@ +Emit +==== +.. _ch.cmd.emit: + +This command is not yet implemented in MAD. It will probably be implemented as a layer on top of the Twiss and Match commands. + +.. rubric:: Footnotes + diff --git a/docs/source/extern.rst b/docs/source/extern.rst new file mode 100644 index 000000000..c7ac53593 --- /dev/null +++ b/docs/source/extern.rst @@ -0,0 +1,3 @@ +External modules +================ +.. _ch.mod.extrn: diff --git a/docs/source/fig/dyna-trck-slice-crop.png b/docs/source/fig/dyna-trck-slice-crop.png new file mode 100644 index 000000000..7333de0ce Binary files /dev/null and b/docs/source/fig/dyna-trck-slice-crop.png differ diff --git a/docs/source/fig/dyna-trck-slice.png b/docs/source/fig/dyna-trck-slice.png new file mode 100644 index 000000000..fb1c10851 Binary files /dev/null and b/docs/source/fig/dyna-trck-slice.png differ diff --git a/docs/source/fig/elm_dsplmnt_xs.jpg b/docs/source/fig/elm_dsplmnt_xs.jpg new file mode 100644 index 000000000..77131cea1 Binary files /dev/null and b/docs/source/fig/elm_dsplmnt_xs.jpg differ diff --git a/docs/source/fig/elm_dsplmnt_xy.jpg b/docs/source/fig/elm_dsplmnt_xy.jpg new file mode 100644 index 000000000..5fc0190f7 Binary files /dev/null and b/docs/source/fig/elm_dsplmnt_xy.jpg differ diff --git a/docs/source/fig/elm_dsplmnt_ys.jpg b/docs/source/fig/elm_dsplmnt_ys.jpg new file mode 100644 index 000000000..60709a757 Binary files /dev/null and b/docs/source/fig/elm_dsplmnt_ys.jpg differ diff --git a/docs/source/fig/elm_refsys_rbend.jpg b/docs/source/fig/elm_refsys_rbend.jpg new file mode 100644 index 000000000..7dbeee150 Binary files /dev/null and b/docs/source/fig/elm_refsys_rbend.jpg differ diff --git a/docs/source/fig/elm_refsys_sbend.jpg b/docs/source/fig/elm_refsys_sbend.jpg new file mode 100644 index 000000000..2a1c0a3de Binary files /dev/null and b/docs/source/fig/elm_refsys_sbend.jpg differ diff --git a/docs/source/fig/geom-trck-slice-crop.png b/docs/source/fig/geom-trck-slice-crop.png new file mode 100644 index 000000000..058a028e2 Binary files /dev/null and b/docs/source/fig/geom-trck-slice-crop.png differ diff --git a/docs/source/fig/madng-ecosys-crop.png b/docs/source/fig/madng-ecosys-crop.png new file mode 100644 index 000000000..e669399f0 Binary files /dev/null and b/docs/source/fig/madng-ecosys-crop.png differ diff --git a/docs/source/fig/objmod-lookup-crop.png b/docs/source/fig/objmod-lookup-crop.png new file mode 100644 index 000000000..5891a31b5 Binary files /dev/null and b/docs/source/fig/objmod-lookup-crop.png differ diff --git a/docs/source/fig/phys_refsys_glo.jpg b/docs/source/fig/phys_refsys_glo.jpg new file mode 100644 index 000000000..de66ce414 Binary files /dev/null and b/docs/source/fig/phys_refsys_glo.jpg differ diff --git a/docs/source/fig/phys_refsys_loc.jpg b/docs/source/fig/phys_refsys_loc.jpg new file mode 100644 index 000000000..899c08e1d Binary files /dev/null and b/docs/source/fig/phys_refsys_loc.jpg differ diff --git a/docs/source/functions.rst b/docs/source/functions.rst index e77a1a097..bd1baf036 100644 --- a/docs/source/functions.rst +++ b/docs/source/functions.rst @@ -129,7 +129,7 @@ Special Functions The special function :func:`fact()` supports negative integers as input as it uses extended factorial definition, and the values are cached to make its complexity in :math:`O(1)` after warmup. -The special function :func:`rangle()` adjust the angle :var:`a` versus the *previous* right angle :var:`r`, e.g. during phase advance accumulation, to ensure proper value when passing through the :math:`±2k\pi` boundaries. +The special function :func:`rangle()` adjust the angle :var:`a` versus the *previous* right angle :var:`r`, e.g. during phase advance accumulation, to ensure proper value when passing through the :math:`\pm 2k\pi` boundaries. =================== ================================================ ========================= Functions Return values C functions diff --git a/docs/source/geomap.rst b/docs/source/geomap.rst new file mode 100644 index 000000000..7606ede2f --- /dev/null +++ b/docs/source/geomap.rst @@ -0,0 +1,4 @@ +.. _ch.phy.geomap: + +Geometric Maps +============== \ No newline at end of file diff --git a/docs/source/gphys.rst b/docs/source/gphys.rst new file mode 100644 index 000000000..2d9209edd --- /dev/null +++ b/docs/source/gphys.rst @@ -0,0 +1,4 @@ +Generic Physics +=============== + +Just a link (never written) diff --git a/docs/source/index.rst b/docs/source/index.rst index 3c809fbf7..db9b2b546 100644 --- a/docs/source/index.rst +++ b/docs/source/index.rst @@ -30,6 +30,12 @@ Welcome to MAD-NG's Reference Manual! /part-IV.rst +.. toctree:: + :maxdepth: 3 + :caption: Part V: + + /part-V.rst + Indices and tables ================== diff --git a/docs/source/integrators.rst b/docs/source/integrators.rst new file mode 100644 index 000000000..0ea2b8ca5 --- /dev/null +++ b/docs/source/integrators.rst @@ -0,0 +1,4 @@ +.. _ch.phy.intrg: + +Integrators +=========== diff --git a/docs/source/intro.rst b/docs/source/intro.rst new file mode 100644 index 000000000..fa8a19c0d --- /dev/null +++ b/docs/source/intro.rst @@ -0,0 +1,202 @@ +Introduction +============ +.. _ch.gen.intro: + +Presentation +------------ + +The Methodical Accelerator Design -- Next Generation application is an all-in-one standalone versatile tool for particle accelerator design, modeling, and optimization, and for beam dynamics and optics studies. Its general purpose scripting language is based on the simple yet powerful Lua programming language (with a few extensions) and embeds the state-of-art Just-In-Time compiler LuaJIT. Its physics is based on symplectic integration of differential maps made out of GTPSA (Generalized Truncated Power Series). The physics of the transport maps and the normal form analysis were both strongly inspired by the PTC/FPP library from E. Forest. MAD-NG development started in 2016 by the author as a side project of MAD-X, hence MAD-X users should quickly become familiar with its ecosystem, e.g. lattices definition. + +MAD-NG is free open-source software, distributed under the GNU General Public License v3. The source code, units tests, integration tests, and examples are all available on its Github `repository `_, including the `documentation `_ and its LaTeX source. For convenience, the binaries and few examples are also made available from the `releases repository `_ located on the AFS shared file system at CERN. + +Installation +------------ + +Download the binary corresponding to your platform from the `releases repository`_ and install it in a local directory. Update (or check) that the and install it in a local directory. Update (or check) that the ``PATH`` environment variable contains the path to your local directory or prefix environment variable contains the path to your local directory or prefix ``mad`` with this path to run it. Rename the application from with this path to run it. Rename the application from ``mad-arch-v.m.n`` to to ``mad`` and make it executable with the command ' and make it executable with the command '``chmod u+x mad``' on Unix systems or add the extension on Windows. + +.. code-block:: console + + $ ./mad - h + usage: ./mad [options]... [script [args]...]. + Available options are: + - e chunk Execute string 'chunk'. + - l name Require library 'name'. + - b ... Save or list bytecode. + - j cmd Perform JIT control command. + - O[opt] Control JIT optimizations. + - i Enter interactive mode after executing 'script'. + - q Do not show version information. + - M Do not load MAD environment. + - Mt[=num] Set initial MAD trace level to 'num'. + - MT[=num] Set initial MAD trace level to 'num' and location. + - E Ignore environment variables. + -- Stop handling options. + - Execute stdin and stop handling options. + +Releases version +"""""""""""""""" + +MAD-NG releases are tagged on the Github repository and use mangled binary names on the releases repository, i.e. ``mad-arch-v.m.n`` where: + +**arch** + is the platform architecture for binaries among ``linux``, ``macos`` and ``windows``. +**v** + is the **v**\ ersion number, ``0`` meaning beta-version under active development. +**m** + is the **m**\ ajor release number corresponding to features completeness. +**n** + is the mi\ **n**\ or release number corresponding to bug fixes. + + +Interactive Mode +---------------- + +To run MAD-NG in interactive mode, just typewrite its name on the Shell invite like any command-line tool. It is recommended to wrap MAD-NG with the `readline wrapper `_ in interactive mode for easier use and commands history: + +.. code-block:: console + + $ rlwrap ./mad + ____ __ ______ ______ | Methodical Accelerator Design + / \/ \ / _ \ / _ \ | release: 0.9.0 (OSX 64) + / __ / / /_/ / / /_/ / | support: http://cern.ch/mad + /__/ /_/ /__/ /_/ /_____ / | licence: GPL3 (C) CERN 2016+ + | started: 2020-08-01 20:13:51 + + +.. code-block:: + + > print "hello world!" + "hello world!" + +Here the application is assumed to be installed in the current directory '``.``' and the character '``>``' is the prompt waiting for user input in interactive mode. If you write an incomplete statement, the interpreter waits for its completion by issuing a different prompt: + +.. code-block:: + + > print -- 1st level prompt, incomplete statement + >> "hello world!" -- 2nd level prompt, complete the statement + hello world! -- execute + +Typing the character '``=``' right after the 1st level prompt is equivalent to call the :literal:`print` function: + +.. code-block:: + + > = "hello world!" -- 1st level prompt followed by = + hello world! -- execute print "hello world!" + > = MAD.option.numfmt + % -.10g + + +To quit the application typewrite ``Crtl+D`` to send ``EOF`` (end-of-file) on the input, [#f2]_ ``Crtl+\`` to send the ``SIGQUIT`` (quit) signal, or ``Crtl+C`` to send the stronger ``SIGINT`` (interrupt) signal. If the application is stalled or looping for ever, typewriting a single ``Crtl+\`` or ``Crtl+C`` twice will stop it: + +.. code-block:: + + > while true do end -- loop forever, 1st Crtl+C doesn't stop it + pending interruption (*in*) VM! (next will exit) -- 2nd Crtl+C + interrupted! -- application stopped + + > while true do end -- loop forever, a single Crtl+\ does stop it + Quit: 3 -- Signal 3 caught, application stopped + + +In interactive mode, each line input is run in its own *chunk* [#f3]_, which also rules variables scopes. Hence ``local``, variables are not visible between chunks, i.e. input lines. The simple solutions are either to use global variables or to enclose local statements into the same chunk delimited by the ``do ... end`` keywords: + +.. code-block:: + + > local a = "hello" + > print(a.." world!") + stdin:1: attempt to concatenate global 'a' (a nil value) + stack traceback: + stdin:1: (*in*) main chunk + [C]: at 0x01000325c0 + + > do -- 1st level prompt, open the chunck + >> local a = "hello" -- 2nd level prompt, waiting for statement completion + >> print(a.." world!") -- same chunk, local 'a' is visible + >> end -- close and execute the chunk + hello world! + > print(a) -- here 'a' is an unset global variable + nil + > a = "hello" -- set global 'a' + > print(a.." world!") -- works but pollutes the global environment + hello world! + + +Batch Mode +---------- + +To run MAD-NG in batch mode, just run it in the shell with files as arguments on the command line: + +.. code-block:: console + + $ ./mad [mad options] myscript1.mad myscript2.mad ... + + +where the scripts contains programs written in the MAD-NG programming language (see :doc:`Scripting