From 8f618d63988634bae3e0741bfeb2e288dfece81b Mon Sep 17 00:00:00 2001 From: Joshua Gray <61458311+jgray-19@users.noreply.github.com> Date: Thu, 19 Mar 2026 13:48:04 +0100 Subject: [PATCH] Various updates --- refman/source/mad_cmd_cofind.rst | 190 ++++----- refman/source/mad_cmd_match.rst | 574 ++++++++++++++-------------- refman/source/mad_cmd_track.rst | 219 +++++++---- refman/source/mad_cmd_twiss.rst | 262 +++++++------ refman/source/mad_gen_madx.rst | 107 +++++- refman/source/mad_gen_mtable.rst | 48 +-- refman/source/mad_gen_object.rst | 3 +- refman/source/mad_gen_sequence.rst | 6 +- refman/source/mad_mod_const.rst | 9 +- refman/source/mad_mod_cplxnum.rst | 45 +-- refman/source/mad_mod_functions.rst | 99 ++--- refman/source/mad_mod_linalg.rst | 116 +++--- refman/source/mad_mod_miscfuns.rst | 4 +- refman/source/mad_mod_monomial.rst | 30 +- refman/source/mad_mod_numrange.rst | 40 +- 15 files changed, 985 insertions(+), 767 deletions(-) diff --git a/refman/source/mad_cmd_cofind.rst b/refman/source/mad_cmd_cofind.rst index a392820..6e89372 100644 --- a/refman/source/mad_cmd_cofind.rst +++ b/refman/source/mad_cmd_cofind.rst @@ -13,45 +13,51 @@ Command synopsis :caption: Synopsis of the :var:`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) + 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 + 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 + method=nil, -- method or order for integration (1 to 8) + model=nil, -- model for integration ('DKD' or 'TKT') + mapdef=true, -- setup for damap (or list of, true => {}) + secnmul=nil, -- curved-multipole expansion for bends + implicit=nil, -- slice implicit elements too (e.g. plots) + misalign=nil, -- consider misalignment + aperture=nil, -- default aperture + fringe=nil, -- enable fringe fields (see element.flags.fringe) + frngmax=nil, -- maximum multipole fringe field order + radiate=nil, -- radiate at slices + nocavity=nil, -- disable rfcavities + totalpath=nil, -- variable 't' is the totalpath + cmap=nil, -- use C/C++ maps when available + ptcmodel=nil, -- nil=MADNG, true=PTC, false=MADX + save=false, -- create mtable and save results + aper=nil, -- check for aperture + 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=nil, -- action called when debugging the element maps + apersel=nil, -- aperture selector (predicate) + coitr=25, -- maximum number of iterations + cotol=1e-8, -- closed orbit tolerance (i.e.|dX|) + costp=1e-8, -- finite-difference scale for the Jacobian + O1=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 :var:`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 :var:`cofind` relies on the :var:`track` command defaults. @@ -60,7 +66,7 @@ The :var:`cofind` command supports the following attributes: .. _cofind.attr: **sequence** - The *sequence* to track. (no default, required). + The *sequence* to track. (no default, required). Example: :expr:`sequence = lhcb1`. @@ -70,187 +76,179 @@ The :var:`cofind` command supports the following attributes: Example: :expr:`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 :attr:`seq.range`. (default: :const:`nil`). + 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 :attr:`seq.range`. (default: :const:`nil`). Example: :expr:`range = "S.DS.L8.B1/E.DS.R8.B1"`. **dir** - The :math:`s`-direction of the tracking: :const:`1` forward, :const:`-1` backward. (default: :const:`nil`). + The :math:`s`-direction of the tracking: :const:`1` forward, :const:`-1` backward. (default: :const:`nil`). Example: :expr:`dir = -1`. **s0** - A *number* specifying the initial :math:`s`-position offset. (default: :const:`nil`). + A *number* specifying the initial :math:`s`-position offset. (default: :const:`nil`). Example: :expr:`s0 = 5000`. **X0** - A *mappable* (or a list of *mappable*) specifying initial coordinates :literal:`{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 :literal:`mapdef` is specified, but both will use :literal:`mapdef` to setup the damap constructor. Each tracked object may also contain a :var:`beam` to override the reference beam, and a *logical* :literal:`nosave` to discard this object from being saved in the mtable. (default: :const:`nil`). + A *mappable* (or a list of *mappable*) specifying initial coordinates :literal:`{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 :literal:`mapdef` is specified, but both will use :literal:`mapdef` to setup the damap constructor. Each tracked object may also contain a :var:`beam` to override the reference beam, and a *logical* :literal:`nosave` to discard this object from being saved in the mtable. (default: :const:`nil`). Example: :expr:`X0 = { x=1e-3, px=-1e-5 }`. **O0** - A *mappable* specifying initial coordinates :literal:`{x,px,y,py,t,pt}` of the reference orbit around which X0 definitions take place. If it has the attribute :expr:`cofind == true`, it will be used as an initial guess to search for the reference closed orbit. (default: :const:`0` ). + A *mappable* specifying initial coordinates :literal:`{x,px,y,py,t,pt}` of the reference orbit around which X0 definitions take place. If it has the attribute :expr:`cofind == true`, it will be used as an initial guess to search for the reference closed orbit. (default: :const:`nil`). Example: :expr:`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 :literal:`pt` of each tracked particle or damap. (default::const:`nil`). + A *number* (or list of *number*) specifying the initial :math:`\delta_p` to convert (using the beam) and add to the :literal:`pt` of each tracked particle or damap. (default: :const:`nil`). Example: :expr:`s0 = 5000`. **nturn** - A *number* specifying the number of turn to track. (default: :const:`nil`). + A *number* specifying the number of turn to track. (default: :const:`nil`). Example: :expr:`nturn = 2`. -**nstep** - A *number* specifying the number of element to track. A negative value will track all elements. (default: :const:`nil`). - - Example: :expr:`nstep = 1`. - **nslice** - A *number* specifying the number of slices or an *iterable* of increasing relative positions or a *callable* :literal:`(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`). + A *number* specifying the number of slices or an *iterable* of increasing relative positions or a *callable* :literal:`(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: :expr:`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 :const:`true` is equivalent to invoke the *damap* constructor with :literal:`{}` as argument. A value of :const:`false` or :const:`nil` disable the use of damaps and force :var:`cofind` to replace each particles or damaps by seven particles to approximate their Jacobian by finite difference. (default: :const:`true`). + A *logical* or a *damap* specification as defined by the :doc:`DAmap ` module to track DA maps instead of particles coordinates. A value of :const:`true` is equivalent to invoke the *damap* constructor with :literal:`{}` as argument. A value of :const:`false` or :const:`nil` disable the use of damaps and force :var:`cofind` to replace each particles or damaps by seven particles to approximate their Jacobian by finite difference. (default: :const:`true`). Example: :expr:`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 :literal:`simple` (equiv. to :literal:`DKD` order 2), :literal:`collim` (equiv. to :literal:`MKM` order 2), and :literal:`teapot` (Teapot splitting order 2). (default: :const:`nil`). + 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 :literal:`simple` (equiv. to :literal:`DKD` order 2), :literal:`collim` (equiv. to :literal:`MKM` order 2), and :literal:`teapot` (Teapot splitting order 2). (default: :const:`nil`). Example: :expr:`method = 'teapot'`. **model** - A *string* specifying the integration model, either :literal:`'DKD'` for *Drift-Kick-Drift* thin lens integration or :literal:`'TKT'` for *Thick-Kick-Thick* thick lens integration. [#f2]_ (default: :const:`nil`) + A *string* specifying the integration model, either :literal:`'DKD'` for *Drift-Kick-Drift* thin lens integration or :literal:`'TKT'` for *Thick-Kick-Thick* thick lens integration. [#f2]_ (default: :const:`nil`) Example: :expr:`model = 'DKD'`. **ptcmodel** - A *logical* indicating to use strict PTC model. [#f3]_ (default: :const:`nil`) + A *logical* selecting the tracking backend: :const:`nil` keeps the MAD-NG model, :const:`true` selects the strict PTC model, and :const:`false` selects the MAD-X-compatible model. [#f3]_ (default: :const:`nil`) Example: :expr:`ptcmodel = true`. +The attributes :literal:`secnmul`, :literal:`aperture`, :literal:`frngmax`, :literal:`nocavity`, :literal:`cmap`, :literal:`aper` and :literal:`apersel` are forwarded unchanged to the underlying :var:`track` command and therefore keep the same semantics and default handling as in :doc:`track `. + **implicit** - A *logical* indicating that implicit elements must be sliced too, e.g. for smooth plotting. (default: :const:`nil`). + A *logical* indicating that implicit elements must be sliced too, e.g. for smooth plotting. (default: :const:`nil`). Example: :expr:`implicit = true`. **misalign** - A *logical* indicating that misalignment must be considered. (default: :const:`nil`). + A *logical* indicating that misalignment must be considered. (default: :const:`nil`). Example: :expr:`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 :const:`true` is equivalent to the bit mask , i.e. allow all elements (default) fringe fields. (default: :const:`nil`). + 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 :const:`true` is equivalent to the bit mask , i.e. allow all elements (default) fringe fields. (default: :const:`nil`). Example: :expr:`fringe = false`. **radiate** - A *logical* enabling or disabling the radiation or the *string* specifying the :literal:`'average'` type of radiation. The value :const:`true` is equivalent to :literal:`'average'` and the value :literal:`'quantum'` is converted to :literal:`'average'`. (default: :const:`nil`). + A *logical* enabling damping radiation during the closed-orbit iterations. Any truthy value is collapsed to the damping-only tracking mode used internally by :var:`cofind`. (default: :const:`nil`). - Example: :expr:`radiate = 'average'`. + Example: :expr:`radiate = true`. **totalpath** - A *logical* indicating to use the totalpath for the fifth variable :literal:`'t'` instead of the local path. (default: :const:`nil`). + A *logical* indicating to use the totalpath for the fifth variable :literal:`'t'` instead of the local path. (default: :const:`nil`). Example: :expr:`totalpath = true`. **save** - A *logical* specifying to create a *mtable* and record tracking information at the observation points. The :literal:`save` attribute can also be a *string* specifying saving positions in the observed elements: :literal:`"atentry"`, :literal:`"atslice"`, :literal:`"atexit"` (i.e. :const:`true`), :literal:`"atbound"` (i.e. entry and exit), :literal:`"atbody"` (i.e. slices and exit) and :literal:`"atall"`. (default: :const:`false`). + A *logical* specifying to create a *mtable* and record tracking information at the observation points. The :literal:`save` attribute can also be a *string* specifying saving positions in the observed elements: :literal:`"atentry"`, :literal:`"atslice"`, :literal:`"atexit"` (i.e. :const:`true`), :literal:`"atbound"` (i.e. entry and exit), :literal:`"atbody"` (i.e. slices and exit) and :literal:`"atall"`. (default: :const:`false`). Example: :expr:`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 :literal:`seq.name`. (default: :const:`nil`). - - Example: :expr:`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 :literal:`observe`\ :math:`>0` turns. (default: :const:`nil`). + 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 :literal:`observe`\ :math:`>0` turns. (default: :const:`nil`). Example: :expr:`observe = 1`. **savesel** - A *callable* :literal:`(elm, mflw, lw, islc)` acting as a predicate on selected elements for observation, i.e. the element is discarded if the predicate returns :const:`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`) + A *callable* :literal:`(elm, mflw, lw, islc)` acting as a predicate on selected elements for observation, i.e. the element is discarded if the predicate returns :const:`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: :expr:`savesel = \\e -> mylist[e.name] ~= nil`. **savemap** - A *logical* indicating to save the damap in the column :literal:`__map` of the *mtable*. (default: :const:`nil`). + A *logical* indicating to save the damap in the column :literal:`__map` of the *mtable*. (default: :const:`nil`). Example: :expr:`savemap = true`. **atentry** - A *callable* :literal:`(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 :const:`-1`. (default: :const:`nil`). + A *callable* :literal:`(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 :const:`-1`. (default: :const:`nil`). Example: :expr:`atentry = myaction`. **atslice** - A *callable* :literal:`(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`). + A *callable* :literal:`(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: :expr:`atslice = myaction`. -**atexit** - A *callable* :literal:`(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`). +**atexit** + A *callable* :literal:`(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: :expr:`atexit = myaction`. **ataper** - A *callable* :literal:`(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 :expr:`status="lost"` and it is removed from the list of tracked items. (default: :const:`fnil`). + A *callable* :literal:`(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 :expr:`status="lost"` and it is removed from the list of tracked items. (default: :const:`fnil`). Example: :expr:`ataper = myaction`. **atsave** - A *callable* :literal:`(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`). + A *callable* :literal:`(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: :expr:`atsave = myaction`. **atdebug** - A *callable* :literal:`(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. :literal:`"map_name:0"` for entry and :literal:`":1"` for exit. If the level :literal:`debug` :math:`\geq 4` and :literal:`atdebug` is not specified, the default *function* :literal:`mdump` is used. In some cases, extra arguments could be passed to the method. (default: :const:`fnil`). + A *callable* :literal:`(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. :literal:`"map_name:0"` for entry and :literal:`":1"` for exit. If the level :literal:`debug` :math:`\geq 4` and :literal:`atdebug` is not specified, the default *function* :literal:`mdump` is used. In some cases, extra arguments could be passed to the method. (default: :const:`fnil`). Example: :expr:`atdebug = myaction`. -**codiff** - A *number* specifying the finite difference step to approximate the Jacobian when damaps are disabled. If :literal:`codiff` is larger than :math:`100\times`\ :literal:`cotol`, it will be adjusted to :literal:`cotol` :math:`/100` and a warning will be emitted. (default: :const:`1e-8`). +**costp** + A *number* specifying the relative finite-difference scale used to approximate the Jacobian when damaps are disabled. If a tracked object has zero norm, :literal:`cofind` falls back to :literal:`max(costp, cotol)` for that perturbation. (default: :const:`1e-8`). - Example: :expr:`codiff = 1e-10`. + Example: :expr:`costp = 1e-10`. -**coiter** - A *number* specifying the maximum number of iteration. If this threshold is reached, all the remaining tracked objects are tagged as :literal:`"unstable"`. (default: 20). +**coitr** + A *number* specifying the maximum number of iteration. If this threshold is reached, all the remaining tracked objects are tagged as :literal:`"unstable"`. (default: 25). - Example: :expr:`coiter = 5`. + Example: :expr:`coitr = 5`. **cotol** - A *number* specifying the closed orbit tolerance. If all coordinates update of a particle or a damap are smaller than :literal:`cotol`, then it is tagged as :literal:`"stable"`. (default: :const:`1e-8`). + A *number* specifying the closed orbit tolerance. If all coordinates update of a particle or a damap are smaller than :literal:`cotol`, then it is tagged as :literal:`"stable"`. (default: :const:`1e-8`). Example: :expr:`cotol = 1e-6`. -**X1** - A *mappable* specifying the coordinates :literal:`{x,px,y,py,t,pt}` to *subtract* to the final coordinates of the particles or the damaps. (default: :const:`0`). +**O1** + A *mappable* specifying the coordinates :literal:`{x,px,y,py,t,pt}` to *subtract* from the final coordinates of the particles or the damaps. (default: :const:`0`). - Example: :expr:`X1 = { t=100, pt=10 }`. + Example: :expr:`O1 = { t=100, pt=10 }`. **info** - A *number* specifying the information level to control the verbosity of the output on the console. (default: :const:`nil`). + A *number* specifying the information level to control the verbosity of the output on the console. (default: :const:`nil`). Example: :expr:`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`). + 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: :expr:`debug = 2`. **usrdef** - Any user defined data that will be attached to the tracked map flow, which is internally passed to the elements method :literal:`:track` and to their underlying maps. (default: :const:`nil`). + Any user defined data that will be attached to the tracked map flow, which is internally passed to the elements method :literal:`:track` and to their underlying maps. (default: :const:`nil`). Example: :expr:`usrdef = { myvar=somevalue }`. -**mflow** - A *mflow* containing the current state of a :var:`track` command. If a map flow is provided, all attributes are discarded except :literal:`nstep`, :literal:`info` and :literal:`debug`, as the command was already set up upon its creation. (default: :const:`nil`). +**mflow** + A *mflow* containing the current state of a :var:`cofind` command. If a map flow is provided, all setup attributes are ignored and only the volatile fields already stored in the mflow are reused; in practice, :literal:`nstep`, :literal:`info` and :literal:`debug` are the fields refreshed by the command wrapper. (default: :const:`nil`). Example: :expr:`mflow = mflow0`. @@ -260,7 +258,9 @@ The :var:`cofind` command stops when all particles or damap are tagged as :liter A *mtable* corresponding to the TFS table of the :var:`track` command where the :literal:`status` column may also contain the new values :literal:`"stable"`, :literal:`"unstable"` or :literal:`"singular"`. **mflw** - A *mflow* corresponding to the map flow of the :var:`track` command. The particles or damaps :literal:`status` are tagged and ordered by :literal:`"stable"`, :literal:`"unstable"`, :literal:`"singular"`, :literal:`"lost"` and :literal:`id`. + A *mflow* corresponding to the map flow of the :var:`track` command. The particles or damaps :literal:`status` are tagged and ordered by :literal:`"stable"`, :literal:`"unstable"`, :literal:`"singular"`, :literal:`"lost"` and :literal:`id`. Particle-like results also carry the solver metadata fields :literal:`id`, :literal:`status`, :literal:`rank` and :literal:`coitr` in addition to the canonical coordinates :literal:`x`, :literal:`px`, :literal:`y`, :literal:`py`, :literal:`t`, :literal:`pt`. + +The closed-orbit coordinates are converged against :literal:`cotol`. In other words, users should validate the returned orbit against :literal:`cotol` (or a tighter user-specified value), not against machine epsilon. Cofind mtable ------------- @@ -273,6 +273,6 @@ Examples TODO -.. [#f1] Initial coordinates :var:`X0` may override it by providing a beam per particle or damap. +.. [#f1] Initial coordinates :var:`X0` may override it by providing a beam per particle or damap. .. [#f2] The :literal:`TKT` scheme (Yoshida) is automatically converted to the :literal:`MKM` scheme (Boole) when appropriate. .. [#f3] In all cases, MAD-NG uses PTC setup :expr:`time=true, exact=true`. diff --git a/refman/source/mad_cmd_match.rst b/refman/source/mad_cmd_match.rst index 25dcfe5..3694ca9 100644 --- a/refman/source/mad_cmd_match.rst +++ b/refman/source/mad_cmd_match.rst @@ -19,27 +19,28 @@ The :literal:`match` command format is summarized in :numref:`fig-match-synop`. :caption: Synopsis of the :literal:`match` command with default setup. :name: fig-match-synop - status, fmin, ncall = match { - command = function or nil, - variables = { variables-attributes, - { variable-attributes }, - ..., more variable definitions, ... - { variable-attributes } }, - equalities = { constraints-attributes, - { constraint-attributes }, - ..., more equality definitions, ... - { constraint-attributes } }, - inequalities = { constraints-attributes, - { constraint-attributes }, - ..., more inequality definitions,... - { constraint-attributes } }, - weights = { weights-list }, - objective = { objective-attributes }, - maxcall=nil, -- call limit - maxtime=nil, -- time limit - info=nil, -- information level (output on terminal) - debug=nil, -- debug information level (output on terminal) - usrdef=nil, -- user defined data attached to the environment + status, fmin, ncall = match { + command = function or nil, + jacobian = function or nil, + variables = { variables-attributes, + { variable-attributes }, + ..., more variable definitions, ... + { variable-attributes } }, + equalities = { constraints-attributes, + { constraint-attributes }, + ..., more equality definitions, ... + { constraint-attributes } }, + inequalities = { constraints-attributes, + { constraint-attributes }, + ..., more inequality definitions,... + { constraint-attributes } }, + weights = { weights-list }, + objective = { objective-attributes }, + maxcall=nil, -- call limit + maxtime=nil, -- time limit + info=nil, -- information level (output on terminal) + debug=nil, -- debug information level (output on terminal) + usrdef=nil, -- user defined data attached to the environment } @@ -48,32 +49,37 @@ The :literal:`match` command supports the following attributes: .. _match.attr: :ref:`command ` - A *callable* :literal:`(e)` that will be invoked during the optimization process at each iteration. (default: :const:`nil`). + A *callable* :literal:`(e)` that will be invoked during the optimization process at each iteration. (default: :const:`nil`). Example: :expr:`command := twiss { twiss-attributes }`. +**jacobian** + A *callable* :literal:`(cres, fgrd, cjac, e)` that fills the objective gradient and/or the constraints Jacobian explicitly for the current command result :literal:`cres`. When provided, it supersedes the finite-difference Jacobian builder. (default: :const:`nil`). + + Example: :expr:`jacobian = my_jacobian`. + :ref:`variables ` - An *mappable* of single :ref:`variable ` specification that can be combined with a *set* of specifications for all variables. (no default, required). + An *mappable* of single :ref:`variable ` specification that can be combined with a *set* of specifications for all variables. (no default, required). Example: :expr:`variables = {{ var="seq.knobs.mq_k1" }}`. :ref:`equalities ` - An *mappable* of single equality specification that can be combined with a *set* of specifications for all equalities. (default: :literal:`{}`). + An *mappable* of single equality specification that can be combined with a *set* of specifications for all equalities. (default: :literal:`{}`). Example: :expr:`equalities = {{ expr=\\t -> t.q1-64.295, name='q1' }}`. :ref:`inequalities ` - An *mappable* of single inequality specification that can be combined with a *set* of specifications for all inequalities. (default: :literal:`{}`). + An *mappable* of single inequality specification that can be combined with a *set* of specifications for all inequalities. (default: :literal:`{}`). Example: :expr:`inequalities = {{ expr=\\t -> t.mq4.beta11-50 }}`. :ref:`weights ` - A *mappable* of weights specification that can be used in the :literal:`kind` attribute of the constraints specifications. (default: :literal:`{}`). + A *mappable* of weights specification that can be used in the :literal:`kind` attribute of the constraints specifications. (default: :literal:`{}`). Example: :expr:`weights = { px=10 }`. :ref:`objective ` - A *mappable* of specifications for the objective to minimize. (default: :literal:`{}`). + A *mappable* of specifications for the objective to minimize. (default: :literal:`{}`). Example: :expr:`objective = { method="LD_LMDIF", fmin=1e-10 }`. @@ -87,20 +93,20 @@ The :literal:`match` command supports the following attributes: Example: :expr:`maxtime = 60`. -**info** - A *number* specifying the information level to control the verbosity of the output on the :ref:`console `. (default: :const:`nil`). +**info** + A *number* specifying the information level to control the verbosity of the output on the :ref:`console `. (default: :const:`nil`). Example: :expr:`info = 3`. .. _match.debug: -**debug** - A *number* specifying the debug level to perform extra assertions and to control the verbosity of the output on the :ref:`console `. (default: :const:`nil`). +**debug** + A *number* specifying the debug level to perform extra assertions and to control the verbosity of the output on the :ref:`console `. (default: :const:`nil`). Example: :expr:`debug = 2`. -**usrdef** - Any user defined data that will be attached to the matching environment, which is passed as extra argument to all user defined functions in the :literal:`match` command. (default: :const:`nil`). +**usrdef** + Any user defined data that will be attached to the matching environment, which is passed as extra argument to all user defined functions in the :literal:`match` command. (default: :const:`nil`). Example: :expr:`usrdef = { var=vector(15) }`. @@ -119,7 +125,7 @@ The :literal:`match` command returns the following values in this order: .. table:: List of :var:`status` (*string*) returned by the :mod:`match` command. :name: tbl.match.status :align: center - + +---------------+------------------------------------------------------------------------------------------------------+ | :var:`status` | Meaning | +===============+======================================================================================================+ @@ -184,7 +190,7 @@ Command The attribute :literal:`command` (default: :const:`nil`) must be a *callable* :literal:`(e)` that will be invoked with the matching environment as first argument during the optimization, right after the update of the :ref:`variables ` to their new values, and before the evaluation of the :ref:`constraints ` and the :ref:`objective ` function. (default: :const:`nil`). -.. code-block:: +.. code-block:: command = function or nil @@ -211,11 +217,11 @@ Variables The attribute :literal:`variables` (no default, required) defines the variables that the command :literal:`match` will update while trying to minimize the objective function. -.. code-block:: +.. code-block:: - variables = { variables-attributes, - { variable-attributes }, - ... ,more variable definitions, ... + variables = { variables-attributes, + { variable-attributes }, + ... ,more variable definitions, ... { variable-attributes } } The *variable-attributes* is a set of attributes that specify a single variable: @@ -223,52 +229,52 @@ The *variable-attributes* is a set of attributes that specify a single variable: .. _par.match.var: **var** - A *string* specifying the identifier (and indirection) needed to reach the variable from the user's scope where the :literal:`match` command is defined. (default: :const:`nil`). + A *string* specifying the identifier (and indirection) needed to reach the variable from the user's scope where the :literal:`match` command is defined. (default: :const:`nil`). Example: :expr:`var = "lhcb1.mq_12l4_b1.k1"`. **name** - A *string* specifying the name of the variable to display when the :var:`info` level is positive. (default: :literal:`var`). + A *string* specifying the name of the variable to display when the :var:`info` level is positive. (default: :literal:`var`). Example: :expr:`name = "MQ.12L4.B1->k1"`. **min** - A *number* specifying the lower bound for the variable. (default: :literal:`-inf` ). + A *number* specifying the lower bound for the variable. (default: :literal:`-inf` ). Example: :expr:`min = -4`. **max** - A *number* specifying the upper bound for the variable. (default: :literal:`+inf` ). + A *number* specifying the upper bound for the variable. (default: :literal:`+inf` ). Example: :expr:`max = 10`. -**sign** - A *logical* enforcing the sign of the variable by moving :var:`min` or :var:`max` to zero depending on the sign of its initial value. (default: :const:`false`). +**sign** + A *logical* enforcing the sign of the variable by moving :var:`min` or :var:`max` to zero depending on the sign of its initial value. (default: :const:`false`). Example: :expr:`sign = true`. -**slope** - A *number* enforcing (:ref:`LSopt ` methods only) with its sign the variation direction of the variable, i.e. positive will only increase and negative will only decrease. (default: :const:`0` ). +**slope** + A *number* enforcing (:ref:`LSopt ` methods only) with its sign the variation direction of the variable, i.e. positive will only increase and negative will only decrease. (default: :const:`0` ). Example: :expr:`slope = -1`. -**step** - A small positive *number* used to approximate the derivatives using the :ref:`sec.match.der` method. If the value is not provided, the command will use some heuristic. (default: :const:`nil`). +**rstp** + A small positive *number* specifying the relative finite-difference scale used to approximate the derivatives with the :ref:`sec.match.der` method. If the value is not provided, the command will use its built-in heuristic. (default: :const:`nil`). - Example: :expr:`step = 1e-6`. + Example: :expr:`rstp = 1e-6`. -**tol** - A *number* specifying the tolerance on the variable step. If an update is smaller than :literal:`tol`, the command will return the status :literal:`"XTOL"`. (default: :const:`0`). +**tol** + A *number* specifying the tolerance on the variable step. If an update is smaller than :literal:`tol`, the command will return the status :literal:`"XTOL"`. (default: :const:`0`). Example: :expr:`tol = 1e-8`. -**get** - A *callable* :literal:`(e)` returning the variable value as a *number*, optionally using the matching environment passed as first argument. This attribute is required if the variable is *local* or an *upvalue* to avoid a significant slowdown of the code. (default: :const:`nil`). +**get** + A *callable* :literal:`(e)` returning the variable value as a *number*, optionally using the matching environment passed as first argument. This attribute is required if the variable is *local* or an *upvalue* to avoid a significant slowdown of the code. (default: :const:`nil`). Example: :expr:`get := lhcb1.mq_12l4_b1.k1`. -**set** - A *callable* :literal:`(v, e)` updating the variable value with the *number* passed as first argument, optionally using the matching environment passed as second argument.This attribute is required if the variable is *local* or an *upvalue* to avoid a significant slowdown of the code. (default: :const:`nil`). +**set** + A *callable* :literal:`(v, e)` updating the variable value with the *number* passed as first argument, optionally using the matching environment passed as second argument.This attribute is required if the variable is *local* or an *upvalue* to avoid a significant slowdown of the code. (default: :const:`nil`). Example: :expr:`set = \\v,e => lhcb1.mqxa_1l5.k1 = v*e.usrdef.xon end`. @@ -287,34 +293,39 @@ The *variables-attributes* is a set of attributes that specify all variables tog **slope** Idem :ref:`variable-attributes `, but for all variables with no local override. -**step** +**rstp** Idem :ref:`variable-attributes `, but for all variables with no local override. **tol** Idem :ref:`variable-attributes `, but for all variables with no local override. -**rtol** - A *number* specifying the relative tolerance on all variable steps. If an update is smaller than :literal:`rtol` relative to its variable value, the command will return the status :literal:`"XTOL"`\ . (default: :const:`eps`). +**rtol** + A *number* specifying the relative tolerance on all variable steps. If an update is smaller than :literal:`rtol` relative to its variable value, the command will return the status :literal:`"XTOL"`\ . (default: :const:`eps`). Example: :expr:`tol = 1e-8`. +**rmov** + A *number* specifying the relative maximum move allowed on each variable during a single update. (default: :const:`inf`). + + Example: :expr:`rmov = 0.2`. + **nvar** - A *number* specifying the number of variables of the problem. It is useful when the problem is made abstract with functions and it is not possible to deduce this count from single variable definitions, or one needs to override it. (default: :const:`nil`). + A *number* specifying the number of variables of the problem. It is useful when the problem is made abstract with functions and it is not possible to deduce this count from single variable definitions, or one needs to override it. (default: :const:`nil`). Example: :expr:`nvar = 15`. **get** - A *callable* :literal:`(x, e)` updating a *vector* passed as first argument with the values of all variables, optionally using the matching environment passed as second argument. This attribute supersedes all single variable :literal:`get` and may be useful when it is better to read all the variables together, or when they are all *local*\ s or *upvalue*\ s. (default: :const:`nil`). + A *callable* :literal:`(x, e)` updating a *vector* passed as first argument with the values of all variables, optionally using the matching environment passed as second argument. This attribute supersedes all single variable :literal:`get` and may be useful when it is better to read all the variables together, or when they are all *local*\ s or *upvalue*\ s. (default: :const:`nil`). Example: :expr:`get = \\x,e -> e.usrdef.var:copy(x)`. **set** - A *callable* :literal:`(x, e)` updating all the variables with the values passed as first argument in a *vector*, optionally using the matching environment passed as second argument. This attribute supersedes all single variable :literal:`set` and may be useful when it is better to update all the variables together, or when they are all *local*\ s or *upvalue*\ s.(default: :const:`nil`). + A *callable* :literal:`(x, e)` updating all the variables with the values passed as first argument in a *vector*, optionally using the matching environment passed as second argument. This attribute supersedes all single variable :literal:`set` and may be useful when it is better to update all the variables together, or when they are all *local*\ s or *upvalue*\ s.(default: :const:`nil`). Example: :expr:`set = \\x,e -> x:copy(e.usrdef.var)`. **nowarn** - A *logical* disabling a warning emitted when the definition of :literal:`get` and :literal:`set` are advised but not defined. It is safe to not define :literal:`get` and :literal:`set` in such case, but it will significantly slowdown the code. (default: :const:`nil`). + A *logical* disabling a warning emitted when the definition of :literal:`get` and :literal:`set` are advised but not defined. It is safe to not define :literal:`get` and :literal:`set` in such case, but it will significantly slowdown the code. (default: :const:`nil`). Example: :expr:`nowarn = true`. @@ -325,17 +336,17 @@ Constraints The attributes :literal:`equalities` (default: :literal:`{}`) and :literal:`inequalities` (default: :literal:`{}`) define the constraints that the command :literal:`match` will try to satisfy while minimizing the objective function. Equalities and inequalities are considered differently when calculating the :ref:`penalty function `. -.. code-block:: +.. code-block:: equalities = { constraints-attributes, - { constraint-attributes } , - ... more equality definitions ... + { constraint-attributes } , + ... more equality definitions ... { constraint-attributes } }, inequalities = { constraints-attributes, - { constraint-attributes } , - ... more inequality definitions ... + { constraint-attributes } , + ... more inequality definitions ... { constraint-attributes } }, weights = { weights-list }, @@ -344,28 +355,28 @@ The attributes :literal:`equalities` (default: :literal:`{}`) and :literal:`ineq The *constraint-attributes* is a set of attributes that specify a single constraint, either an *equality* or an *inequality*: - **expr** + **expr** A *callable* :literal:`(r, e)` returning the constraint value as a *number*, optionally using the result of :literal:`command` passed as first argument, and the matching environment passed as second argument. (default: :const:`nil`) Example: :expr:`expr = \\t -> t.IP8.beta11-beta_ip8`. **name** - A *string* specifying the name of the constraint to display when the :literal:`info` level is positive. (default: :const:`nil`). + A *string* specifying the name of the constraint to display when the :literal:`info` level is positive. (default: :const:`nil`). Example: :expr:`name = "betx@IP8"`. - **kind** - A *string* specifying the kind to refer to for the weight of the constraint, taken either in the user-defined or in the default :ref:`weights-list`\ . (default: :const:`nil`). + **kind** + A *string* specifying the kind to refer to for the weight of the constraint, taken either in the user-defined or in the default :ref:`weights-list`\ . (default: :const:`nil`). Example: :expr:`kind = "dq1"`. **weight** - A *number* used to override the weight of the constraint. (default: :const:`nil`). + A *number* used to override the weight of the constraint. (default: :const:`nil`). Example: :expr:`weight = 100`. - **tol** - A *number* specifying the tolerance to apply on the constraint when checking for its fulfillment. (default: :const:`1e-8` ). + **tol** + A *number* specifying the tolerance to apply on the constraint when checking for its fulfillment. (default: :const:`1e-8` ). Example: :expr:`tol = 1e-6`. @@ -376,33 +387,33 @@ The *constraints-attributes* is a set of attributes that specify all equalities Idem :ref:`constraint-attributes `, but for all constraints with no local override. **nequ** - A *number* specifying the number of equations (i.e. number of equalities or inequalities) of the problem. It is useful when the problem is made abstract with functions and it is not possible to deduce this count from single constraint definitions, or one needs to override it. (default: :const:`nil`). + A *number* specifying the number of equations (i.e. number of equalities or inequalities) of the problem. It is useful when the problem is made abstract with functions and it is not possible to deduce this count from single constraint definitions, or one needs to override it. (default: :const:`nil`). Example: :expr:`nequ = 15`. **exec** - A *callable* :literal:`(x, c, cjac)` updating a *vector* passed as second argument with the values of all constraints, and updating an optional *matrix* passed as third argument with the Jacobian of all constraints (if not :const:`nil`), using the variables values passed in a *vector* as first argument. This attribute supersedes all constraints :literal:`expr` and may be useful when it is better to update all the constraints together. (default: :const:`nil`). + A *callable* :literal:`(x, c, cjac)` updating a *vector* passed as second argument with the values of all constraints, and updating an optional *matrix* passed as third argument with the Jacobian of all constraints (if not :const:`nil`), using the variables values passed in a *vector* as first argument. This attribute supersedes all constraints :literal:`expr` and may be useful when it is better to update all the constraints together. (default: :const:`nil`). Example: :expr:`exec = myinequ`, where (:literal:`nvar=2` and :literal:`nequ=2`) .. code:: - local function myinequ (x, c, cjac) - c:fill { 8*x[1]^3 - x[2] ; (1 - x[1])^3 - x[2] } - if cjac then -- fill [2x2] matrix if present + local function myinequ (x, c, cjac) + c:fill { 8*x[1]^3 - x[2] ; (1 - x[1])^3 - x[2] } + if cjac then -- fill [2x2] matrix if present cjac:fill { 24*x[1]^2, - 1 ; - 3*(1 - x[1])^2, - 1 } end end \ - **disp** - A *logical* disabling the display of the equalities in the summary if it is explicitly set to :const:`false`. This is useful for fitting data where equalities are used to compute the residuals. (default: :const:`nil`). + **disp** + A *logical* disabling the display of the equalities in the summary if it is explicitly set to :const:`false`. This is useful for fitting data where equalities are used to compute the residuals. (default: :const:`nil`). Example: :expr:`disp = false`. .. _par.match.wght: -The *weights-list* is a set of attributes that specify weights for kinds used by constraints. It allows to override the default weights of the supported kinds summarized in :numref:`tbl.match.wght`, or to extend this list with new kinds and weights. The default weight for any undefined :literal:`kind` is :const:`1`. +The *weights-list* is a set of attributes that specify weights for kinds used by constraints. It allows to override the default weights of the supported kinds summarized in :numref:`tbl.match.wght`, or to extend this list with new kinds and weights. The default weight for any undefined :literal:`kind` is :const:`1`. Example: :expr:`weights = { q1=100, q2=100, mykind=3 }`. .. table:: List of supported kinds (*string*) and their default weights (*number*). @@ -410,39 +421,39 @@ Example: :expr:`weights = { q1=100, q2=100, mykind=3 }`. :align: center +---------------+-------------+-------------+-------------+-------------+-------------+----------------+ - |Name |Weight |Name |Weight |Name |Weight |Generic name | + |Name |Weight |Name |Weight |Name |Weight |Generic name | +===============+=============+=============+=============+=============+=============+================+ - |:var:`x` |:const:`10` |:var:`y` |:const:`10` |:var:`t` |:const:`10` | | + |:var:`x` |:const:`10` |:var:`y` |:const:`10` |:var:`t` |:const:`10` | | +---------------+-------------+-------------+-------------+-------------+-------------+----------------+ - |:var:`px` |:const:`100` |:var:`py` |:const:`100` |:var:`pt` |:const:`100` | | + |:var:`px` |:const:`100` |:var:`py` |:const:`100` |:var:`pt` |:const:`100` | | +---------------+-------------+-------------+-------------+-------------+-------------+----------------+ - |:var:`dx` |:const:`10` |:var:`dy` |:const:`10` |:var:`dt` |:const:`10` |:var:`d` | + |:var:`dx` |:const:`10` |:var:`dy` |:const:`10` |:var:`dt` |:const:`10` |:var:`d` | +---------------+-------------+-------------+-------------+-------------+-------------+----------------+ - |:var:`dpx` |:const:`100` |:var:`dpy` |:const:`100` |:var:`dpt` |:const:`100` |:var:`dp` | + |:var:`dpx` |:const:`100` |:var:`dpy` |:const:`100` |:var:`dpt` |:const:`100` |:var:`dp` | +---------------+-------------+-------------+-------------+-------------+-------------+----------------+ - |:var:`ddx` |:const:`10` |:var:`ddy` |:const:`10` |:var:`ddt` |:const:`10` |:var:`dd` | + |:var:`ddx` |:const:`10` |:var:`ddy` |:const:`10` |:var:`ddt` |:const:`10` |:var:`dd` | +---------------+-------------+-------------+-------------+-------------+-------------+----------------+ - |:var:`ddpx` |:const:`100` |:var:`ddpy` |:const:`100` |:var:`ddpt` |:const:`100` |:var:`ddp` | + |:var:`ddpx` |:const:`100` |:var:`ddpy` |:const:`100` |:var:`ddpt` |:const:`100` |:var:`ddp` | +---------------+-------------+-------------+-------------+-------------+-------------+----------------+ - |:var:`wx` |:const:`1` |:var:`wy` |:const:`1` |:var:`wz` |:const:`1` |:var:`w` | + |:var:`wx` |:const:`1` |:var:`wy` |:const:`1` |:var:`wz` |:const:`1` |:var:`w` | +---------------+-------------+-------------+-------------+-------------+-------------+----------------+ - |:var:`phix` |:const:`1` |:var:`phiy` |:const:`1` |:var:`phiz` |:const:`1` |:var:`phi` | + |:var:`phix` |:const:`1` |:var:`phiy` |:const:`1` |:var:`phiz` |:const:`1` |:var:`phi` | +---------------+-------------+-------------+-------------+-------------+-------------+----------------+ - |:var:`betx` |:const:`1` |:var:`bety` |:const:`1` |:var:`betz` |:const:`1` |:var:`beta` | + |:var:`betx` |:const:`1` |:var:`bety` |:const:`1` |:var:`betz` |:const:`1` |:var:`beta` | +---------------+-------------+-------------+-------------+-------------+-------------+----------------+ - |:var:`alfx` |:const:`10` |:var:`alfy` |:const:`10` |:var:`alfz` |:const:`10` |:var:`alfa` | + |:var:`alfx` |:const:`10` |:var:`alfy` |:const:`10` |:var:`alfz` |:const:`10` |:var:`alfa` | +---------------+-------------+-------------+-------------+-------------+-------------+----------------+ - |:var:`mux` |:const:`10` |:var:`muy` |:const:`10` |:var:`muz` |:const:`10` |:var:`mu` | + |:var:`mux` |:const:`10` |:var:`muy` |:const:`10` |:var:`muz` |:const:`10` |:var:`mu` | +---------------+-------------+-------------+-------------+-------------+-------------+----------------+ - |:var:`beta1` |:const:`1` |:var:`beta2` |:const:`1` |:var:`beta3` |:const:`1` |:var:`beta` | + |:var:`beta1` |:const:`1` |:var:`beta2` |:const:`1` |:var:`beta3` |:const:`1` |:var:`beta` | +---------------+-------------+-------------+-------------+-------------+-------------+----------------+ - |:var:`alfa1` |:const:`10` |:var:`alfa2` |:const:`10` |:var:`alfa3` |:const:`10` |:var:`alfa` | + |:var:`alfa1` |:const:`10` |:var:`alfa2` |:const:`10` |:var:`alfa3` |:const:`10` |:var:`alfa` | +---------------+-------------+-------------+-------------+-------------+-------------+----------------+ - |:var:`mu1` |:const:`10` |:var:`mu2` |:const:`10` |:var:`mu3` |:const:`10` |:var:`mu` | + |:var:`mu1` |:const:`10` |:var:`mu2` |:const:`10` |:var:`mu3` |:const:`10` |:var:`mu` | +---------------+-------------+-------------+-------------+-------------+-------------+----------------+ - |:var:`q1` |:const:`10` |:var:`q2` |:const:`10` |:var:`q3` |:const:`10` |:var:`q` | + |:var:`q1` |:const:`10` |:var:`q2` |:const:`10` |:var:`q3` |:const:`10` |:var:`q` | +---------------+-------------+-------------+-------------+-------------+-------------+----------------+ - |:var:`dq1` |:const:`1` |:var:`dq2` |:const:`1` |:var:`dq3` |:const:`1` |:var:`dq` | + |:var:`dq1` |:const:`1` |:var:`dq2` |:const:`1` |:var:`dq3` |:const:`1` |:var:`dq` | +---------------+-------------+-------------+-------------+-------------+-------------+----------------+ .. _sec.match.obj: @@ -459,54 +470,54 @@ The attribute :literal:`objective` (default: :literal:`{}`) defines the objectiv The *objective-attributes* is a set of attributes that specify the objective to fulfill: - **method** - A *string* specifying the algorithm to use for solving the problem, see :numref:`tbl.match.mthd`, :numref:`tbl.match.lmthd` and :numref:`tbl.match.gmthd`. (default: :literal:`"LN_COBYLA"` if :literal:`objective.exec` is defined, :literal:`"LD_JACOBIAN"` otherwise). + **method** + A *string* specifying the algorithm to use for solving the problem, see :numref:`tbl.match.mthd`, :numref:`tbl.match.lmthd` and :numref:`tbl.match.gmthd`. (default: :literal:`"LN_COBYLA"` if :literal:`objective.exec` is defined, :literal:`"LD_JACOBIAN"` otherwise). Example: :expr:`method = "LD_LMDIF"`. - **submethod** - A *string* specifying the algorithm from NLopt module to use for solving the problem locally when the method is an augmented algorithm, see :numref:`tbl.match.lmthd` and :numref:`tbl.match.gmthd` (default: :literal:`"LN_COBYLA"`). + **submethod** + A *string* specifying the algorithm from NLopt module to use for solving the problem locally when the method is an augmented algorithm, see :numref:`tbl.match.lmthd` and :numref:`tbl.match.gmthd` (default: :literal:`"LN_COBYLA"`). Example: :expr:`method = "AUGLAG", submethod = "LD_SLSQP"`. - **fmin** - A *number* corresponding to the minimum to reach during the optimization. For least squares problems, it corresponds to the tolerance on the :ref:`penalty function `. If an iteration finds a value smaller than :literal:`fmin` and all the constraints are fulfilled, the command will return the status :literal:`"FMIN"` . (default: :const:`nil`). + **fmin** + A *number* corresponding to the minimum to reach during the optimization. For least squares problems, it corresponds to the tolerance on the :ref:`penalty function `. If an iteration finds a value smaller than :literal:`fmin` and all the constraints are fulfilled, the command will return the status :literal:`"FMIN"` . (default: :const:`nil`). Example: :expr:`fmin = 1e-12`. - **tol** - A *number* specifying the tolerance on the objective function step. If an update is smaller than :literal:`tol`, the command will return the status :literal:`"FTOL"`. (default: :const:`0`). + **tol** + A *number* specifying the tolerance on the objective function step. If an update is smaller than :literal:`tol`, the command will return the status :literal:`"FTOL"`. (default: :const:`0`). Example: :expr:`tol = 1e-10`. - **rtol** - A *number* specifying the relative tolerance on the objective function step. If an update is smaller than :literal:`rtol` relative to its step value, the command will return the status :literal:`"FTOL"` (default: :const:`0`). + **rtol** + A *number* specifying the relative tolerance on the objective function step. If an update is smaller than :literal:`rtol` relative to its step value, the command will return the status :literal:`"FTOL"` (default: :const:`0`). Example: :expr:`tol = 1e-8`. - **bstra** - A *number* specifying the strategy to select the *best case* of the :ref:`objective ` function. (default: :const:`nil`). + **bstra** + A *number* specifying the strategy to select the *best case* of the :ref:`objective ` function. (default: :const:`nil`). Example: :expr:`bstra = 0`. [#f3]_ - **broyden** + **broyden** A *logical* allowing the Jacobian approximation by finite difference to update its columns with a *Broyden's rank one* estimates when the step of the corresponding variable is almost collinear with the variables step vector. This option may save some expensive calls to :literal:`command`, e.g. save Twiss calculations, when it does not degrade the rate of convergence of the selected method. (default: :const:`nil`). Example: :expr:`broyden = true`. - **reset** - A *logical* specifying to the :literal:`match` command to restore the initial state of the variables before returning. This is useful to attempt an optimization without changing the state of the variables. Note that if any function amongst :literal:`command`, variables :literal:`get` and :literal:`set`, constraints :literal:`expr` or :literal:`exec`, or objective :literal:`exec` have side effects on the environment, these will be persistent. (default: :const:`nil`). + **reset** + A *logical* specifying to the :literal:`match` command to restore the initial state of the variables before returning. This is useful to attempt an optimization without changing the state of the variables. Note that if any function amongst :literal:`command`, variables :literal:`get` and :literal:`set`, constraints :literal:`expr` or :literal:`exec`, or objective :literal:`exec` have side effects on the environment, these will be persistent. (default: :const:`nil`). Example: :expr:`reset = true`. - **exec** - A *callable* :literal:`(x, fgrd)` returning the value of the objective function as a *number*, and updating a *vector* passed as second argument with its gradient, using the variables values passed in a *vector* as first argument. (default: :const:`nil`). + **exec** + A *callable* :literal:`(x, fgrd)` returning the value of the objective function as a *number*, and updating a *vector* passed as second argument with its gradient, using the variables values passed in a *vector* as first argument. (default: :const:`nil`). Example: :expr:`exec = myfun`, where (:literal:`nvar=2`) - + .. code-block:: - local function myfun(x, fgrd) + local function myfun(x, fgrd) if fgrd then -- fill [2x1] vector if present fgrd:fill { 0, 0.5/sqrt(x[2]) } end @@ -516,8 +527,8 @@ The *objective-attributes* is a set of attributes that specify the objective to \ - **grad** - A *logical* enabling (:const:`true`) or disabling (:const:`false`) the approximation by finite difference of the gradient of the objective function or the Jacobian of the constraints. A :const:`nil` value will be converted to :const:`true` if no :literal:`exec` function is defined and the selected :literal:`method` requires derivatives (:literal:`D`), otherwise it will be converted to :const:`false`. (default: :const:`nil`). + **grad** + A *logical* enabling (:const:`true`) or disabling (:const:`false`) the approximation by finite difference of the gradient of the objective function or the Jacobian of the constraints. A :const:`nil` value will be converted to :const:`true` if no :literal:`exec` function is defined and the selected :literal:`method` requires derivatives (:literal:`D`), otherwise it will be converted to :const:`false`. (default: :const:`nil`). Example: :expr:`grad = false`. @@ -526,35 +537,40 @@ The *objective-attributes* is a set of attributes that specify the objective to Example: :expr:`bisec = 9`. - **rcond** - A *number* specifying ( :ref:`LSopt ` methods only) how to determine the effective rank of the Jacobian while solving the least squares system (see :literal:`ssolve` from the :doc:`Linear Algebra ` module). This attribute can be updated between iterations, e.g. through :literal:`env.objective.rcond`. (default: :literal:`eps` ). + **rcond** + A *number* specifying ( :ref:`LSopt ` methods only) how to determine the effective rank of the Jacobian while solving the least squares system (see :literal:`ssolve` from the :doc:`Linear Algebra ` module). This attribute can be updated between iterations, e.g. through :literal:`env.objective.rcond`. (default: :literal:`eps` ). Example: :expr:`rcond = 1e-14`. + **ncond** + A *number* specifying (:ref:`LSopt ` methods only) how many singular values must be discarded while solving the least-squares system with :literal:`ssolve`. A positive (resp. negative) integer discards the smallest (resp. largest) singular values. This attribute can be updated between iterations, e.g. through :literal:`env.objective.ncond`. (default: :const:`0`). + + Example: :expr:`ncond = 1`. + **jtol** - A *number* specifying (:ref:`LSopt ` methods only) the tolerance on the norm of the Jacobian rows to reject useless constraints. This attribute can be updated between iterations, e.g. through :literal:`env.objective.jtol`. (default: :literal:`eps`). + A *number* specifying (:ref:`LSopt ` methods only) the tolerance on the norm of the Jacobian rows to reject useless constraints. This attribute can be updated between iterations, e.g. through :literal:`env.objective.jtol`. (default: :literal:`eps`). Example: :expr:`tol = 1e-14`. **jiter** - A *number* specifying (:ref:`LSopt ` methods only) the maximum allowed attempts to solve the least squares system when variables are rejected, e.g. wrong slope or out-of-bound values. (default: :const:`10`). + A *number* specifying (:ref:`LSopt ` methods only) the maximum allowed attempts to solve the least squares system when variables are rejected, e.g. wrong slope or out-of-bound values. (default: :const:`10`). Example: :expr:`jiter = 15`. **jstra** - A *number* specifying (:ref:`LSopt ` methods only) the strategy to use for reducing the variables of the least squares system. (default: :const:`1`). + A *number* specifying (:ref:`LSopt ` methods only) the strategy to use for reducing the variables of the least squares system. (default: :const:`1`). Example: :expr:`jstra = 3`. [#f4]_ -======== ========================================================================= -jstra Strategy for reducing variables of least squares system. -======== ========================================================================= -0 no variables reduction, constraints reduction is still active. -1 reduce system variables for bad slopes and out-of-bound values. -2 idem 1, but bad slopes reinitialize variables to their original state. -3 idem 2, but strategy switches definitely to 0 if :literal:`jiter` is reached. -======== ========================================================================= +======== ========================================================================= +jstra Strategy for reducing variables of least squares system. +======== ========================================================================= +0 no variables reduction, constraints reduction is still active. +1 reduce system variables for bad slopes and out-of-bound values. +2 idem 1, but bad slopes reinitialize variables to their original state. +3 idem 2, but strategy switches definitely to 0 if :literal:`jiter` is reached. +======== ========================================================================= .. _sec.match.algo: @@ -584,7 +600,7 @@ and solved for :math:`\nabla_{\vec{h}}\vec{f}=0`. The factor :math:`\alpha>0` is **Quasi-Newton** A variant of the Newton method that uses BFGS approximation of the Hessian :math:`\nabla^2\vec{f}` or its inverse :math:`(\nabla^2\vec{f})^{-1}`, based on values from past iterations. -**Gauss-Newton** +**Gauss-Newton** A variant of the Newton method for *least-squares* problems that uses iteration step given by the minimization :math:`\vec{h}=-\alpha(\nabla\vec{f}^T\nabla\vec{f})^{-1}(\nabla\vec{f}^T\vec{f})`, where the Hessian :math:`\nabla^2\vec{f}` is approximated by :math:`\nabla\vec{f}^T\nabla\vec{f}` with :math:`\nabla\vec{f}` being the Jacobian of the residuals :math:`\vec{f}`. **Levenberg-Marquardt** @@ -605,13 +621,13 @@ Stopping criteria The :literal:`match` command will stop the iteration of the algorithm and return one of the following :literal:`status` if the corresponding criteria, *checked in this order*, is fulfilled (see also :numref:`tbl.match.status`): - :literal:`STOPPED` + :literal:`STOPPED` Check :literal:`env.stop == true`, i.e. termination forced by a user-defined function. :literal:`FMIN` Check :math:`f\leq f_{\min}` if :math:`c_{\text{fail}} = 0` or :literal:`bstra == 0`, where :math:`f` is the current value of the objective function, and :math:`c_{\text{fail}}` is the number of failed constraints (i.e. feasible point). - :literal:`FTOL` + :literal:`FTOL` Check :math:`|\Delta f| \leq f_{\text{tol}}` or :math:`|\Delta f| \leq f_{\text{rtol}}\,|f|` if :math:`c_{\text{fail}} = 0`, where :math:`f` and :math:`\Delta f` are the current value and step of the objective function, and :math:`c_{\text{fail}}` the number of failed constraints (i.e. feasible point). :literal:`XTOL` @@ -664,13 +680,13 @@ The objective function is the key point of the :literal:`match` command, special Derivatives """"""""""" -The derivatives are approximated by the finite difference methods when the selected algorithm requires them (:literal:`D`) and the function :literal:`objective.exec` is undefined or the attribute :literal:`grad=false`. The difficulty of the finite difference methods is to choose the small step :math:`h` for the difference. The :literal:`match` command uses the *forward difference method* with a step :math:`h = 10^{-4}\,\|\vec{h}\|`, where :math:`\vec{h}` is the last :ref:`iteration steps `, unless it is overridden by the user with the variable attribute :literal:`step`. In order to avoid zero step size, which would be problematic for the calculation of the Jacobian, the choice of :math:`h` is a bit more subtle: +The derivatives are approximated by the finite difference methods when the selected algorithm requires them (:literal:`D`) and the function :literal:`objective.exec` is undefined or the attribute :literal:`grad=false`. The difficulty of the finite difference methods is to choose the small step :math:`h` for the difference. The :literal:`match` command uses the *forward difference method* with a step :math:`h = 10^{-4}\,\|\vec{h}\|`, where :math:`\vec{h}` is the last :ref:`iteration steps `, unless it is overridden by the user with the variable attribute :literal:`rstp`. In order to avoid zero step size, which would be problematic for the calculation of the Jacobian, the choice of :math:`h` is a bit more subtle: -.. math:: +.. math:: \frac{\partial f_j}{\partial x_i} \approx \frac{f_j(\vec{x}+h\vec{e_i}) - f_j(\vec{x})}{h}\quad ; \quad - h = + h = \begin{cases} 10^{-4}\,\|\vec{h}\| & \text{if } \|\vec{h}\| \not= 0 \\ 10^{-8}\,\|\vec{x}\| & \text{if } \|\vec{h}\| = 0 \text{ and } \|\vec{x}\| \not= 0 \\ @@ -680,7 +696,7 @@ The derivatives are approximated by the finite difference methods when the selec Hence the approximation of the Jacobian will need an extra evaluation of the objective function per variable. If this evaluation has an heavy cost, e.g. like a :var:`twiss` command, it is possible to approximate the Jacobian evolution by a Broyden's rank-1 update with the :literal:`broyden` attribute: -.. math:: +.. math:: \vec{J}_{k+1} = \vec{J}_{k} + \frac{\vec{f}(\vec{x}_{k}+\vec{h}_k) - \vec{f}(\vec{x}_{k}) - \vec{J}_{k}\,\vec{h}_{k}}{\|\vec{h}_{k}\|^2}\,\vec{h}^T_k The update of the :math:`i`-th column of the Jacobian by the Broyden approximation makes sense if the angle between :math:`\vec{h}` and :math:`\vec{e}_i` is small, that is when :math:`|\vec{h}^T\vec{e}_i| \geq \gamma\,\|\vec{h}\|`. The :literal:`match` command uses a rather pessimistic choice of :math:`\gamma = 0.8`, which gives good performance. Nevertheless, it is advised to always check if Broyden's update saves evaluations of the objective function for your study. @@ -908,7 +924,7 @@ The NLopt (Non-Linear optimization) module provides a simple interface to the al +---------------------------+-----+-----+----------------------------------------------------------------------------------------------------------------------------+ | :var:`GN_MLSL_LDS` | n | n | Idem :var:`GN_MLSL` with low-discrepancy scan sequence. | +---------------------------+-----+-----+----------------------------------------------------------------------------------------------------------------------------+ - | *Global optimizers with derivative* (:var:`GD_`) | + | *Global optimizers with derivative* (:var:`GD_`) | +---------------------------+-----+-----+----------------------------------------------------------------------------------------------------------------------------+ | :var:`GD_MLSL` | n | n | Multi-Level Single-Linkage algorithm (stochastic method). | +---------------------------+-----+-----+----------------------------------------------------------------------------------------------------------------------------+ @@ -926,7 +942,7 @@ The NLopt (Non-Linear optimization) module provides a simple interface to the al +---------------------------+-----+-----+----------------------------------------------------------------------------------------------------------------------------+ | :var:`G_MLSL_LDS` | n | n | Idem :var:`G_MLSL` with low-discrepancy scan sequence. | +---------------------------+-----+-----+----------------------------------------------------------------------------------------------------------------------------+ - + .. _sec.match.xmp: Examples @@ -940,30 +956,30 @@ The following example below shows how to match the betatron tunes of the LHC bea .. code-block:: - local lhcb1 in MADX - local twiss, match in MAD - - local status, fmin, ncall = match { - command := twiss { sequence=lhcb1, cofind=true, - method=4, observe=1 }, - variables = { rtol=1e-6, -- 1 ppm - { var='MADX.kqtf_b1' }, - { var='MADX.kqtd_b1' }}, - equalities = {{ expr=\t -> t.q1- 64.295, name='q1' }, - { expr=\t -> t.q2- 59.301, name='q2' }}, - objective = { fmin=1e-10, broyden=true }, - maxcall=100, info=2 - } - local status, fmin, ncall = match { - command := twiss { sequence=lhcb1, cofind=true, chrom=true, - method=4, observe=1 }, - variables = { rtol=1e-6, -- 1 ppm - { var='MADX.ksf_b1' }, - { var='MADX.ksd_b1' }}, - equalities = {{ expr= \t -> t.dq1-15, name='dq1' }, - { expr= \t -> t.dq2-15, name='dq2' }}, - objective = { fmin=1e-8, broyden=true }, - maxcall=100, info=2 + local lhcb1 in MADX + local twiss, match in MAD + + local status, fmin, ncall = match { + command := twiss { sequence=lhcb1, cofind=true, + method=4, observe=1 }, + variables = { rtol=1e-6, -- 1 ppm + { var='MADX.kqtf_b1' }, + { var='MADX.kqtd_b1' }}, + equalities = {{ expr=\t -> t.q1- 64.295, name='q1' }, + { expr=\t -> t.q2- 59.301, name='q2' }}, + objective = { fmin=1e-10, broyden=true }, + maxcall=100, info=2 + } + local status, fmin, ncall = match { + command := twiss { sequence=lhcb1, cofind=true, chrom=true, + method=4, observe=1 }, + variables = { rtol=1e-6, -- 1 ppm + { var='MADX.ksf_b1' }, + { var='MADX.ksd_b1' }}, + equalities = {{ expr= \t -> t.dq1-15, name='dq1' }, + { expr= \t -> t.dq2-15, name='dq2' }}, + objective = { fmin=1e-8, broyden=true }, + maxcall=100, info=2 } Matching interaction point @@ -973,68 +989,68 @@ The following example hereafter shows how to squeeze the beam 1 of the LHC to :m .. code-block:: - local SS, ES = "S.DS.L8.B1", "E.DS.R8.B1" - lhcb1.range = SS.."/"..ES - for n=1,2 do - beta_ip8 = beta_ip8*0.6 - local status, fmin, ncall = match { - command := twiss { sequence=lhcb1, X0=bir8b1, method=4, observe=1 }, - variables = { sign=true, rtol=1e-8, -- 20 variables - { var='MADX.kq4_l8b1', name='kq4.l8b1', min=-lim2, max=lim2 }, - { var='MADX.kq5_l8b1', name='kq5.l8b1', min=-lim2, max=lim2 }, - { var='MADX.kq6_l8b1', name='kq6.l8b1', min=-lim2, max=lim2 }, - { var='MADX.kq7_l8b1', name='kq7.l8b1', min=-lim2, max=lim2 }, - { var='MADX.kq8_l8b1', name='kq8.l8b1', min=-lim2, max=lim2 }, - { var='MADX.kq9_l8b1', name='kq9.l8b1', min=-lim2, max=lim2 }, - { var='MADX.kq10_l8b1', name='kq10.l8b1', min=-lim2, max=lim2 }, - { var='MADX.kqtl11_l8b1', name='kqtl11.l8b1', min=-lim3, max=lim3 }, - { var='MADX.kqt12_l8b1', name='kqt12.l8b1' , min=-lim3, max=lim3 }, - { var='MADX.kqt13_l8b1', name='kqt13.l8b1', min=-lim3, max=lim3 }, - { var='MADX.kq4_r8b1', name='kq4.r8b1', min=-lim2, max=lim2 }, - { var='MADX.kq5_r8b1', name='kq5.r8b1', min=-lim2, max=lim2 }, - { var='MADX.kq6_r8b1', name='kq6.r8b1', min=-lim2, max=lim2 }, - { var='MADX.kq7_r8b1', name='kq7.r8b1', min=-lim2, max=lim2 }, - { var='MADX.kq8_r8b1', name='kq8.r8b1', min=-lim2, max=lim2 }, - { var='MADX.kq9_r8b1', name='kq9.r8b1', min=-lim2, max=lim2 }, - { var='MADX.kq10_r8b1', name='kq10.r8b1', min=-lim2, max=lim2 }, - { var='MADX.kqtl11_r8b1', name='kqtl11.r8b1', min=-lim3, max=lim3 }, - { var='MADX.kqt12_r8b1', name='kqt12.r8b1', min=-lim3, max=lim3 }, - { var='MADX.kqt13_r8b1', name='kqt13.r8b1', min=-lim3, max=lim3 }, - }, - equalities = { -- 14 equalities - { expr=\t -> t.IP8.beta11-beta_ip8, kind='beta', name='IP8' }, - { expr=\t -> t.IP8.beta22-beta_ip8, kind='beta', name='IP8' }, - { expr=\t -> t.IP8.alfa11, kind='alfa', name='IP8' }, - { expr=\t -> t.IP8.alfa22, kind='alfa', name='IP8' }, - { expr=\t -> t.IP8.dx, kind='dx', name='IP8' }, - { expr=\t -> t.IP8.dpx, kind='dpx', name='IP8' }, - { expr=\t -> t[ES].beta11-eir8b1.beta11, kind='beta', name=ES }, - { expr=\t -> t[ES].beta22-eir8b1.beta22, kind='beta', name=ES }, - { expr=\t -> t[ES].alfa11-eir8b1.alfa11, kind='alfa', name=ES }, - { expr=\t -> t[ES].alfa22-eir8b1.alfa22, kind='alfa', name=ES }, - { expr=\t -> t[ES].dx-eir8b1.dx, kind='dx', name=ES }, - { expr=\t -> t[ES].dpx-eir8b1.dpx, kind='dpx', name=ES }, - { expr=\t -> t[ES].mu1-muxip8, kind='mu1', name=ES }, - { expr=\t -> t[ES].mu2-muyip8, kind='mu2', name=ES }, - }, - objective = { fmin=1e-10, broyden=true }, - maxcall=1000, info=2 - } - MADX.n, MADX.tar = n, fmin - - end + local SS, ES = "S.DS.L8.B1", "E.DS.R8.B1" + lhcb1.range = SS.."/"..ES + for n=1,2 do + beta_ip8 = beta_ip8*0.6 + local status, fmin, ncall = match { + command := twiss { sequence=lhcb1, X0=bir8b1, method=4, observe=1 }, + variables = { sign=true, rtol=1e-8, -- 20 variables + { var='MADX.kq4_l8b1', name='kq4.l8b1', min=-lim2, max=lim2 }, + { var='MADX.kq5_l8b1', name='kq5.l8b1', min=-lim2, max=lim2 }, + { var='MADX.kq6_l8b1', name='kq6.l8b1', min=-lim2, max=lim2 }, + { var='MADX.kq7_l8b1', name='kq7.l8b1', min=-lim2, max=lim2 }, + { var='MADX.kq8_l8b1', name='kq8.l8b1', min=-lim2, max=lim2 }, + { var='MADX.kq9_l8b1', name='kq9.l8b1', min=-lim2, max=lim2 }, + { var='MADX.kq10_l8b1', name='kq10.l8b1', min=-lim2, max=lim2 }, + { var='MADX.kqtl11_l8b1', name='kqtl11.l8b1', min=-lim3, max=lim3 }, + { var='MADX.kqt12_l8b1', name='kqt12.l8b1' , min=-lim3, max=lim3 }, + { var='MADX.kqt13_l8b1', name='kqt13.l8b1', min=-lim3, max=lim3 }, + { var='MADX.kq4_r8b1', name='kq4.r8b1', min=-lim2, max=lim2 }, + { var='MADX.kq5_r8b1', name='kq5.r8b1', min=-lim2, max=lim2 }, + { var='MADX.kq6_r8b1', name='kq6.r8b1', min=-lim2, max=lim2 }, + { var='MADX.kq7_r8b1', name='kq7.r8b1', min=-lim2, max=lim2 }, + { var='MADX.kq8_r8b1', name='kq8.r8b1', min=-lim2, max=lim2 }, + { var='MADX.kq9_r8b1', name='kq9.r8b1', min=-lim2, max=lim2 }, + { var='MADX.kq10_r8b1', name='kq10.r8b1', min=-lim2, max=lim2 }, + { var='MADX.kqtl11_r8b1', name='kqtl11.r8b1', min=-lim3, max=lim3 }, + { var='MADX.kqt12_r8b1', name='kqt12.r8b1', min=-lim3, max=lim3 }, + { var='MADX.kqt13_r8b1', name='kqt13.r8b1', min=-lim3, max=lim3 }, + }, + equalities = { -- 14 equalities + { expr=\t -> t.IP8.beta11-beta_ip8, kind='beta', name='IP8' }, + { expr=\t -> t.IP8.beta22-beta_ip8, kind='beta', name='IP8' }, + { expr=\t -> t.IP8.alfa11, kind='alfa', name='IP8' }, + { expr=\t -> t.IP8.alfa22, kind='alfa', name='IP8' }, + { expr=\t -> t.IP8.dx, kind='dx', name='IP8' }, + { expr=\t -> t.IP8.dpx, kind='dpx', name='IP8' }, + { expr=\t -> t[ES].beta11-eir8b1.beta11, kind='beta', name=ES }, + { expr=\t -> t[ES].beta22-eir8b1.beta22, kind='beta', name=ES }, + { expr=\t -> t[ES].alfa11-eir8b1.alfa11, kind='alfa', name=ES }, + { expr=\t -> t[ES].alfa22-eir8b1.alfa22, kind='alfa', name=ES }, + { expr=\t -> t[ES].dx-eir8b1.dx, kind='dx', name=ES }, + { expr=\t -> t[ES].dpx-eir8b1.dpx, kind='dpx', name=ES }, + { expr=\t -> t[ES].mu1-muxip8, kind='mu1', name=ES }, + { expr=\t -> t[ES].mu2-muyip8, kind='mu2', name=ES }, + }, + objective = { fmin=1e-10, broyden=true }, + maxcall=1000, info=2 + } + MADX.n, MADX.tar = n, fmin + + end Fitting data """""""""""" The following example shows how to fit data with a non-linear model using the least squares methods. The "measurements" are generated by the data function: -.. math:: +.. math:: d(x) = a \sin(x f_1) \cos(x f_2), \quad \text{with} \quad a=5, f1=3, f2=7, \text{ and } x\in[0,\pi). -The least squares minimization is performed by the small code below starting from the arbitrary values :math:`a=1`, :math:`f_1=1`, and :math:`f_2=1`. The :literal:`'LD_JACOBIAN'` +The least squares minimization is performed by the small code below starting from the arbitrary values :math:`a=1`, :math:`f_1=1`, and :math:`f_2=1`. The :literal:`'LD_JACOBIAN'` methods finds the values :math:`a=5\pm 10^{-10}`, :math:`f_1=3\pm 10^{-11}`, and :math:`f_2=7\pm 10^{-11}` in :math:`2574` iterations and :math:`0.1`\,s. The :literal:`'LD_LMDIF'` method finds similar values in :math:`2539` iterations. The data and the model are plotted in the :numref:`fig.match.fit`. .. _fig.match.fit: @@ -1042,23 +1058,23 @@ methods finds the values :math:`a=5\pm 10^{-10}`, :math:`f_1=3\pm 10^{-11}`, and .. figure:: fig/match-fitjac.png :align: center :width: 90% - + Fitting data using the Jacobian or Levenberg-Marquardt methods.} - -.. code-block:: - - local n, k, a, f1, f2 = 1000, pi/1000, 5, 3, 7 - local d = vector(n):seq():map \i -> a*sin(i*k*f1)*cos(i*k*f2) -- data - if noise then d=d:map \x -> x+randtn(noise) end -- add noise if any - local m, p = vector(n), { a=1, f1=1, f2=1 } -- model parameters - local status, fmin, ncall = match { - command := m:seq():map \i -> p.a*sin(i*k*p.f1)*cos(i*k*p.f2), - variables = { { var='p.a' }, - { var='p.f1' }, - { var='p.f2' }, min=1, max=10 }, - equalities = { { expr=\m -> ((d-m):norm()) } }, - objective = { fmin=1e-9, bisec=noise and 5 }, - maxcall=3000, info=1 + +.. code-block:: + + local n, k, a, f1, f2 = 1000, pi/1000, 5, 3, 7 + local d = vector(n):seq():map \i -> a*sin(i*k*f1)*cos(i*k*f2) -- data + if noise then d=d:map \x -> x+randtn(noise) end -- add noise if any + local m, p = vector(n), { a=1, f1=1, f2=1 } -- model parameters + local status, fmin, ncall = match { + command := m:seq():map \i -> p.a*sin(i*k*p.f1)*cos(i*k*p.f2), + variables = { { var='p.a' }, + { var='p.f1' }, + { var='p.f2' }, min=1, max=10 }, + equalities = { { expr=\m -> ((d-m):norm()) } }, + objective = { fmin=1e-9, bisec=noise and 5 }, + maxcall=3000, info=1 } The same least squares minimization can be achieved on noisy data by adding a gaussian RNG truncated at :math:`2\sigma` to the data generator, i.e.:literal:`noise=2`, and by increasing the attribute :literal:`bisec=5`. Of course, the penalty tolerance :literal:`fmin` must be moved to variables tolerance :literal:`tol` or :literal:`rtol`. @@ -1069,10 +1085,10 @@ The :literal:`'LD_JACOBIAN'` methods finds the values :math:`a=4.98470, f_1=3.00 .. figure:: fig/match-fitjacnoise.png :align: center :width: 90% - + Fitting data with noise using Jacobian or Levenberg-Marquardt methods. - - + + Fitting data with derivatives """"""""""""""""""""""""""""" @@ -1086,33 +1102,33 @@ The following example shows how to fit data with a non-linear model and its deri Fitting data with derivatives using the Jacobian or Levenberg-Marquardt methods. -.. code-block:: - - local x = vector{0.038, 0.194, 0.425, 0.626 , 1.253 , 2.500 , 3.740 } - local y = vector{0.050, 0.127, 0.094, 0.2122, 0.2729, 0.2665, 0.3317} - local p = { v=0.9, k=0.2 } - local n = #x - local function eqfun (_, r, jac) - local v, k in p - for i=1,n do - r[i] = y[i] - v*x[i]/(k+x[i]) - jac[2*i-1] = -x[i]/(k+x[i]) - jac[2*i] = v*x[i]/(k+x[i])^2 - end - end - local status, fmin, ncall = match { - variables = { tol=5e-3, min=0.1, max=2, - { var='p.v' }, - { var='p.k' } }, - equalities = { nequ=n, exec=eqfun, disp=false }, - maxcall=20 +.. code-block:: + + local x = vector{0.038, 0.194, 0.425, 0.626 , 1.253 , 2.500 , 3.740 } + local y = vector{0.050, 0.127, 0.094, 0.2122, 0.2729, 0.2665, 0.3317} + local p = { v=0.9, k=0.2 } + local n = #x + local function eqfun (_, r, jac) + local v, k in p + for i=1,n do + r[i] = y[i] - v*x[i]/(k+x[i]) + jac[2*i-1] = -x[i]/(k+x[i]) + jac[2*i] = v*x[i]/(k+x[i])^2 + end + end + local status, fmin, ncall = match { + variables = { tol=5e-3, min=0.1, max=2, + { var='p.v' }, + { var='p.k' } }, + equalities = { nequ=n, exec=eqfun, disp=false }, + maxcall=20 Minimizing function """"""""""""""""""" The following example [#f6]_ hereafter shows how to find the minimum of the function: -.. math:: +.. math:: \min_{\vec{x}\in\mathbb{R}^2} \sqrt{x_2}, \quad \text{subject to the constraints} \quad \begin{cases} @@ -1123,24 +1139,24 @@ The following example [#f6]_ hereafter shows how to find the minimum of the func for the parameters :math:`a_1=2, b_1=0, a_2=-1` and :math:`b_2=1`. The minimum of the function is :math:`f_{\min} = \sqrt{\frac{8}{27}}` at the point :math:`\vec{x} = (\frac{1}{3}, \frac{8}{27})`, and found by the method :literal:`LD_MMA` in 11 evaluations for a relative tolerance of :math:`10^{-4}` on the variables, starting at the arbitrary point :math:`\vec{x}_0=(1.234, 5.678)`. -.. code-block:: - - local function testFuncFn (x, grd) - if grd then x:fill{ 0, 0.5/sqrt(x[2]) } end - return sqrt(x[2]) - end - local function testFuncLe (x, r, jac) - if jac then jac:fill{ 24*x[1]^2, -1, -3*(1-x[1])^2, -1 } end - r:fill{ 8*x[1]^3-x[2], (1-x[1])^3-x[2] } - end - local x = vector{1.234, 5.678} -- start point - local status, fmin, ncall = match { - variables = { rtol=1e-4, - { var='x[1]', min=-inf }, - { var='x[2]', min=0 } }, - inequalities = { exec=testFuncLe, nequ=2, tol=1e-8 }, - objective = { exec=testFuncFn, method='LD_MMA' }, - maxcall=100, info=2 +.. code-block:: + + local function testFuncFn (x, grd) + if grd then x:fill{ 0, 0.5/sqrt(x[2]) } end + return sqrt(x[2]) + end + local function testFuncLe (x, r, jac) + if jac then jac:fill{ 24*x[1]^2, -1, -3*(1-x[1])^2, -1 } end + r:fill{ 8*x[1]^3-x[2], (1-x[1])^3-x[2] } + end + local x = vector{1.234, 5.678} -- start point + local status, fmin, ncall = match { + variables = { rtol=1e-4, + { var='x[1]', min=-inf }, + { var='x[2]', min=0 } }, + inequalities = { exec=testFuncLe, nequ=2, tol=1e-8 }, + objective = { exec=testFuncFn, method='LD_MMA' }, + maxcall=100, info=2 } @@ -1148,8 +1164,8 @@ This example can also be solved with least squares methods, where the :literal:` .. [#f1] Here, the function (i.e. the deferred expression) ignores the matching environment passed as first argument. -.. [#f2] The function :literal:`mchklost` is provided by the :doc:`GPhys module. ` +.. [#f2] The function :literal:`mchklost` is provided by the :doc:`GPhys module. ` .. [#f3] MAD-X matching corresponds to :literal:`bstra=0`. .. [#f4] MAD-X :literal:`JACOBIAN` with :literal:`strategy=3` corresponds to :literal:`jstra=3`. .. [#f5] The `LSopt `_ module sets the values of valid inequalities to zero, i.e. :math:`\vec{c}^{\leq} = 0` if :math:`\vec{c}^{\leq} \leq\vec{c}^{\leq}_{\text{tol}}`. -.. [#f6] This example is taken from the NLopt `documentation `_. \ No newline at end of file +.. [#f6] This example is taken from the NLopt `documentation `_. diff --git a/refman/source/mad_cmd_track.rst b/refman/source/mad_cmd_track.rst index fc03456..96028fa 100644 --- a/refman/source/mad_cmd_track.rst +++ b/refman/source/mad_cmd_track.rst @@ -17,31 +17,42 @@ The :var:`track` command provides a simple interface to the *dynamic* tracking c s0=0, -- initial s-position offset [m] X0=0, -- initial coordinates (or damap(s), or beta block(s)) O0=0, -- initial coordinates of reference orbit - deltap=nil, -- initial deltap(s) + deltap=0, -- initial deltap(s) nturn=1, -- number of turns to track nstep=-1, -- number of elements to track nslice=1, -- number of slices (or weights) for each element - mapdef=false, -- setup for damap (or list of, true => {}) - method=2, -- method or order for integration (1 to 8) + method=4, -- method or order for integration (1 to 8) model='TKT', -- model for integration ('DKD' or 'TKT') - ptcmodel=nil, -- use strict PTC thick model (override option) + mapdef=false, -- setup for damap (or list of, true => {}) + secnmul=false, -- curved-multipole expansion for sbends implicit=false, -- slice implicit elements too (e.g. plots) misalign=false, -- consider misalignments aperture=false, -- default aperture fringe=true, -- enable fringe fields (see element.flags.fringe) + frngmax=2, -- maximum multipole fringe field order radiate=false, -- radiate at slices + taper=false, -- tapering compensation + nocavity=false, -- disable rfcavities totalpath=false, -- variable 't' is the totalpath + cmap=true, -- use C/C++ maps when available + ptcmodel=nil, -- nil=MADNG, true=PTC, false=MADX save=true, -- create mtable and save results - title=nil, -- title of mtable (default seq.name) + aper=true, -- check for aperture observe=1, -- save only in observed elements (every n turns) + reserve=0, -- preallocate output rows (0 => guess) savesel=fnil, -- save selector (predicate) savemap=false, -- save damap in the column __map atentry=fnil, -- action called when entering an element atslice=fnil, -- action called after each element slices atexit=fnil, -- action called when exiting an element - ataper=fnil, -- action called when checking for aperture atsave=fnil, -- action called when saving in mtable + ataper=fnil, -- action called when checking for aperture atdebug=fnil, -- action called when debugging the element maps + apersel=fnil, -- aperture selector (predicate) + coitr=nil, -- closed-orbit iteration limit + cotol=nil, -- closed-orbit tolerance + costp=nil, -- finite-difference scale for closed-orbit Jacobian + O1=nil, -- optional final closed-orbit 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 @@ -53,193 +64,248 @@ The :var:`track` command provides a simple interface to the *dynamic* tracking c Command synopsis ---------------- -| The :var:`track` command format is summarized in :numref:`fig-track-synop`, including the default setup of the attributes. +| The :var:`track` command format is summarized in :numref:`fig-track-synop`, including the default setup of the attributes. | The :var:`track` command supports the following attributes: **sequence** - The *sequence* to track. (no default, required). + The *sequence* to track. (no default, required). Example: :expr:`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 :literal:`seq.beam`. [#f2]_ (default: :const:`nil`). +**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 :literal:`seq.beam`. [#f2]_ (default: :const:`nil`). Example: :expr:`beam = beam 'lhcbeam' { ... }` where ... are the *beam-attributes*. -**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 :attr:`seq.range`. (default: :const:`nil`). +**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 :attr:`seq.range`. (default: :const:`nil`). Example: :expr:`range = "S.DS.L8.B1/E.DS.R8.B1"`. **dir** - The :math:`s`-direction of the tracking: :const:`1` forward, :const:`-1` backward. (default: 1). + The :math:`s`-direction of the tracking: :const:`1` forward, :const:`-1` backward. (default: 1). Example: :expr:`dir = -1`. -**s0** - A *number* specifying the initial :math:`s`-position offset. (default: :math:`0` [m]). +**s0** + A *number* specifying the initial :math:`s`-position offset. (default: :math:`0` [m]). Example: :expr:`s0 = 5000`. -**X0** - A *mappable* (or a list of *mappable*) specifying initial coordinates :literal:`{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 :literal:`mapdef` is specified, but both will use :literal:`mapdef` to setup the damap constructor. Each tracked object may also contain a :var:`beam` to override the reference beam, and a *logical* :literal:`nosave` to discard this object from being saved in the mtable. (default: 0). +**X0** + A *mappable* (or a list of *mappable*) specifying initial coordinates :literal:`{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 :literal:`mapdef` is specified, but both will use :literal:`mapdef` to setup the damap constructor. Each tracked object may also contain a :var:`beam` to override the reference beam, and a *logical* :literal:`nosave` to discard this object from being saved in the mtable. (default: 0). Example: :expr:`X0 = { x=1e-3, px=-1e-5 }`. **O0** - A *mappable* specifying initial coordinates :literal:`{x,px,y,py,t,pt}` of the reference orbit around which X0 definitions take place. If it has the attribute :expr:`cofind == true`, it will be used as an initial guess to search for the reference closed orbit. (default: 0). + A *mappable* specifying initial coordinates :literal:`{x,px,y,py,t,pt}` of the reference orbit around which X0 definitions take place. If it has the attribute :expr:`cofind == true`, it will be used as an initial guess to search for the reference closed orbit. (default: 0). Example: :expr:`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 :literal:`pt` of each tracked particle or damap. (default: :const:`nil`). + A *number* (or list of *number*) specifying the initial :math:`\delta_p` to convert (using the beam) and add to the :literal:`pt` of each tracked particle or damap. (default: :const:`0`). Example: :expr:`s0 = 5000`. **nturn** - A *number* specifying the number of turn to track. (default: 1). + A *number* specifying the number of turn to track. (default: 1). Example: :expr:`nturn = 2`. **nstep** - A *number* specifying the number of element to track. A negative value will track all elements. (default: -1). + A *number* specifying the number of element to track. A negative value will track all elements. (default: -1). Example: :expr:`nstep = 1`. -**nslice** - A *number* specifying the number of slices or an *iterable* of increasing relative positions or a *callable* :literal:`(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: 1). +**nslice** + A *number* specifying the number of slices or an *iterable* of increasing relative positions or a *callable* :literal:`(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: 1). Example: :expr:`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 :const:`true` is equivalent to invoke the *damap* constructor with :literal:`{}` as argument. This attribute allows to track DA maps instead of particles. (default: :const:`nil`). +**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 :const:`true` is equivalent to invoke the *damap* constructor with :literal:`{}` as argument. (default: :const:`false`). Example: :expr:`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 :literal:`simple` (equiv. to :literal:`DKD` order 2), :literal:`collim` (equiv. to :literal:`MKM` order 2), and :literal:`teapot` (Teapot splitting order 2). (default: 2). +**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 :literal:`simple` (equiv. to :literal:`DKD` order 2), :literal:`collim` (equiv. to :literal:`MKM` order 2), and :literal:`teapot` (Teapot splitting order 2). (default: 4). Example: :expr:`method = 'teapot'`. -**model** - A *string* specifying the integration model, either :literal:`'DKD'` for *Drift-Kick-Drift* thin lens integration or :literal:`'TKT'` for *Thick-Kick-Thick* thick lens integration. [#f3]_ (default: :literal:`'TKT'`) +**model** + A *string* specifying the integration model, either :literal:`'DKD'` for *Drift-Kick-Drift* thin lens integration or :literal:`'TKT'` for *Thick-Kick-Thick* thick lens integration. [#f3]_ (default: :literal:`'TKT'`) Example: :expr:`model = 'DKD'`. -**ptcmodel** - A *logical* indicating to use strict PTC model. [#f7]_ (default: :const:`nil`) +**secnmul** + A *logical* or a non-negative *number* controlling the curved-multipole expansion used for SBEND thick maps. A false value disables the extra curved-multipole terms. (default: :const:`false`). + + Example: :expr:`secnmul = 6`. + +**ptcmodel** + A *logical* selecting the tracking backend: :const:`nil` keeps the MAD-NG model, :const:`true` selects the strict PTC model, and :const:`false` selects the MAD-X-compatible model. [#f7]_ (default: :const:`nil`) Example: :expr:`ptcmodel = true`. **implicit** - A *logical* indicating that implicit elements must be sliced too, e.g. for smooth plotting. (default: :const:`false`). + A *logical* indicating that implicit elements must be sliced too, e.g. for smooth plotting. (default: :const:`false`). Example: :expr:`implicit = true`. **misalign** - A *logical* indicating that misalignment must be considered. (default: :const:`false`). + A *logical* indicating that misalignment must be considered. (default: :const:`false`). Example: :expr:`misalign = true`. **aperture** - A *mappable* specifying the default aperture to consider when it's missing at element level, e.g. in implicit drift. See also sequence default aperture. (default: :expr:`{kind='circle', 1}`). + A *mappable* specifying the default aperture to consider when it is missing at element level, e.g. in implicit drift. A false value lets :var:`track` fall back to :literal:`sequence.aperture` or, if absent, to :expr:`{kind='circle', 1}`. (default: :const:`false`). Example: :expr:`aperture = {kind='square', 10}`. **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 :const:`true` is equivalent to the bit mask , i.e. allow all elements (default) fringe fields. (default: :const:`true`). + 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 :const:`true` is equivalent to the bit mask , i.e. allow all elements (default) fringe fields. (default: :const:`true`). Example: :expr:`fringe = false`. +**frngmax** + A non-negative *number* specifying the maximum multipole order used for fringe-field expansions. (default: :const:`2`). + + Example: :expr:`frngmax = 4`. + **radiate** - A *logical* enabling or disabling the radiation or a *string* specifying the type of radiation: :literal:`'average'` or :literal:`'quantum'`. The value :const:`true` is equivalent to :literal:`'average'`. The value :literal:`'quantum+photon'` enables the tracking of emitted photons. (default: :const:`false`). + A *logical* enabling radiation, or a *string* selecting the radiation mode :literal:`'damping'`, :literal:`'quantum'` or :literal:`'photon'`. A trailing :literal:`'+'` keeps the corresponding bookkeeping enabled, e.g. :literal:`'damping+'` or :literal:`'quantum+'`. The value :const:`true` is equivalent to damping radiation. (default: :const:`false`). Example: :expr:`radiate = 'quantum'`. -**totalpath** - A *logical* indicating to use the totalpath for the fifth variable :literal:`'t'` instead of the local path. (default: :const:`false`). +**taper** + A *logical* or a positive *number* enabling tapering compensation. The value :const:`true` is converted to :literal:`3`, i.e. tapering is applied during the first three passes tracked by the map flow. Any positive number limits the compensation to that many passes. (default: :const:`false`). + + Example: :expr:`taper = true`. + +**nocavity** + A *logical* disabling RF cavities and therefore enforcing 5D tracking. (default: :const:`false`). + + Example: :expr:`nocavity = true`. + +**totalpath** + A *logical* indicating to use the totalpath for the fifth variable :literal:`'t'` instead of the local path. (default: :const:`false`). Example: :expr:`totalpath = true`. -**save** - A *logical* specifying to create a *mtable* and record tracking information at the observation points. The :literal:`save` attribute can also be a *string* specifying saving positions in the observed elements: :literal:`"atentry"`, :literal:`"atslice"`, :literal:`"atexit"` (i.e. :const:`true`), :literal:`"atbound"` (i.e. entry and exit), :literal:`"atbody"` (i.e. slices and exit) and :literal:`"atall"`. (default: :const:`true`). +**cmap** + A *logical* indicating whether the C/C++ map implementations should be used when available. (default: :const:`true`). + + Example: :expr:`cmap = false`. + +**save** + A *logical* specifying to create a *mtable* and record tracking information at the observation points. The :literal:`save` attribute can also be a *string* specifying saving positions in the observed elements: :literal:`"atentry"`, :literal:`"atslice"`, :literal:`"atexit"` (i.e. :const:`true`), :literal:`"atbound"` (i.e. entry and exit), :literal:`"atbody"` (i.e. slices and exit) and :literal:`"atall"`. (default: :const:`true`). Example: :expr:`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 :literal:`seq.name`. (default: :const:`nil`). +**aper** + A *logical* or a *string* enabling the default aperture check attached to :literal:`ataper`. The value :const:`true` applies the check at the last slice. A *string* can be used to select the checking positions with the same directives as :literal:`save`, i.e. :literal:`"atentry"`, :literal:`"atslice"`, :literal:`"atexit"`, :literal:`"atbound"`, :literal:`"atbody"` or :literal:`"atall"`. (default: :const:`true`). - Example: :expr:`title = "track around IP5"`. + Example: :expr:`aper = false`. -**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 :literal:`observe` :math:`>0` turns. (default: :const:`1` ). +**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 :literal:`observe` :math:`>0` turns. (default: :const:`1` ). Example: :expr:`observe = 1`. +**reserve** + A non-negative *number* used to preallocate the number of output rows in the produced *mtable*. A value of :const:`0` keeps the built-in size estimate. (default: :const:`0`). + + Example: :expr:`reserve = 50000`. + **savesel** - A *callable* :literal:`(elm, mflw, lw, islc)` acting as a predicate on selected elements for observation, i.e. the element is discarded if the predicate returns :const:`false`. The arguments are in order, the current element, the tracked map flow, the length weight of the slice and the slice index. (default: :literal:`fnil`) + A *callable* :literal:`(elm, mflw, lw, islc)` acting as a predicate on selected elements for observation, i.e. the element is discarded if the predicate returns :const:`false`. The arguments are in order, the current element, the tracked map flow, the length weight of the slice and the slice index. (default: :literal:`fnil`) Example: :expr:`savesel = \\e -> mylist[e.name] ~= nil`. -**savemap** - A *logical* indicating to save the damap in the column :literal:`__map` of the *mtable*. (default: :const:`false`). +**savemap** + A *logical* indicating to save the damap in the column :literal:`__map` of the *mtable*. (default: :const:`false`). Example: :expr:`savemap = true`. -**atentry** - A *callable* :literal:`(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 . (default: :literal:`fnil`). +**atentry** + A *callable* :literal:`(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 . (default: :literal:`fnil`). Example: :expr:`atentry = myaction`. -**atslice** - A *callable* :literal:`(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: :literal:`fnil`). +**atslice** + A *callable* :literal:`(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: :literal:`fnil`). Example: :expr:`atslice = myaction`. -**atexit** - A *callable* :literal:`(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: :literal:`fnil`). +**atexit** + A *callable* :literal:`(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: :literal:`fnil`). Example: :expr:`atexit = myaction`. -**ataper** - A *callable* :literal:`(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 :literal:`status = "lost"` and it is removed from the list of tracked items. (default: :literal:`fnil`). +**ataper** + A *callable* :literal:`(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 :literal:`status = "lost"` and it is removed from the list of tracked items. (default: :literal:`fnil`). Example: :expr:`ataper = myaction`. -**atsave** - A *callable* :literal:`(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: :literal:`fnil`). +**atsave** + A *callable* :literal:`(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: :literal:`fnil`). Example: :expr:`atsave = myaction`. -**atdebug** - A *callable* :literal:`(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. :literal:`"map_name:0"` for entry and :literal:`":1"` for exit. If the level :literal:`debug` :math:`\geq 4` and :literal:`atdebug` is not specified, the default *function* :literal:`mdump` is used. In some cases, extra arguments could be passed to the method. (default: :literal:`fnil`). +**atdebug** + A *callable* :literal:`(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. :literal:`"map_name:0"` for entry and :literal:`":1"` for exit. If the level :literal:`debug` :math:`\geq 4` and :literal:`atdebug` is not specified, the default *function* :literal:`mdump` is used. In some cases, extra arguments could be passed to the method. (default: :literal:`fnil`). Example: :expr:`atdebug = myaction`. +**apersel** + A *callable* :literal:`(elm, mflw, lw, islc)` acting as a predicate on aperture-check positions. If it returns :const:`false`, the default aperture action is skipped for that location. (default: :literal:`fnil`). + + Example: :expr:`apersel = \\e -> e.kind ~= "marker"`. + +**coitr** + A *number* specifying the maximum number of closed-orbit iterations when the map flow requests a closed-orbit search. (default: :const:`nil` and inherited from the closed-orbit helper). + + Example: :expr:`coitr = 25`. + +**cotol** + A *number* specifying the closed-orbit tolerance used when the map flow requests a closed-orbit search. (default: :const:`nil` and inherited from the closed-orbit helper). + + Example: :expr:`cotol = 1e-8`. + +**costp** + A *number* specifying the relative finite-difference scale used for the closed-orbit Jacobian when a closed-orbit search is requested. (default: :const:`nil` and inherited from the closed-orbit helper). + + Example: :expr:`costp = 1e-8`. + +**O1** + A *mappable* specifying the coordinates :literal:`{x,px,y,py,t,pt}` to subtract from the final closed-orbit coordinates when the closed-orbit helper is used. (default: :const:`nil`). + + Example: :expr:`O1 = { 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: :expr:`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`). + 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: :expr:`debug = 2`. -**usrdef** - Any user defined data that will be attached to the tracked map flow, which is internally passed to the elements method :meth:`:track` and to their underlying maps. (default: :const:`nil`). +**usrdef** + Any user defined data that will be attached to the tracked map flow, which is internally passed to the elements method :meth:`:track` and to their underlying maps. (default: :const:`nil`). Example: :expr:`usrdef = { myvar=somevalue }`. -**mflow** - An *mflow* containing the current state of a :var:`track` command. If a map flow is provided, all attributes are discarded except :literal:`nstep`, :literal:`info` and :literal:`debug`, as the command was already set up upon its creation. (default: :const:`nil`). +**mflow** + An *mflow* containing the current state of a :var:`track` command. If a map flow is provided, the setup stored in the mflow is reused; in practice, only the volatile fields :literal:`nstep`, :literal:`info` and :literal:`debug` are refreshed by the command wrapper. (default: :const:`nil`). Example: :expr:`mflow = mflow0`. The :var:`track` command returns the following objects in this order: -**mtbl** +**mtbl** An *mtable* corresponding to the TFS table of the :var:`track` command. **mflw** @@ -253,7 +319,7 @@ Track mtable ------------ .. _sec.track.mtable: -The :var:`track` command returns a *mtable* where the information described hereafter is the default list of fields written to the TFS files. [#f4]_ +The :var:`track` command returns a *mtable* where the information described hereafter is the default list of fields written to the TFS files. [#f4]_ The header of the *mtable* contains the fields in the default order: @@ -261,8 +327,6 @@ The header of the *mtable* contains the fields in the default order: The name of the command that created the *mtable*, e.g. :literal:`"track"`. **type** The type of the *mtable*, i.e. :literal:`"track"`. -**title** - The value of the command attribute :literal:`title`. **origin** The origin of the application that created the *mtable*, e.g. :literal:`"MAD 1.0.0 OSX 64"`. **date** @@ -279,14 +343,16 @@ The header of the *mtable* contains the fields in the default order: The value of the command attribute :literal:`implicit`. **misalign** The value of the command attribute :literal:`misalign`. +**radiate** + The value of the command attribute :literal:`radiate`. +**particle** + The reference beam particle name. +**energy** + The reference beam energy. **deltap** The value of the command attribute :literal:`deltap`. **lost** The number of lost particle(s) or damap(s). -**range** - The value of the command attribute :literal:`range`. [#f5]_ -**__seq** - The *sequence* from the command attribute :var:`sequence`. [#f6]_ : The core of the *mtable* contains the columns in the default order: @@ -314,6 +380,8 @@ The core of the *mtable* contains the columns in the default order: The local coordinate :math:`p_t` at the :math:`s`-position. **pc** The reference beam :math:`P_0c` in which :math:`p_t` is expressed. +**ktap** + The tapering compensation factor stored at the current tracking position. **slc** The slice index ranging from :literal:`-2` to :literal:`nslice`. **turn** @@ -327,6 +395,8 @@ The core of the *mtable* contains the columns in the default order: **__map** The damap at the :math:`s`-position. [#f6]_ +The mtable also carries the in-memory attributes :literal:`taper`, :literal:`range` and the protected sequence handle :literal:`__seq`, but they are not part of the default header list written to TFS files. + Dynamical tracking ------------------ @@ -339,7 +409,7 @@ Dynamical tracking :align: center :figwidth: 98% - Dynamical tracking with slices. + Dynamical tracking with slices. Slicing """"""" @@ -383,5 +453,4 @@ Examples .. [#f3] The :literal:`TKT` scheme (Yoshida) is automatically converted to the :literal:`MKM` scheme (Boole) when approriate. .. [#f7] In all cases, MAD-NG uses PTC setup :literal:`time=true, exact=true`. .. [#f4] The output of mtable in TFS files can be fully customized by the user. -.. [#f5] This field is not saved in the TFS table by default. .. [#f6] Fields and columns starting with two underscores are protected data and never saved to TFS files. diff --git a/refman/source/mad_cmd_twiss.rst b/refman/source/mad_cmd_twiss.rst index 5915b78..94332fa 100644 --- a/refman/source/mad_cmd_twiss.rst +++ b/refman/source/mad_cmd_twiss.rst @@ -15,48 +15,57 @@ The :var:`twiss` command format is summarized in :numref:`fig-twiss-synop`, incl :caption: Synopsis of the :var:`twiss` command with default setup. - mtbl, mflw [, eidx] = twiss { - 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) + mtbl, mflw [, eidx] = twiss { + 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(s), or beta block(s)) - O0=nil, -- initial coordinates of reference orbit - deltap=nil, -- initial deltap(s) - chrom=false, -- compute chromatic functions by finite difference - coupling=false, -- compute optical functions for non-diagonal modes - nturn=nil, -- number of turns to track - nstep=nil, -- number of elements 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=true, -- create mtable and save results - title=nil, -- title of mtable (default seq.name) - observe=0, -- 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=nil, -- finite differences step for jacobian - coiter=nil, -- maximum number of iterations - cotol=nil, -- closed orbit tolerance (i.e.|dX|) - X1=nil, -- 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 + X0=nil, -- initial coordinates (or damap(s), or beta block(s)) + O0=nil, -- initial coordinates of reference orbit + deltap=nil, -- initial deltap(s) + chrom=false, -- compute chromatic functions by finite difference + coupling=false, -- compute optical functions for non-diagonal modes + trkopt=false, -- compute selected parametric optical functions + trkrdt=false, -- compute selected resonance driving terms + nturn=nil, -- number of turns to track + nstep=nil, -- number of elements to track + nslice=nil, -- number of slices (or weights) for each element + method=nil, -- method or order for integration (1 to 8) + model=nil, -- model for integration ('DKD' or 'TKT') + mapdef=2, -- setup for damap (or list of, true => {xy=1}) + secnmul=nil, -- curved-multipole expansion for bends + implicit=nil, -- slice implicit elements too (e.g. plots) + misalign=nil, -- consider misalignment + aperture=nil, -- default aperture + fringe=nil, -- enable fringe fields (see element.flags.fringe) + frngmax=nil, -- maximum multipole fringe field order + radiate=nil, -- radiate at slices + nocavity=nil, -- disable rfcavities + totalpath=nil, -- variable 't' is the totalpath + cmap=nil, -- use C/C++ maps when available + ptcmodel=nil, -- nil=MADNG, true=PTC, false=MADX + save=true, -- create mtable and save results + aper=nil, -- check for aperture + observe=0, -- save only in observed elements (every n turns) + savesel=nil, -- save selector (predicate) + savemap=nil, -- save damap in the column __map + saveanf=nil, -- save analysed normal form in the column __nf + 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=nil, -- action called when debugging the element maps + apersel=nil, -- aperture selector (predicate) + costp=nil, -- finite-difference scale for Jacobian + coitr=nil, -- maximum number of iterations + cotol=nil, -- closed orbit tolerance (i.e.|dX|) + O1=nil, -- 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 :var:`twiss` command supports the following attributes: @@ -64,7 +73,7 @@ The :var:`twiss` command supports the following attributes: .. _twiss.attr: **sequence** - The *sequence* to track. (no default, required). + The *sequence* to track. (no default, required). Example: :expr:`sequence = lhcb1`. @@ -74,207 +83,219 @@ The :var:`twiss` command supports the following attributes: Example: :expr:`beam = beam 'lhcbeam' { beam-attributes }`. **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 :attr:`seq.range`. (default: :const:`nil`). + 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 :attr:`seq.range`. (default: :const:`nil`). Example: :expr:`range = "S.DS.L8.B1/E.DS.R8.B1"`. **dir** - The :math:`s`-direction of the tracking: :const:`1` forward, :const:`-1` backward. (default: :const:`nil`). + The :math:`s`-direction of the tracking: :const:`1` forward, :const:`-1` backward. (default: :const:`nil`). Example: :expr:`dir = -1`. **s0** - A *number* specifying the initial :math:`s`-position offset. (default: :const:`nil`). + A *number* specifying the initial :math:`s`-position offset. (default: :const:`nil`). Example: :expr:`s0 = 5000`. **X0** - A *mappable* (or a list of *mappable*) specifying initial coordinates :literal:`{x,px,y,py, t,pt}`, damap, or beta0 block for each tracked object, i.e. particle or damap. The beta0 blocks are converted to damaps, while the coordinates are converted to damaps only if :literal:`mapdef` is specified, but both will use :literal:`mapdef` to setup the damap constructor. A closed orbit will be automatically searched for damaps built from coordinates. Each tracked object may also contain a :var:`beam` to override the reference beam, and a *logical* :literal:`nosave` to discard this object from being saved in the mtable. (default: :const:`0`). + A *mappable* (or a list of *mappable*) specifying initial coordinates :literal:`{x,px,y,py, t,pt}`, damap, or beta0 block for each tracked object, i.e. particle or damap. The beta0 blocks are converted to damaps, while the coordinates are converted to damaps only if :literal:`mapdef` is specified, but both will use :literal:`mapdef` to setup the damap constructor. A closed orbit will be automatically searched for damaps built from coordinates. Each tracked object may also contain a :var:`beam` to override the reference beam, and a *logical* :literal:`nosave` to discard this object from being saved in the mtable. (default: :const:`nil`). Example: :expr:`X0 = { x=1e-3, px=-1e-5 }`. -**O0** - A *mappable* specifying initial coordinates :literal:`{x,px,y,py,t,pt}` of the reference orbit around which X0 definitions take place. If it has the attribute :literal:`cofind == true`, it will be used as an initial guess to search for the reference closed orbit. (default: :const:`0`). +**O0** + A *mappable* specifying initial coordinates :literal:`{x,px,y,py,t,pt}` of the reference orbit around which X0 definitions take place. If it has the attribute :literal:`cofind == true`, it will be used as an initial guess to search for the reference closed orbit. (default: :const:`nil`). Example: :expr:`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 :literal:`pt` of each tracked particle or damap. (default: :const:`nil`). + A *number* (or list of *number*) specifying the initial :math:`\delta_p` to convert (using the beam) and add to the :literal:`pt` of each tracked particle or damap. (default: :const:`nil`). Example: :expr:`s0 = 5000`. **chrom** - A *logical* specifying to calculate the chromatic functions by finite different using an extra :math:`\delta_p=` :const:`1e-6`. (default: :const:`false`). + A *logical* specifying to calculate the chromatic functions by finite different using an extra :math:`\delta_p=` :const:`1e-6`. (default: :const:`false`). Example: :expr:`chrom = true`. **coupling** - A *logical* specifying to calculate the optical functions for coupling terms in the normalized forms. (default: :const:`false`). + A *logical* specifying to calculate the optical functions for coupling terms in the normalized forms. (default: :const:`false`). - Example: :expr:`chrom = true`. + Example: :expr:`coupling = true`. + +**trkopt** + A *list* of optical-function names requesting additional parametric optics columns to be tracked and stored in the output table. (default: :const:`false`). + + Example: :expr:`trkopt = {'beta11_01', 'beta22_10'}`. + +**trkrdt** + A *list* of resonance-driving-term names requesting additional RDT columns to be tracked and stored in the output table. Each requested name must start with :literal:`'f'`. (default: :const:`false`). + + Example: :expr:`trkrdt = {'f3000', 'f2100'}`. **nturn** - A *number* specifying the number of turn to track. (default: :const:`nil`). + A *number* specifying the number of turn to track. (default: :const:`nil`). Example: :expr:`nturn = 2`. **nstep** - A *number* specifying the number of element to track. A negative value will track all elements. (default: :const:`nil`). + A *number* specifying the number of element to track. A negative value will track all elements. (default: :const:`nil`). Example: :expr:`nstep = 1`. **nslice** - A *number* specifying the number of slices or an *iterable* of increasing relative positions or a *callable* :literal:`(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`). + A *number* specifying the number of slices or an *iterable* of increasing relative positions or a *callable* :literal:`(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: :expr:`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 :const:`true` is equivalent to invoke the *damap* constructor with :literal:`{}` as argument. A value of :const:`false` or :const:`nil` will be internally forced to :const:`true` for the tracking of the normalized forms. (default: :const:`true`). +**mapdef** + A *logical*, a *number*, or a *damap* specification as defined by the :doc:`DAmap ` module to track DA maps instead of particles coordinates. A value of :const:`true` is equivalent to invoke the *damap* constructor with :literal:`{}` as argument. The default value :literal:`2` forces a second-order damap setup for the linear normal-form analysis. (default: :literal:`2`). Example: :expr:`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 :literal:`simple` (equiv. to :literal:`DKD` order 2), :literal:`collim` (equiv. to :literal:`MKM` order 2), and :literal:`teapot` (Teapot splitting order 2). (default: :const:`nil`). + 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 :literal:`simple` (equiv. to :literal:`DKD` order 2), :literal:`collim` (equiv. to :literal:`MKM` order 2), and :literal:`teapot` (Teapot splitting order 2). (default: :const:`nil`). Example: :expr:`method = 'teapot'`. **model** - A *string* specifying the integration model, either :literal:`'DKD'` for *Drift-Kick-Drift* thin lens integration or :literal:`'TKT'` for *Thick-Kick-Thick* thick lens integration. [#f7]_ (default: :const:`nil`) + A *string* specifying the integration model, either :literal:`'DKD'` for *Drift-Kick-Drift* thin lens integration or :literal:`'TKT'` for *Thick-Kick-Thick* thick lens integration. [#f7]_ (default: :const:`nil`) Example: :expr:`model = 'DKD'`. **ptcmodel** - A *logical* indicating to use strict PTC model. [#f8]_ (default: :const:`nil`) + A *logical* selecting the tracking backend: :const:`nil` keeps the MAD-NG model, :const:`true` selects the strict PTC model, and :const:`false` selects the MAD-X-compatible model. [#f8]_ (default: :const:`nil`) Example: :expr:`ptcmodel = true`. +The attributes :literal:`secnmul`, :literal:`aperture`, :literal:`frngmax`, :literal:`nocavity`, :literal:`cmap`, :literal:`aper` and :literal:`apersel` are forwarded unchanged to the underlying :var:`track` command and therefore keep the same semantics and default handling as in :doc:`track `. + **implicit** - A *logical* indicating that implicit elements must be sliced too, e.g. for smooth plotting. (default: :const:`nil`). + A *logical* indicating that implicit elements must be sliced too, e.g. for smooth plotting. (default: :const:`nil`). Example: :expr:`implicit = true`. **misalign** - A *logical* indicating that misalignment must be considered. (default: :const:`nil`). + A *logical* indicating that misalignment must be considered. (default: :const:`nil`). Example: :expr:`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 :const:`true` is equivalent to the bit mask , i.e. allow all elements (default) fringe fields. (default: :const:`nil`). + 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 :const:`true` is equivalent to the bit mask , i.e. allow all elements (default) fringe fields. (default: :const:`nil`). Example: :expr:`fringe = false`. **radiate** - A *logical* enabling or disabling the radiation or the *string* specifying the :literal:`'average'` type of radiation during the closed orbit search. The value :const:`true` is equivalent to :literal:`'average'` and the value :literal:`'quantum'` is converted to :literal:`'average'`. (default: :const:`nil`). + A *logical* enabling damping radiation during the closed-orbit and one-turn-map preparation phases. Any truthy value is collapsed to the damping-only tracking mode used internally by :var:`twiss`. (default: :const:`nil`). - Example: :expr:`radiate = 'average'`. + Example: :expr:`radiate = true`. **totalpath** - A *logical* indicating to use the totalpath for the fifth variable :literal:`'t'` instead of the local path. (default: :const:`nil`). + A *logical* indicating to use the totalpath for the fifth variable :literal:`'t'` instead of the local path. (default: :const:`nil`). Example: :expr:`totalpath = true`. **save** - A *logical* specifying to create a *mtable* and record tracking information at the observation points. The :literal:`save` attribute can also be a *string* specifying saving positions in the observed elements: :literal:`"atentry"`, :literal:`"atslice"`, :literal:`"atexit"` (i.e. :const:`true`), :literal:`"atbound"` (i.e. entry and exit), :literal:`"atbody"` (i.e. slices and exit) and :literal:`"atall"`. (default: :const:`false`). + A *logical* specifying to create a *mtable* and record tracking information at the observation points. The :literal:`save` attribute can also be a *string* specifying saving positions in the observed elements: :literal:`"atentry"`, :literal:`"atslice"`, :literal:`"atexit"` (i.e. :const:`true`), :literal:`"atbound"` (i.e. entry and exit), :literal:`"atbody"` (i.e. slices and exit) and :literal:`"atall"`. (default: :const:`true`). Example: :expr:`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 :literal:`seq.name`. (default: :const:`nil`). - - Example: :expr:`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 :literal:`observe`\ :math:`>0` turns. (default: :const:`nil`). + 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 :literal:`observe`\ :math:`>0` turns. (default: :const:`0`). Example: :expr:`observe = 1`. **savesel** - A *callable* :literal:`(elm, mflw, lw, islc)` acting as a predicate on selected elements for observation, i.e. the element is discarded if the predicate returns :const:`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:`fnil`) + A *callable* :literal:`(elm, mflw, lw, islc)` acting as a predicate on selected elements for observation, i.e. the element is discarded if the predicate returns :const:`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:`fnil`) Example: :expr:`savesel = \\e -> mylist[e.name] ~= nil`. **savemap** - A *logical* indicating to save the damap in the column :literal:`__map` of the *mtable*. (default: :const:`nil`). + A *logical* indicating to save the damap in the column :literal:`__map` of the *mtable*. (default: :const:`nil`). Example: :expr:`savemap = true`. +**saveanf** + A *logical* indicating to save the analysed normal form in the protected column :literal:`__nf` of the *mtable*. (default: :const:`nil`). + + Example: :expr:`saveanf = true`. + **atentry** - A *callable* :literal:`(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 :const:`-1`. (default: :const:`fnil`). - + A *callable* :literal:`(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 :const:`-1`. (default: :const:`fnil`). + Example: :expr:`atentry = myaction`. **atslice** - A *callable* :literal:`(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:`fnil`). + A *callable* :literal:`(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:`fnil`). Example: :expr:`atslice = myaction`. -**atexit** - A *callable* :literal:`(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:`fnil`). +**atexit** + A *callable* :literal:`(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:`fnil`). Example: :expr:`atexit = myaction`. **ataper** - A *callable* :literal:`(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 :literal:`status="lost"` and it is removed from the list of tracked items. (default: :const:`fnil`). + A *callable* :literal:`(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 :literal:`status="lost"` and it is removed from the list of tracked items. (default: :const:`fnil`). Example: :expr:`ataper = myaction`. **atsave** - A *callable* :literal:`(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:`fnil`). + A *callable* :literal:`(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:`fnil`). Example: :expr:`atsave = myaction`. **atdebug** - A *callable* :literal:`(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. :literal:`"map_name:0"` for entry and :literal:`":1"` for exit. If the level :literal:`debug` :math:`\geq 4` and :literal:`atdebug` is not specified, the default *function* :literal:`mdump` is used. In some cases, extra arguments could be passed to the method. (default: :const:`fnil`). + A *callable* :literal:`(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. :literal:`"map_name:0"` for entry and :literal:`":1"` for exit. If the level :literal:`debug` :math:`\geq 4` and :literal:`atdebug` is not specified, the default *function* :literal:`mdump` is used. In some cases, extra arguments could be passed to the method. (default: :const:`fnil`). Example: :expr:`atdebug = myaction`. -**codiff** - A *number* specifying the finite difference step to approximate the Jacobian when damaps are disabled. If :literal:`codiff` is larger than :math:`100\times`\ :literal:`cotol`, it will be adjusted to :literal:`cotol` :math:`/100` and a warning will be emitted. (default: :const:`1e-8`). +**costp** + A *number* specifying the relative finite-difference scale to approximate the Jacobian when damaps are disabled. If :literal:`costp == true`, the closed-orbit preparation stage falls back to the default finite-difference scale from :var:`cofind`. (default: :const:`nil`). - Example: :expr:`codiff = 1e-10`. + Example: :expr:`costp = 1e-8`. -**coiter** - A *number* specifying the maximum number of iteration. If this threshold is reached, all the remaining tracked objects are tagged as :literal:`"unstable"`. (default: 20). +**coitr** + A *number* specifying the maximum number of iteration for the closed-orbit search stage. If this threshold is reached, all the remaining tracked objects are tagged as :literal:`"unstable"`. (default: :const:`nil` and inherited from :var:`cofind`). - Example: :expr:`coiter = 5`. + Example: :expr:`coitr = 5`. **cotol** - A *number* specifying the closed orbit tolerance. If all coordinates update of a particle or a damap are smaller than :literal:`cotol`, then it is tagged as :literal:`"stable"`. (default: :const:`1e-8`). + A *number* specifying the closed orbit tolerance. If all coordinates update of a particle or a damap are smaller than :literal:`cotol`, then it is tagged as :literal:`"stable"`. (default: :const:`nil` and inherited from :var:`cofind`). Example: :expr:`cotol = 1e-6`. -**X1** - A *mappable* specifying the coordinates :literal:`{x,px,y,py,t,pt}` to *subtract* to the final coordinates of the particles or the damaps. (default: :const:`0`). +**O1** + A *mappable* specifying the coordinates :literal:`{x,px,y,py,t,pt}` to *subtract* from the final closed-orbit coordinates. (default: :const:`nil`). - Example: :expr:`X1 = { t=100, pt=10 }`. + Example: :expr:`O1 = { t=100, pt=10 }`. **info** - A *number* specifying the information level to control the verbosity of the output on the console. (default: :const:`nil`). - + A *number* specifying the information level to control the verbosity of the output on the console. (default: :const:`nil`). + Example: :expr:`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`). - + 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: :expr:`debug = 2`. **usrdef** - Any user defined data that will be attached to the tracked map flow, which is internally passed to the elements method :literal:`:track` and to their underlying maps. (default: :const:`nil`). + Any user defined data that will be attached to the tracked map flow, which is internally passed to the elements method :literal:`:track` and to their underlying maps. (default: :const:`nil`). Example: :expr:`usrdef = { myvar=somevalue }`. -**mflow** - A *mflow* containing the current state of a :var:`track` command. If a map flow is provided, all attributes are discarded except :literal:`nstep`, :literal:`info` and :literal:`debug`, as the command was already set up upon its creation. (default: :const:`nil`). +**mflow** + A *mflow* containing the current state of a :var:`twiss` command. If a map flow is provided, all setup attributes are ignored and only the volatile fields already stored in the mflow are reused; in practice, :literal:`nstep`, :literal:`info` and :literal:`debug` are the fields refreshed by the command wrapper. (default: :const:`nil`). Example: :expr:`mflow = mflow0`. The :var:`twiss` command returns the following objects in this order: -**mtbl** +**mtbl** A *mtable* corresponding to the augmented TFS table of the :var:`track` command with the :var:`twiss` command columns. -**mflw** +**mflw** A *mflow* corresponding to the augmented map flow of the :var:`track` command with the :var:`twiss` command data. **eidx** @@ -283,18 +304,16 @@ The :var:`twiss` command returns the following objects in this order: Twiss mtable ------------ -.. _sec.track.mtable: +.. _sec.twiss.mtable: -The :var:`twiss` command returns a *mtable* where the information described hereafter is the default list of fields written to the TFS files. [#f2]_ +The :var:`twiss` command returns a *mtable* where the information described hereafter is the default list of fields written to the TFS files. [#f2]_ -The header of the *mtable* contains the fields in the default order: [#f3]_ +The header of the *mtable* contains the fields in the default order: [#f3]_ **name** - The name of the command that created the *mtable*, e.g. :literal:`"track"`. + The name of the command that created the *mtable*, e.g. :literal:`"twiss"`. **type** - The type of the *mtable*, i.e. :literal:`"track"`. -**title** - The value of the command attribute :literal:`title`. + The type of the *mtable*, i.e. :literal:`"twiss"`. **origin** The origin of the application that created the *mtable*, e.g. :literal:`"MAD 1.0.0 OSX 64"`. **date** @@ -311,6 +330,12 @@ The header of the *mtable* contains the fields in the default order: [#f3]_ The value of the command attribute :literal:`implicit`. **misalign** The value of the command attribute :literal:`misalign`. +**radiate** + The value of the command attribute :literal:`radiate`. +**particle** + The reference beam particle name. +**energy** + The reference beam energy. **deltap** The value of the command attribute :literal:`deltap`. **lost** @@ -319,6 +344,10 @@ The header of the *mtable* contains the fields in the default order: [#f3]_ The value of the command attribute :literal:`chrom`. **coupling** The value of the command attribute :literal:`coupling`. +**trkopt** + The value of the command attribute :literal:`trkopt`. +**trkrdt** + The value of the command attribute :literal:`trkrdt`. **length** The :math:`s`-length of the tracked design orbit. **q1** @@ -347,10 +376,6 @@ The header of the *mtable* contains the fields in the default order: [#f3]_ The sixth synchroton radiation integral. **synch_8** The eighth synchroton radiation integral. -**range** - The value of the command attribute :literal:`range`. [#f4]_ -**__seq** - The *sequence* from the command attribute :var:`sequence`. [#f5]_ The core of the *mtable* contains the columns in the default order: [#f6]_ @@ -376,6 +401,10 @@ The core of the *mtable* contains the columns in the default order: [#f6]_ The local coordinate :math:`t` at the :math:`s`-position. **pt** The local coordinate :math:`p_t` at the :math:`s`-position. +**pc** + The reference beam :math:`P_0c` in which :math:`p_t` is expressed. +**ktap** + The tapering compensation factor stored at the current tracking position. **slc** The slice index ranging from :literal:`-2` to :literal:`nslice`. **turn** @@ -421,6 +450,10 @@ The core of the *mtable* contains the columns in the default order: [#f6]_ **__map** The damap at the :math:`s`-position. [#f5]_ +If :literal:`saveanf == true`, the protected column :literal:`__nf` is also added and stores the analysed normal form at each saved row. + +The mtable also carries the in-memory attributes :literal:`taper`, :literal:`range` and the protected sequence handle :literal:`__seq`, but they are not part of the default header list written to TFS files. + The :literal:`chrom` attribute will add the following fields to the *mtable* header: **dq1** @@ -506,11 +539,10 @@ TODO .. rubric:: Footnotes -.. [#f1] Initial coordinates :var:`X0` may override it by providing a beam per particle or damap. +.. [#f1] Initial coordinates :var:`X0` may override it by providing a beam per particle or damap. .. [#f7] The :literal:`TKT` scheme (Yoshida) is automatically converted to the :literal:`MKM` scheme (Boole) when appropriate. .. [#f8] In all cases, MAD-NG uses PTC setup :literal:`time=true, exact=true`. .. [#f2] The output of mtable in TFS files can be fully customized by the user. .. [#f3] The fields from :literal:`name` to :literal:`lost` are set by the :var:`track` command -.. [#f4] This field is not saved in the TFS table by default. .. [#f5] Fields and columns starting with two underscores are protected data and never saved to TFS files. .. [#f6] The column from :literal:`name` to :literal:`status` are set by the :var:`track` command. diff --git a/refman/source/mad_gen_madx.rst b/refman/source/mad_gen_madx.rst index ab8dd37..0f7454d 100644 --- a/refman/source/mad_gen_madx.rst +++ b/refman/source/mad_gen_madx.rst @@ -3,16 +3,111 @@ MADX ==== +The keyword :literal:`MADX` denotes the special environment within MAD-NG that emulates the behavior of the global workspace of MAD-X. It is a compatibility workspace for importing MAD-X and MAD8 lattice descriptions into MAD-NG. + Environment ----------- -Importing Sequences -------------------- +The object :literal:`MADX` is available globally. Its mutable child is used as the working environment when MAD-X or MAD8 files are imported, so names defined by these files become variables, elements, sequences or beam lines inside :literal:`MADX`. + +:literal:`MADX` is not the CERN MAD-X program embedded into MAD-NG, and it does not execute MAD-X code directly. Instead, MAD-X or MAD8 input is translated to MAD-NG code and then loaded into this environment. The resulting objects are ordinary MAD-NG objects that can be inspected, modified and used by MAD-NG commands such as :var:`track`, :var:`twiss`, :var:`cofind` or :var:`match`. + +In practice, :literal:`MADX` is the workspace that stores imported legacy names. After loading a sequence or optics deck, users typically: + +* access imported objects directly as :literal:`MADX.ps`, :literal:`MADX.lhcb1`, :literal:`MADX.nrj`, ... +* bring selected names into local scope with :literal:`local ps, nrj in MADX` +* update imported knobs and deferred expressions through :literal:`MADX` + +Typical workflow: + +.. code-block:: lua + + MADX:load("fodo.seq", "fodo.mad") + local seq in MADX + seq.beam = beam + mtbl, mflw = twiss { sequence=seq, implicit=true, nslice=10 } + +The environment exposes the option set :literal:`MADX.option` with the following defaults: + +**debug** + Enable extra diagnostic output during translation and loading. (default: :const:`false`) + +**info** + Enable informational output during translation and loading. (default: :const:`false`) + +**warn** + Emit warnings for compatibility fallbacks, in particular when an undefined MAD-X name is read and auto-created with value :const:`0`. (default: :const:`true`) + +**rbarc** + Interpret RBEND lengths using the MAD-X arc/chord compatibility rules during import. (default: :const:`true`) + +**nopub** + Prevent imported sequence elements from being published automatically in the :literal:`MADX` environment. (default: :const:`false`) + +Methods +------- + +**load** + A *method* :literal:`MADX:load(src [, dst [, cfg]])` that loads MAD-X, MAD8 or already translated MAD-NG input. + + If :literal:`src` is a MAD-X/MAD8 file, it is translated to MAD-NG code and then loaded into the environment. If :literal:`dst` is provided, the translated MAD-NG file is written there with the :literal:`.mad` suffix before being loaded. If :literal:`src` is already a :literal:`.mad` file and :literal:`dst` is omitted, it is compiled directly with no translation step. + + This is the standard entry point to import legacy MAD-X or MAD8 models. It is common to call :literal:`MADX:load(...)` several times in a row to import a base sequence, one or more optics files, and optional helper files that predefine otherwise unset MAD-X variables. + + The optional configuration table :literal:`cfg` currently supports: + + * :literal:`reload` to force regeneration of :literal:`dst` even when it is newer than :literal:`src` + * :literal:`mad8` to enable MAD8 parsing rules + * :literal:`rbarc` to override :literal:`MADX.option.rbarc` for the current load + * :literal:`nopub` to override :literal:`MADX.option.nopub` for the current load + +**open_env** + A *method* :literal:`MADX:open_env([ctx])` that opens the MADX object as the active object environment and sets :literal:`option.madxenv` accordingly. + + This is mainly useful when one wants to evaluate a block of assignments using bare MAD-X names instead of prefixed accesses through :literal:`MADX`. For example: + + .. code-block:: lua + + MADX:open_env() + dqx_b1 = 6.65239e-4 + dqy_b1 = 3.31034e-3 + MADX:close_env() + +**close_env** + A *method* :literal:`MADX:close_env()` that closes the active MADX object environment and clears :literal:`option.madxenv`. + +Functions and Constants +----------------------- + +The :literal:`MADX` environment is preloaded with: + +* all variables from :mod:`MAD.constant` +* all element classes from :mod:`MAD.element` +* MAD-X-like scalar helpers such as :literal:`abs`, :literal:`sqrt`, :literal:`exp`, :literal:`log`, :literal:`sin`, :literal:`cos`, :literal:`tan`, :literal:`asin`, :literal:`acos`, :literal:`atan`, :literal:`erf`, :literal:`erfc`, :literal:`fact`, :literal:`sinc`, :literal:`round` and :literal:`frac` +* random helpers :literal:`ranf()`, :literal:`gauss()`, :literal:`tgauss(cut)`, :literal:`poisson(lambda)` and :literal:`seed(seed)` +* geometry helpers :literal:`cord2arc`, :literal:`arc2cord`, :literal:`cord2arc_w` and :literal:`arc2cord_w` + +Compatibility Aliases +--------------------- + +The environment also defines a few MAD-X-specific aliases and compatibility objects: + +* :literal:`MADX.multipole` overrides the survey angle convention so that :literal:`knl[1]` contributes like MAD-X +* :literal:`MADX.rcollimator`, :literal:`MADX.ecollimator`, :literal:`MADX.translation` and :literal:`MADX.elseparator` are provided as aliases not present in the base MAD element namespace +* string identifiers such as :literal:`centre`, :literal:`circle`, :literal:`ellipse`, :literal:`rectellipse`, :literal:`entry` and :literal:`exit` are preloaded, with :literal:`center` mapped to :literal:`centre` + +Names and Lookup +---------------- + +MAD-X names are normalized before lookup: -Converting Scripts ------------------- +* names are converted to lower case +* :literal:`.` and :literal:`$` are converted to :literal:`_` +* repeated primes are rewritten to suffixes such as :literal:`_prime`, :literal:`_2prime`, and so on -Converting Macros ------------------ +Reading an undefined name from :literal:`MADX` creates it lazily with value :const:`0`. If :literal:`MADX.option.warn == true`, a warning is emitted before the zero value is stored. +The same imported object can therefore be reached in several equivalent ways. For example, after importing a sequence named :literal:`ps`, one may use: +* :literal:`MADX.ps` +* :literal:`local ps in MADX` diff --git a/refman/source/mad_gen_mtable.rst b/refman/source/mad_gen_mtable.rst index 92be897..15780de 100644 --- a/refman/source/mad_gen_mtable.rst +++ b/refman/source/mad_gen_mtable.rst @@ -17,7 +17,7 @@ The :literal:`mtable` object provides the following attributes: A *string* specifying the type of the mtable (often) set to the name of the command that created it, like :literal:`survey`, :var:`track` or :var:`twiss`. (default: :literal:`'user'`). **title** - A *string* specifying the title of the mtable (often) set to the attribute :literal:`title` of the command that created it. (default: :literal:`'no-title'`). + A *string* specifying the title of the mtable when one is attached by the creator. Commands may set it explicitly, but it is not part of the base mtable defaults. **origin** A *string* specifying the origin of the mtable. (default: :literal:`"MAD version os arch"`). @@ -33,7 +33,7 @@ The :literal:`mtable` object provides the following attributes: **header** A *list* specifying the augmented attributes names (and their order) used by default for the header when writing the mtable to files. Augmented meaning that the *list* is concatenated to the *list* held by the parent mtable during initialization. - (default: :literal:`{'name', 'type', 'title', 'origin', 'date', 'time', 'refcol'}`). + (default: :literal:`{'name', 'type', 'origin', 'date', 'time', 'refcol'}`). **column** A *list* specifying the augmented columns names (and their order) used by default for the columns when writing the mtable to files. Augmented meaning that the *list* is concatenated to the *list* held by the parent mtable during initialization. (default: :const:`nil`). @@ -41,11 +41,8 @@ The :literal:`mtable` object provides the following attributes: **novector** A *logical* specifying to not convert (:literal:`novector == true`) columns containing only numbers to vectors during the insertion of the second row. The attribute can also be a *list* specifying the columns names to remove from the specialization. If the *list* is empty or :literal:`novector ~= true`, all numeric columns will be converted to vectors, and support all methods and operations from the :doc:`linear algebra ` module. (default: :const:`nil`). -**owner** - A *logical* specifying if an *empty* mtable is a view with no data (:literal:`owner ~= true`), or a mtable holding data (:literal:`owner == true`). (default: :const:`nil`). - **reserve** - A *number* specifying an estimate of the maximum number of rows stored in the mtable. If the value is underestimated, the mtable will still expand on need. (default: :literal:`8`). + A *number* specifying an estimate of the maximum number of rows stored in the mtable. If the value is underestimated, the mtable will still expand on need. (default: :literal:`100`). **Warning**: the following private and read-only attributes are present in all mtables and should *never be used, set or changed*; breaking this rule would lead to an *undefined behavior*: @@ -87,7 +84,7 @@ The :literal:`mtable` object provides the following methods: A *method* :literal:`(idx, [ref])` returning a *string* corresponding to the (mangled) *value* from the reference column of the row at the index :literal:`idx`, or :const:`nil`. A row *value* appearing more than once in the reference column will be mangled with an absolute count, e.g. :literal:`mq[3]`, or a relative count versus the reference row determined by :literal:`:index_of(ref)`, e.g. :literal:`mq{-2}`. **index_of** - A *method* :literal:`(a, [ref], [dir])` returning a *number* corresponding to the positive index of the row determined by the first argument or :const:`nil`. If :literal:`a` is a *number* (or a *string* representing a *number*), it is interpreted as the index of the row and returned as a second *number*. If :literal:`a` is a *string*, it is interpreted as the (mangled) *value* of the row in the reference column as returned by :literal:`:name_of`. Finally, :literal:`a` can be a *reference* to an element to search for **if** the mtable has both, an attached sequence, and a column named :literal:`'eidx'` mapping the indexes of the elements to the attached sequence. [#f1]_ The argument :literal:`ref` (default: :const:`nil`) specifies the reference row determined by :literal:`:index_of(ref)` to use for relative indexes, for decoding mangled values with relative counts, or as the reference row to start searching from. The argument :literal:`dir` (default: :const:`1`) specifies the direction of the search with values :const:`1` (forward), :literal:`-1` (backward), or :const:`0` (no direction), which correspond respectively to the rounding methods :literal:`ceil`, :literal:`floor` and :literal:`round` from the lua math module. + A *method* :literal:`(a, [ref], [dir])` returning a *number* corresponding to the positive index of the row determined by the first argument or :const:`nil`. If :literal:`a` is a *number* (or a *string* representing a *number*), it is interpreted as the index of the row and returned as a second *number*. If :literal:`a` is a *string*, it is interpreted as the (mangled) *value* of the row in the reference column as returned by :literal:`:name_of`. Finally, :literal:`a` can be a *reference* to an element to search for **if** the mtable has both, an attached sequence, and a column named :literal:`'eidx'` mapping the indexes of the elements to the attached sequence. [#f1]_ The argument :literal:`ref` (default: :const:`nil`) specifies the reference row determined by :literal:`:index_of(ref)` to use for relative indexes, for decoding mangled values with relative counts, or as the reference row to start searching from. The argument :literal:`dir` (default: :const:`0`) specifies the direction of the search with values :const:`1` (forward), :literal:`-1` (backward), or :const:`0` (no direction), which correspond respectively to the rounding methods :literal:`ceil`, :literal:`floor` and :literal:`round` from the lua math module. **range_of** A *method* :literal:`([rng], [ref], [dir])` returning three *number*\ s corresponding to the positive indexes *start* and *end* of the range and its direction *dir* (default: :const:`1`), or :const:`nil` for an empty range. If :literal:`rng` is omitted, it returns :const:`1`, :literal:`#self`, :const:`1`, or :literal:`#self`, :const:`1`, :literal:`-1` if :literal:`dir` is negative. If :literal:`rng` is a *number* or a *string* with no :literal:`'/'` separator, it is interpreted as *start* and *end*, both determined by :literal:`:index_of`. If :literal:`rng` is a *string* containing the separator :literal:`'/'`, it is split in two *string*\ s interpreted as *start* and *end*, both determined by :literal:`:index_of`. If :literal:`rng` is a *list*, it will be interpreted as { *start*, *end*, :literal:`[ref]`, :literal:`[dir]` }, both determined by :literal:`:index_of`. The arguments :literal:`ref` and :literal:`dir` are forwarded to all invocations of :literal:`:index_of` with a higher precedence than ones in the *list* :literal:`rng`, and a runtime error is raised if the method returns :const:`nil`, i.e. to disambiguate between a valid empty range and an invalid range. @@ -165,19 +162,19 @@ The :literal:`mtable` object provides the following methods: A *method* :literal:`([rng], [sel])` returning the mtable itself after removing the rows determined by :literal:`:filter([rng], [sel], true)`. **sort** - A *method* :literal:`(cmp, [rng], [sel])` returning the mtable itself after sorting the rows at the indexes determined by :literal:`:filter([rng], [sel], true)` using the ordering *callable* :literal:`cmp(row1, row2)`. The arguments :literal:`row1` and :literal:`row2` are *mappable* (proxies) referring to the current rows being compared and providing access to the columns values for the comparison. [#f3]_ The argument :literal:`cmp` can be specified in a compact ordering form as a *string* that will be converted to an ordering *callable* by the function :literal:`str2cmp` from the :doc:`utility ` module. For example, the *string* "-y,x" will be converted by the method to the following *lambda* :literal:`\\r1,r2 -> r1.y > r2.y or r1.y == r2.y and r1.x < r2.x`, where :literal:`y` and :literal:`x` are the columns used to sort the mtable in descending (`-`) and ascending (:literal:`+`) order respectively. The compact ordering form is not limited in the number of columns and avoids making mistakes in the comparison logic when many columns are involved. + A *method* :literal:`(cmp, [rng], [sel])` returning the mtable itself after sorting the rows at the indexes determined by :literal:`:filter([rng], [sel], true)` using the ordering *callable* :literal:`cmp(row1, row2)`. The arguments :literal:`row1` and :literal:`row2` are *mappable* (proxies) referring to the current rows being compared and providing access to the columns values for the comparison. [#f3]_ The argument :literal:`cmp` can be specified in a compact ordering form as a *string* that will be converted to an ordering *callable* by the function :literal:`str2cmp` from the :doc:`utility ` module. For example, the *string* "-y,x" will be converted by the method to the following *lambda* :literal:`\\r1,r2 -> r1.y > r2.y or r1.y == r2.y and r1.x < r2.x`, where :literal:`y` and :literal:`x` are the columns used to sort the mtable in descending (`-`) and ascending (:literal:`+`) order respectively. The compact ordering form is not limited in the number of columns and avoids making mistakes in the comparison logic when many columns are involved. **cycle** A *method* :literal:`(a)` returning the mtable itself after checking that :literal:`a` is a valid reference using :literal:`:index_of(a)`, and storing it in the :literal:`__cycle` attribute, itself erased by the methods editing the mtable like :literal:`:insert`, :literal:`:remove` or :literal:`:sort`. **copy** - A *method* :literal:`([name], [owner])` returning a new mtable from a copy of :literal:`self`, with the optional :literal:`name` and the optional attribute :literal:`owner` set. If the mtable is a view, so will be the copy unless :literal:`owner == true`. + A *method* :literal:`([name])` returning a new mtable from a copy of :literal:`self`, with the optional :literal:`name` set. Copies preserve whether the source is a view or a table holding its own data; there is no :literal:`owner` override on copy. **is_view** A *method* :literal:`()` returning :const:`true` if the mtable is a view over another mtable data, :const:`false` otherwise. **set_readonly** - Set the mtable as read-only, including the columns and the rows proxies. + Set the mtable object as read-only. This protects the object attributes themselves, but does not freeze the row and column data proxies nor the row and column editing methods backed by the internal table data. **read** A *method* :literal:`([filname])` returning a new instance of :literal:`self` filled with the data read from the file determined by :literal:`openfile(filename, 'r', {'.tfs','.txt','.dat'})` from the :doc:`utility ` module. This method can read columns containing the data types *nil*, *boolean*, *number*, *complex number*, (numerical) *range*, and (quoted) *string*. The header can also contain tables saved as *string* and decoded with *function* :literal:`str2tbl` from the :doc:`utility ` module. @@ -231,7 +228,7 @@ The :literal:`mtable` object provides the following metamethods: **__init** - A *metamethod* :literal:`()` called by the constructor to build the mtable from the column names stored in its *list* part and some attributes, like :literal:`owner`, :literal:`reserve` and :literal:`novector`. + A *metamethod* :literal:`()` called by the constructor to build the mtable from the column names stored in its *list* part and some attributes, like :literal:`reserve` and :literal:`novector`. **__copy** A *metamethod* :literal:`()` similar to the *method* :literal:`copy`. @@ -248,7 +245,7 @@ MTables creation During its creation as an *object*, an mtable can defined its attributes as any object, and the *list* of its column names, which will be cleared after its initialization. Any column name in the *list* that is enclosed by braces is designated as the refererence column for the dictionnary that provides fast row indexing, and the attribute :literal:`refcol` is set accordingly. -Some attributes are considered during the creation by the *metamethod* :literal:`__init`, like :literal:`owner`, :literal:`reserve` and :literal:`novector`, and some others are initialized with defined values like :literal:`type`, :literal:`title`, :literal:`origin`, :literal:`date`, :literal:`time`, and :literal:`refcol`. The attributes :literal:`header` and :literal:`column` are concatenated with the the parent ones to build incrementing *list* of attributes names and columns names used by default when writing the mtable to files, and these lists are not provided as arguments. +Some attributes are considered during the creation by the *metamethod* :literal:`__init`, like :literal:`reserve` and :literal:`novector`, and some others are initialized with defined values like :literal:`type`, :literal:`origin`, :literal:`date`, :literal:`time`, and :literal:`refcol`. The attributes :literal:`header` and :literal:`column` are concatenated with the the parent ones to build incrementing *list* of attributes names and columns names used by default when writing the mtable to files, and these lists are not provided as arguments. The older :literal:`owner` creation attribute is no longer supported. The following example shows how to create a mtable form a *list* of column names add rows: @@ -334,7 +331,7 @@ Ranging a mtable triggers a complex look up mechanism where the arguments will b The mtable iterators are created by the method :literal:`:iter`, based on the method :literal:`:range_of` as mentioned in its description and includes an extra *number* of turns as for the method :literal:`:length_of`, and a direction :const:`1` (forward) or :literal:`-1` (backward) for the iteration. -The method :literal:`:foreach` uses the iterator returned by :literal:`:iter` with a range as its sole argument to loop over the rows where to apply the predicate before executing the action. The methods :literal:`:select`, :literal:`:deselect`, :literal:`:filter`, :literal:`:insert`, and :literal:`:remove` are all based directly or indirectly on the :literal:`:foreach` method. Hence, to iterate backward over a mtable range, these methods have to use either its *list* form or a numerical range. For example the invocation :literal:`tbl:foreach(\\r -> print(r.name), {-2, 2, nil, -1})` will iterate backward over the entire mtable excluding the first and last rows, equivalently to the invocation :literal:`tbl:foreach(\\r -> print(r.name), -2..2..-1)`. +The method :literal:`:foreach` uses the iterator returned by :literal:`:iter` with a range as its sole argument to loop over the rows where to apply the predicate before executing the action. The methods :literal:`:select`, :literal:`:deselect`, :literal:`:filter`, :literal:`:insert`, and :literal:`:remove` are all based directly or indirectly on the :literal:`:foreach` method. Hence, to iterate backward over a mtable range, these methods have to use either its *list* form or a numerical :type:`range`. For example the invocation :literal:`tbl:foreach(\\r -> print(r.name), {-2, 2, nil, -1})` iterates backward over the entire mtable excluding the first and last rows. The following example shows how to access to the rows with the :literal:`:foreach` method: @@ -348,7 +345,7 @@ The following example shows how to access to the rows with the :literal:`:foreac + { 'p11', 3.1, 4.2 } local act = \r -> print(r.name, r.y) - tbl:foreach(act, -2..2..-1) + tbl:foreach(act, {-2, 2, nil, -1}) -- display: p13 3.2 ! p12 2.2 tbl:foreach(act, "p11[1]/p11[2]") @@ -381,18 +378,25 @@ The following example shows how the :var:`track` command, i.e. :literal:`self` h .. code-block:: - local header = { -- extra attributes to save in track headers - 'direction', 'observe', 'implicit', 'misalign', 'deltap', 'lost' } + local header = { -- extra attributes saved in track headers + 'direction', 'observe', 'implicit', 'misalign', + 'radiate', 'particle', 'energy', 'deltap', 'lost' } - local function make_mtable (self, range, nosave) - local title, dir, observe, implicit, misalign, deltap, savemap in self - local sequ, nrow = self.sequence, nosave and 0 or 16 + local function make_mtable (self, range) + local range, nturn, dir, observe, reserve, implicit, misalign, radiate, taper, + deltap, savemap in self + local sequ = self.sequence + local beam = self.beam or sequ.beam + local par, nrj = beam.particle, beam.energy + local nrow = reserve > 0 and reserve or + min(1e5, max(1e2, sequ:length_of(range, nturn, dir))) return mtable(sequ.name, { -- keep column order! - type='track', title=title, header=header, + type='track', header=header, direction=dir, observe=observe, implicit=implicit, misalign=misalign, - deltap=deltap, lost=0, range=range, reserve=nrow, __seq=sequ, - {'name'}, 'kind', 's', 'l', 'id', 'x', 'px', 'y', 'py', 't', 'pt', + radiate=radiate, taper=taper, particle=par, energy=nrj, deltap=deltap, + lost=0, range=range, reserve=nrow, __seq=sequ, + {'name'}, 'kind', 's', 'l', 'id', 'x', 'px', 'y', 'py', 't', 'pt', 'pc', 'ktap', 'slc', 'turn', 'tdir', 'eidx', 'status', savemap and '__map' or nil }) end diff --git a/refman/source/mad_gen_object.rst b/refman/source/mad_gen_object.rst index 27dcc5e..cf5d79e 100644 --- a/refman/source/mad_gen_object.rst +++ b/refman/source/mad_gen_object.rst @@ -378,7 +378,7 @@ The root :literal:`object` provides the following methods: A *method* :literal:`()` returning :literal:`self` after clearing the object except its private attributes. **set_methods** - A *method* :literal:`(set, [override])` returning :literal:`self` with the methods set to the pairs (*key*, *value*) contained in :literal:`set`, where *key* must be a *string* (the method's name) and *value* must be a *callable* (the method itself). If :literal:`override ~= true`, the read-only methods (with *key* starting by :literal:`"__"`) cannot be updated. Classes cannot update their methods. + A *method* :literal:`(set, [override])` returning :literal:`self` with the methods set to the pairs (*key*, *value*) contained in :literal:`set`, where *key* must be a *string* (the method's name) and *value* must be a *callable* (the method itself). If :literal:`override ~= true`, only the private methods (with *key* starting by :literal:`"__"`) remain protected. **set_metamethods** A *method* :literal:`(set, [override])` returning :literal:`self` with the attributes set to the pairs (*key*, *value*) contained in :literal:`set`, where *key* must be a *string* (the metamethod's name) and *value* must be a *callable*\ (the metamethod itself). If :literal:`override == false`, the metamethods cannot be updated. Classes cannot update their metamethods. @@ -562,4 +562,3 @@ Note that MAD-X workspace is case insensitive and everything is "global" (no sco .. [#f3] This feature is used to setup a command from another command, e.g. :var:`track` from :var:`twiss` .. [#f4] This approach is safer than the volatile option :literal:`RBARC` of MAD-X. .. [#f5] :literal:`bsearch` and :literal:`lsearch` stand for binary (ordered) search and linear (unordered) search respectively. - diff --git a/refman/source/mad_gen_sequence.rst b/refman/source/mad_gen_sequence.rst index 7bdd8e5..e1b53b7 100644 --- a/refman/source/mad_gen_sequence.rst +++ b/refman/source/mad_gen_sequence.rst @@ -179,7 +179,7 @@ The :var:`sequence` object provides the following methods: A *method* :literal:`([name])` returning a new sequence from the sequence reversed, and named from the optional *string* :literal:`name` (default: :literal:`self.name..'_rev'`). **cycle** - A *method* :literal:`(a)` returning the sequence itself after checking that :literal:`a` is a valid reference using :literal:`:index_of(a)`, and storing it in the :literal:`__cycle` attribute, + A *method* :literal:`(a)` returning the sequence itself after checking that :literal:`a` is a valid reference using :literal:`:index_of(a)` and that it resolves to a *marker*, and storing it in the :literal:`__cycle` attribute, itself erased by the methods editing the sequence like :literal:`:install`, :literal:`:replace`, :literal:`:remove`, :literal:`:share`, and :literal:`:unique`. **share** @@ -199,8 +199,8 @@ The :var:`sequence` object provides the following methods: are created within the :literal:`MADX` environment. **copy** - A *method* :literal:`([name], [owner])` returning a new sequence from a copy of :literal:`self`, with the optional :literal:`name` and the optional attribute :literal:`owner` set. - If the sequence is a view, so will be the copy unless :literal:`owner == true`. + A *method* :literal:`([name])` returning a new sequence from a copy of :literal:`self`, with the optional :literal:`name` set. + If the sequence is a view, the copy is also a view. **set_readonly** Set the sequence as read-only, including its columns. diff --git a/refman/source/mad_mod_const.rst b/refman/source/mad_mod_const.rst index 5430930..f744cf5 100644 --- a/refman/source/mad_mod_const.rst +++ b/refman/source/mad_mod_const.rst @@ -5,7 +5,7 @@ Constants ********* -This chapter describes some constants uniquely defined as macros in the C header :file:`mad_cst.h` and available from modules :mod:`MAD.constant` and :mod:`MAD._C` (C API) as floating point double precision variables. +This chapter describes some constants uniquely defined as macros in the C header :file:`mad_cst.h` and available from modules :mod:`MAD.constant` and :mod:`MAD._C` (C API) as floating point double precision variables. Numerical Constants =================== @@ -13,7 +13,7 @@ Numerical Constants .. index:: Numerical constants -These numerical constants are provided by the system libraries. Note that the constant :const:`huge` differs from :const:`math.huge`, which corresponds in fact to :const:`inf`. +These numerical constants are provided by the system libraries. Note that the constant :const:`huge` differs from :const:`math.huge`, which corresponds in fact to :const:`inf`. =================== ====================== ========================= ====================== MAD constants C macros C constants Values @@ -72,8 +72,8 @@ This section describes some physical constants uniquely defined as macros in the MAD constants C macros C constants Values =============== =================== ======================= ====================== :const:`minlen` :c:macro:`P_MINLEN` :const:`mad_cst_MINLEN` Min length tolerance, default :math:`10^{-10}` in :unit:`[m]` -:const:`minang` :c:macro:`P_MINANG` :const:`mad_cst_MINANG` Min angle tolerance, default :math:`10^{-10}` in :unit:`[1/m]` -:const:`minstr` :c:macro:`P_MINSTR` :const:`mad_cst_MINSTR` Min strength tolerance, default :math:`10^{-10}` in :unit:`[rad]` +:const:`minang` :c:macro:`P_MINANG` :const:`mad_cst_MINANG` Min angle tolerance, default :math:`10^{-10}` in :unit:`[rad]` +:const:`minstr` :c:macro:`P_MINSTR` :const:`mad_cst_MINSTR` Min strength tolerance, default :math:`10^{-10}` in :unit:`[1/m]` =============== =================== ======================= ====================== The following table lists some physical constants from the `CODATA 2018 `_ sheet. @@ -87,6 +87,7 @@ MAD constants C macros C constants Values :const:`qelect` :c:macro:`P_QELECT` :const:`mad_cst_QELECT` Elementary electric charge, :math:`e` in :unit:`[C]` :const:`hbar` :c:macro:`P_HBAR` :const:`mad_cst_HBAR` Reduced Plack's constant, :math:`\hbar` in :unit:`[GeV.s]` :const:`amass` :c:macro:`P_AMASS` :const:`mad_cst_AMASS` Unified atomic mass, :math:`m_u\,c^2` in :unit:`[GeV]` +:const:`umass` :c:macro:`P_AMASS` :const:`mad_cst_AMASS` Alias of :const:`amass` :const:`emass` :c:macro:`P_EMASS` :const:`mad_cst_EMASS` Electron mass, :math:`m_e\,c^2` in :unit:`[GeV]` :const:`pmass` :c:macro:`P_PMASS` :const:`mad_cst_PMASS` Proton mass, :math:`m_p\,c^2` in :unit:`[GeV]` :const:`nmass` :c:macro:`P_NMASS` :const:`mad_cst_NMASS` Neutron mass, :math:`m_n\,c^2` in :unit:`[GeV]` diff --git a/refman/source/mad_mod_cplxnum.rst b/refman/source/mad_mod_cplxnum.rst index ebfa0cf..dbcfd51 100644 --- a/refman/source/mad_mod_cplxnum.rst +++ b/refman/source/mad_mod_cplxnum.rst @@ -66,16 +66,16 @@ Operator-like Methods --------------------- ================= =================== =================== ============================= -Functions Return values Metamethods C functions +Functions Return values Metamethods C functions ================= =================== =================== ============================= -:func:`z:unm()` :math:`-z` :func:`__unm(z,_)` -:func:`z:add(z2)` :math:`z + z_2` :func:`__add(z,z2)` -:func:`z:sub(z2)` :math:`z - z_2` :func:`__sub(z,z2)` -:func:`z:mul(z2)` :math:`z \cdot z_2` :func:`__mul(z,z2)` +:func:`z:unm()` :math:`-z` :func:`__unm(z,_)` +:func:`z:add(z2)` :math:`z + z_2` :func:`__add(z,z2)` +:func:`z:sub(z2)` :math:`z - z_2` :func:`__sub(z,z2)` +:func:`z:mul(z2)` :math:`z \cdot z_2` :func:`__mul(z,z2)` :func:`z:div(z2)` :math:`z / z_2` :func:`__div(z,z2)` :c:func:`mad_cpx_div_r` [#f1]_ :func:`z:mod(z2)` :math:`z \mod z_2` :func:`__mod(z,z2)` :c:func:`mad_cpx_mod_r` :func:`z:pow(z2)` :math:`z ^ {z_2}` :func:`__pow(z,z2)` :c:func:`mad_cpx_pow_r` -:func:`z:eq(z2)` :math:`z = z_2` :func:`__eq(z,z2)` +:func:`z:eq(z2)` :math:`z = z_2` :func:`__eq(z,z2)` ================= =================== =================== ============================= Real-like Methods @@ -84,7 +84,7 @@ Real-like Methods ============================= ==================================================================== ============================ Functions Return values C functions ============================= ==================================================================== ============================ -:func:`z:abs()` :math:`|z|` :c:func:`mad_cpx_abs_r` +:func:`z:abs()` :math:`|\Re(z)|+i\,|\Im(z)|` :c:func:`mad_cpx_abs_r` :func:`z:acos()` :math:`\cos^{-1} z` :c:func:`mad_cpx_acos_r` :func:`z:acosh()` :math:`\cosh^{-1} z` :c:func:`mad_cpx_acosh_r` :func:`z:acot()` :math:`\cot^{-1} z` :c:func:`mad_cpx_atan_r` @@ -95,36 +95,38 @@ Functions Return values :func:`z:asinhc()` :math:`\frac{\sinh^{-1} z}{z}` :c:func:`mad_cpx_asinhc_r` :func:`z:atan()` :math:`\tan^{-1} z` :c:func:`mad_cpx_atan_r` :func:`z:atanh()` :math:`\tanh^{-1} z` :c:func:`mad_cpx_atanh_r` -:func:`z:ceil()` :math:`\lceil\Re(z)\rceil+i\,\lceil\Im(z)\rceil` +:func:`z:ceil()` :math:`\lceil\Re(z)\rceil+i\,\lceil\Im(z)\rceil` :func:`z:cos()` :math:`\cos z` :c:func:`mad_cpx_cos_r` :func:`z:cosh()` :math:`\cosh z` :c:func:`mad_cpx_cosh_r` :func:`z:cot()` :math:`\cot z` :c:func:`mad_cpx_tan_r` :func:`z:coth()` :math:`\coth z` :c:func:`mad_cpx_tanh_r` :func:`z:exp()` :math:`\exp z` :c:func:`mad_cpx_exp_r` -:func:`z:floor()` :math:`\lfloor\Re(z)\rfloor+i\,\lfloor\Im(z)\rfloor` -:func:`z:frac()` :math:`z - \operatorname{trunc}(z)` -:func:`z:hypot(z2)` :math:`\sqrt{z^2+z_2^2}` [#f2]_ -:func:`z:hypot3(z2,z3)` :math:`\sqrt{z^2+z_2^2+z_3^2}` [#f2]_ +:func:`z:floor()` :math:`\lfloor\Re(z)\rfloor+i\,\lfloor\Im(z)\rfloor` +:func:`z:frac()` :math:`z - \operatorname{trunc}(z)` +:func:`z:hypot(z2)` :math:`\sqrt{z^2+z_2^2}` [#f2]_ +:func:`z:hypot3(z2,z3)` :math:`\sqrt{z^2+z_2^2+z_3^2}` [#f2]_ :func:`z:inv(v_)` :math:`\frac{v}{z}` :c:func:`mad_cpx_inv_r` [#f1]_ :func:`z:invsqrt(v_)` :math:`\frac{v}{\sqrt z}` :c:func:`mad_cpx_invsqrt_r` [#f1]_ :func:`z:log()` :math:`\log z` :c:func:`mad_cpx_log_r` :func:`z:log10()` :math:`\log_{10} z` :c:func:`mad_cpx_log10_r` :func:`z:powi(n)` :math:`z^n` :c:func:`mad_cpx_powi_r` -:func:`z:round()` :math:`\lfloor\Re(z)\rceil+i\,\lfloor\Im(z)\rceil` +:func:`z:round()` :math:`\lfloor\Re(z)\rceil+i\,\lfloor\Im(z)\rceil` :func:`z:sin()` :math:`\sin z` :c:func:`mad_cpx_sin_r` :func:`z:sinc()` :math:`\frac{\sin z}{z}` :c:func:`mad_cpx_sinc_r` :func:`z:sinh()` :math:`\sinh z` :c:func:`mad_cpx_sinh_r` :func:`z:sinhc()` :math:`\frac{\sinh z}{z}` :c:func:`mad_cpx_sinhc_r` -:func:`z:sqr()` :math:`z \cdot z` +:func:`z:sqr()` :math:`z \cdot z` :func:`z:sqrt()` :math:`\sqrt{z}` :c:func:`mad_cpx_sqrt_r` :func:`z:tan()` :math:`\tan z` :c:func:`mad_cpx_tan_r` :func:`z:tanh()` :math:`\tanh z` :c:func:`mad_cpx_tanh_r` -:func:`z:trunc()` :math:`\operatorname{trunc} \Re(z)+i\,\operatorname{trunc} \Im(z)` +:func:`z:trunc()` :math:`\operatorname{trunc} \Re(z)+i\,\operatorname{trunc} \Im(z)` :func:`z:unit()` :math:`\frac{z}{|z|}` :c:func:`mad_cpx_unit_r` ============================= ==================================================================== ============================ In methods :func:`inv()` and :func:`invsqrt()`, default is :expr:`v_ = 1`. +For the scalar modulus :math:`|z|`, use the generic function :func:`cabs(z)`. + Complex-like Methods -------------------- @@ -133,14 +135,14 @@ Functions Return values C functions ================= ============================================== ========================== :func:`z:cabs()` :math:`|z|` :c:func:`mad_cpx_abs_r` :func:`z:carg()` :math:`\arg z` :c:func:`mad_cpx_arg_r` -:func:`z:conj()` :math:`z^*` +:func:`z:conj()` :math:`z^*` :func:`z:fabs()` :math:`|\Re(z)|+i\,|\Im(z)|` -:func:`z:imag()` :math:`\Im(z)` +:func:`z:imag()` :math:`\Im(z)` :func:`z:polar()` :math:`|z|\,e^{i \arg z}` :c:func:`mad_cpx_polar_r` :func:`z:proj()` :math:`\operatorname{proj}(z)` :c:func:`mad_cpx_proj_r` -:func:`z:real()` :math:`\Re(z)` +:func:`z:real()` :math:`\Re(z)` :func:`z:rect()` :math:`\Re(z)\cos \Im(z)+i\,\Re(z)\sin \Im(z)` :c:func:`mad_cpx_rect_r` -:func:`z:reim()` :math:`\Re(z), \Im(z)` +:func:`z:reim()` :math:`\Re(z), \Im(z)` ================= ============================================== ========================== Error-like Methods @@ -149,7 +151,7 @@ Error-like Methods Error-like methods call C wrappers to the corresponding functions from the `Faddeeva library `_ from the MIT, considered as one of the most accurate and fast implementation over the complex plane [FADDEEVA]_ (see :file:`mad_num.c`). ======================= ========================================================== ====================== -Functions Return values C functions +Functions Return values C functions ======================= ========================================================== ====================== :func:`z:erf(rtol_)` :math:`\frac{2}{\sqrt\pi}\int_0^z e^{-t^2} dt` :c:func:`mad_cpx_erf_r` :func:`z:erfc(rtol_)` :math:`1-\operatorname{erf}(z)` :c:func:`mad_cpx_erfc_r` @@ -395,6 +397,5 @@ References .. rubric:: Footnotes -.. [#f1] Division and inverse use a robust and fast complex division algorithm, see [CPXDIV]_ and [CPXDIV2]_ for details. +.. [#f1] Division and inverse use a robust and fast complex division algorithm, see [CPXDIV]_ and [CPXDIV2]_ for details. .. [#f2] Hypot and hypot3 methods use a trivial implementation that may lead to numerical overflow/underflow. - diff --git a/refman/source/mad_mod_functions.rst b/refman/source/mad_mod_functions.rst index bd1baf0..17ca358 100644 --- a/refman/source/mad_mod_functions.rst +++ b/refman/source/mad_mod_functions.rst @@ -34,7 +34,7 @@ Functions Return values :func:`atan(x,r_)` :math:`\tan^{-1} x` :func:`atan2(x,y,r_)` :math:`\tan^{-1} \frac{x}{y}` :func:`atanh(x,r_)` :math:`\tanh^{-1} x` :c:func:`atanh` -:func:`ceil(x,r_)` :math:`\lceil x \rceil` +:func:`ceil(x,r_)` :math:`\lceil x \rceil` :func:`cos(x,r_)` :math:`\cos x` :func:`cosh(x,r_)` :math:`\cosh x` :func:`cot(x,r_)` :math:`\cot x` @@ -68,7 +68,7 @@ Functions Return values Generic Complex-like Functions ------------------------------ -Complex-like generic functions forward the call to the method of the same name from the first argument when the latter is not a :type:`number`, otherwise it implements a real-like compatibility layer using the equivalent representation :math:`z=x+0i`. The optional argument :var:`r_` represents a destination for results with reference semantic, i.e. avoiding memory allocation, which is ignored by results with value semantic. +Complex-like generic functions forward the call to the method of the same name from the first argument when the latter is not a :type:`number`, otherwise it implements a real-like compatibility layer using the equivalent representation :math:`z=x+0i`. The optional argument :var:`r_` represents a destination for results with reference semantic, i.e. avoiding memory allocation, which is ignored by results with value semantic. ======================= ================================== Functions Return values @@ -114,13 +114,13 @@ Generic Error-like Functions Error-like generic functions forward the call to the method of the same name from the first argument when the latter is not a :type:`number`, otherwise it calls C wrappers to the corresponding functions from the `Faddeeva library `_ from the MIT (see :file:`mad_num.c`). The optional argument :var:`r_` represents a destination for results with reference semantic, i.e. avoiding memory allocation, which is ignored by results with value semantic. ========================== ========================================================== ======================== -Functions Return values C functions +Functions Return values C functions ========================== ========================================================== ======================== -:func:`erf(z,rtol_,r_)` :math:`\frac{2}{\sqrt\pi}\int_0^z e^{-t^2} dt` :c:func:`mad_num_erf` -:func:`erfc(z,rtol_,r_)` :math:`1-\operatorname{erf}(z)` :c:func:`mad_num_erfc` -:func:`erfi(z,rtol_,r_)` :math:`-i\operatorname{erf}(i z)` :c:func:`mad_num_erfi` -:func:`erfcx(z,rtol_,r_)` :math:`e^{z^2}\operatorname{erfc}(z)` :c:func:`mad_num_erfcx` -:func:`wf(z,rtol_,r_)` :math:`e^{-z^2}\operatorname{erfc}(-i z)` :c:func:`mad_num_wf` +:func:`erf(z,rtol_,r_)` :math:`\frac{2}{\sqrt\pi}\int_0^z e^{-t^2} dt` :c:func:`mad_num_erf` +:func:`erfc(z,rtol_,r_)` :math:`1-\operatorname{erf}(z)` :c:func:`mad_num_erfc` +:func:`erfi(z,rtol_,r_)` :math:`-i\operatorname{erf}(i z)` :c:func:`mad_num_erfi` +:func:`erfcx(z,rtol_,r_)` :math:`e^{z^2}\operatorname{erfc}(z)` :c:func:`mad_num_erfcx` +:func:`wf(z,rtol_,r_)` :math:`e^{-z^2}\operatorname{erfc}(-i z)` :c:func:`mad_num_wf` :func:`dawson(z,rtol_,r_)` :math:`\frac{-i\sqrt\pi}{2}e^{-z^2}\operatorname{erf}(iz)` :c:func:`mad_num_dawson` ========================== ========================================================== ======================== @@ -147,19 +147,20 @@ Basic functions for arc and cord lengths conversion rely on the following elemen l_{\text{arc}} &= a r = \frac{l_{\text{cord}}}{\operatorname{sinc} \frac{a}{2}} - l_{\text{cord}} &= 2 r \sin \frac{a}{2} = l_{\text{arc}} \operatorname{sinc} \frac{a}{2} + l_{\text{cord}} &= 2 r \sin \frac{a}{2} = l_{\text{arc}} \operatorname{sinc} \frac{a}{2} where :math:`r` stands for the radius and :math:`a` for the angle of the `Circular Sector `_. +The auxiliary projected length used by :func:`arc2len()`, :func:`cord2len()`, :func:`len2arc()` and :func:`len2cord()` is :math:`l_{\text{len}} = l_{\text{cord}} \cos \frac{a}{2}`. ===================== ===================================== Functions Return values ===================== ===================================== :func:`arc2cord(l,a)` :math:`l_{\text{arc}} \operatorname{sinc} \frac{a}{2}` -:func:`arc2len(l,a)` :math:`l_{\text{arc}} \operatorname{sinc} \frac{a}{2}\, \cos a` +:func:`arc2len(l,a)` :math:`l_{\text{arc}} \operatorname{sinc} \frac{a}{2}\, \cos \frac{a}{2}` :func:`cord2arc(l,a)` :math:`\frac{l_{\text{cord}}}{\operatorname{sinc} \frac{a}{2}}` -:func:`cord2len(l,a)` :math:`l_{\text{cord}} \cos a` -:func:`len2arc(l,a)` :math:`\frac{l}{\operatorname{sinc} \frac{a}{2}\, cos a}` -:func:`len2cord(l,a)` :math:`\frac{l}{\cos a}` +:func:`cord2len(l,a)` :math:`l_{\text{cord}} \cos \frac{a}{2}` +:func:`len2arc(l,a)` :math:`\frac{l}{\operatorname{sinc} \frac{a}{2}\, \cos \frac{a}{2}}` +:func:`len2cord(l,a)` :math:`\frac{l}{\cos \frac{a}{2}}` ===================== ===================================== .. ---------------------------------------------- @@ -210,12 +211,12 @@ Functions for logical operators are wrappers to associated logical operators. ================= =============================================================== =============== Functions Return values Operator string ================= =============================================================== =============== -:func:`lfalse()` :const:`true` :const:`"T"` -:func:`ltrue()` :const:`false` :const:`"F"` -:func:`lnot(x)` :math:`\lnot x` :const:`"!"` -:func:`lbool(x)` :math:`\lnot\lnot x` :const:`"!!"` -:func:`land(x,y)` :math:`x \land y` :const:`"&&"` -:func:`lor(x,y)` :math:`x \lor y` :const:`"||"` +:func:`lfalse()` :const:`true` :const:`"T"` +:func:`ltrue()` :const:`false` :const:`"F"` +:func:`lnot(x)` :math:`\lnot x` :const:`"!"` +:func:`lbool(x)` :math:`\lnot\lnot x` :const:`"!!"` +:func:`land(x,y)` :math:`x \land y` :const:`"&&"` +:func:`lor(x,y)` :math:`x \lor y` :const:`"||"` :func:`lnum(x)` :math:`\lnot x\rightarrow 0`, :math:`\lnot\lnot x\rightarrow 1` :const:`"!#"` ================= =============================================================== =============== @@ -259,41 +260,41 @@ Bitwise Functions Functions for bitwise operations are those from the LuaJIT module :mod:`bit` and imported into the module :mod:`MAD.gfunc` for convenience, see http://bitop.luajit.org/api.html for details. Note that all these functions have *value semantic* and normalise their arguments to the numeric range of a 32 bit integer before use. ==================== ==================================================== -Functions Return values +Functions Return values ==================== ==================================================== -:func:`tobit(x)` Return the normalized value of :var:`x` to the range of a 32 bit integer -:func:`tohex(x,n_)` Return the hex string of :var:`x` with :var:`n` digits (:math:`n<0` use caps) -:func:`bnot(x)` Return the bitwise reverse of :var:`x` bits -:func:`band(x,...)` Return the bitwise *AND* of all arguments -:func:`bor(x,...)` Return the bitwise *OR* of all arguments +:func:`tobit(x)` Return the normalized value of :var:`x` to the range of a 32 bit integer +:func:`tohex(x,n_)` Return the hex string of :var:`x` with :var:`n` digits (:math:`n<0` use caps) +:func:`bnot(x)` Return the bitwise reverse of :var:`x` bits +:func:`band(x,...)` Return the bitwise *AND* of all arguments +:func:`bor(x,...)` Return the bitwise *OR* of all arguments :func:`bxor(x,...)` Return the bitwise *XOR* of all arguments -:func:`lshift(x,n)` Return the bitwise left shift of :var:`x` by :var:`n` bits with 0-bit shift-in +:func:`lshift(x,n)` Return the bitwise left shift of :var:`x` by :var:`n` bits with 0-bit shift-in :func:`rshift(x,n)` Return the bitwise right shift of :var:`x` by :var:`n` bits with 0-bit shift-in :func:`arshift(x,n)` Return the bitwise right shift of :var:`x` by :var:`n` bits with sign bit shift-in -:func:`rol(x,n)` Return the bitwise left rotation of :var:`x` by :var:`n` bits -:func:`ror(x,n)` Return the bitwise right rotation of :var:`x` by :var:`n` bits -:func:`bswap(x)` Return the swapped bytes of :var:`x`, i.e. convert big endian to/from little endian +:func:`rol(x,n)` Return the bitwise left rotation of :var:`x` by :var:`n` bits +:func:`ror(x,n)` Return the bitwise right rotation of :var:`x` by :var:`n` bits +:func:`bswap(x)` Return the swapped bytes of :var:`x`, i.e. convert big endian to/from little endian ==================== ==================================================== Flags Functions --------------- -A flag is 32 bit unsigned integer used to store up to 32 binary states with the convention that :const:`0` means disabled/cleared and :const:`1` means enabled/set. Functions on flags are useful aliases to, or combination of, bitwise operations to manipulate their states (i.e. their bits). Flags are mainly used by the object model to keep track of hidden and user-defined states in a compact and efficient format. +A flag is 32 bit unsigned integer used to store up to 32 binary states with the convention that :const:`0` means disabled/cleared and :const:`1` means enabled/set. Functions on flags are useful aliases to, or combination of, bitwise operations to manipulate their states (i.e. their bits). Flags are mainly used by the object model to keep track of hidden and user-defined states in a compact and efficient format. =================== ==================================================== -Functions Return values +Functions Return values =================== ==================================================== :func:`bset(x,n)` Return the flag :var:`x` with state :var:`n` enabled -:func:`bclr(x,n)` Return the flag :var:`x` with state :var:`n` disabled -:func:`btst(x,n)` Return :const:`true` if state :var:`n` is enabled in :var:`x`, :const:`false` otherwise -:func:`fbit(n)` Return a flag with only state :var:`n` enabled +:func:`bclr(x,n)` Return the flag :var:`x` with state :var:`n` disabled +:func:`btst(x,n)` Return :const:`true` if state :var:`n` is enabled in :var:`x`, :const:`false` otherwise +:func:`fbit(n)` Return a flag with only state :var:`n` enabled :func:`fnot(x)` Return the flag :var:`x` with all states flipped :func:`fset(x,...)` Return the flag :var:`x` with disabled states flipped if enabled in any flag passed as argument -:func:`fcut(x,...)` Return the flag :var:`x` with enabled states flipped if disabled in any flag passed as argument +:func:`fcut(x,...)` Return the flag :var:`x` with enabled states flipped if disabled in any flag passed as argument :func:`fclr(x,f)` Return the flag :var:`x` with enabled states flipped if enabled in :var:`f` -:func:`ftst(x,f)` Return :const:`true` if all states enabled in :var:`f` are enabled in :var:`x`, :const:`false` otherwise -:func:`fall(x)` Return :const:`true` if all states are enabled in :var:`x`, :const:`false` otherwise -:func:`fany(x)` Return :const:`true` if any state is enabled in :var:`x`, :const:`false` otherwise +:func:`ftst(x,f)` Return :const:`true` if all states enabled in :var:`f` are enabled in :var:`x`, :const:`false` otherwise +:func:`fall(x)` Return :const:`true` if all states are enabled in :var:`x`, :const:`false` otherwise +:func:`fany(x)` Return :const:`true` if any state is enabled in :var:`x`, :const:`false` otherwise =================== ==================================================== Special Functions @@ -302,21 +303,21 @@ Special Functions The module :mod:`MAD.gfunc` provides some useful functions when passed as argument or composed with other functions. ====================== ==================================================== -Functions Return values +Functions Return values ====================== ==================================================== -:func:`narg(...)` Return the number of arguments -:func:`ident(...)` Return all arguments unchanged, i.e. functional identity -:func:`fnil()` Return :const:`nil`, i.e. functional nil +:func:`narg(...)` Return the number of arguments +:func:`ident(...)` Return all arguments unchanged, i.e. functional identity +:func:`fnil()` Return :const:`nil`, i.e. functional nil :func:`ftrue()` Return :const:`true`, i.e. functional true :func:`ffalse()` Return :const:`false`, i.e. functional false :func:`fzero()` Return :const:`0`, i.e. functional zero -:func:`fone()` Return :const:`1`, i.e. functional one +:func:`fone()` Return :const:`1`, i.e. functional one :func:`first(a)` Return first argument and discard the others :func:`second(a,b)` Return second argument and discard the others -:func:`third(a,b,c)` Return third argument and discard the others -:func:`swap(a,b)` Return first and second arguments swapped and discard the other arguments -:func:`swapv(a,b,...)` Return first and second arguments swapped followed by the other arguments -:func:`echo(...)` Return all arguments unchanged after echoing them on stdout +:func:`third(a,b,c)` Return third argument and discard the others +:func:`swap(a,b)` Return first and second arguments swapped and discard the other arguments +:func:`swapv(a,b,...)` Return first and second arguments swapped followed by the other arguments +:func:`echo(...)` Return all arguments unchanged after echoing them on stdout ====================== ==================================================== C API @@ -364,7 +365,7 @@ These functions are provided for performance reason and compliance with the C AP Return the error function of the :type:`number` :var:`x`. -.. c:function:: num_t mad_num_erfc (num_t x, num_t relerr) +.. c:function:: num_t mad_num_erfc (num_t x, num_t relerr) Return the complementary error function of the :type:`number` :var:`x`. @@ -390,6 +391,6 @@ References .. rubric:: Footnotes .. [#f1] For *true* Functional Programming, see the module :mod:`MAD.lfun`, a binding of the `LuaFun `_ library adapted to the ecosystem of MAD-NG. -.. [#f2] Default: :expr:`v_ = 1`. +.. [#f2] Default: :expr:`v_ = 1`. .. [#f3] Sign and sign1 functions take care of special cases like ±0, ±inf and ±NaN. .. [#f4] Element-wise operators are not available directly in the programming language, here we use the Matlab-like notation for convenience. diff --git a/refman/source/mad_mod_linalg.rst b/refman/source/mad_mod_linalg.rst index 1643c29..fca72cf 100644 --- a/refman/source/mad_mod_linalg.rst +++ b/refman/source/mad_mod_linalg.rst @@ -6,7 +6,7 @@ Linear Algebra ************** -This chapter describes the real :type:`matrix`, complex :type:`cmatrix` and integer :type:`imatrix` objects as supported by MAD-NG. The module for `Vector `_ and `Matrix `_ is not exposed, only the contructors are visible from the :mod:`MAD` environment and thus, matrices are handled directly by their methods or by the generic functions of the same name from the module :mod:`MAD.gmath`. The :type:`imatrix`, i.e. matrix of integers, are mainly used for indexing other types of matrix and therefore supports only a limited subset of the features. Column and row vectors are shortcuts for :math:`[n\times 1]` and :math:`[1\times n]` matrices respectively. Note that :type:`matrix`, :type:`cmatrix` and :type:`imatrix` are all defined as C structures containing their elements in `row-major order `_ for direct compliance with the C API. +This chapter describes the real :type:`matrix`, complex :type:`cmatrix` and integer :type:`imatrix` objects as supported by MAD-NG. The module for `Vector `_ and `Matrix `_ is not exposed, only the contructors are visible from the :mod:`MAD` environment and thus, matrices are handled directly by their methods or by the generic functions of the same name from the module :mod:`MAD.gmath`. The :type:`imatrix`, i.e. matrix of integers, are mainly used for indexing other types of matrix and therefore supports only a limited subset of the features. Column and row vectors are shortcuts for :math:`[n\times 1]` and :math:`[1\times n]` matrices respectively. Note that :type:`matrix`, :type:`cmatrix` and :type:`imatrix` are all defined as C structures containing their elements in `row-major order `_ for direct compliance with the C API. Types promotion =============== @@ -17,21 +17,21 @@ The matrix operations may involve other data types like real and complex numbers Left Operand Type Right Operand Type Result Type ================= ================== =============== :type:`number` :type:`imatrix` :type:`imatrix` -:type:`imatrix` :type:`number` :type:`imatrix` +:type:`imatrix` :type:`number` :type:`imatrix` :type:`imatrix` :type:`imatrix` :type:`imatrix` - -:type:`number` :type:`matrix` :type:`matrix` -:type:`matrix` :type:`number` :type:`matrix` -:type:`matrix` :type:`matrix` :type:`matrix` - + +:type:`number` :type:`matrix` :type:`matrix` +:type:`matrix` :type:`number` :type:`matrix` +:type:`matrix` :type:`matrix` :type:`matrix` + :type:`number` :type:`cmatrix` :type:`cmatrix` -:type:`complex` :type:`matrix` :type:`cmatrix` +:type:`complex` :type:`matrix` :type:`cmatrix` :type:`complex` :type:`cmatrix` :type:`cmatrix` :type:`matrix` :type:`complex` :type:`cmatrix` :type:`matrix` :type:`cmatrix` :type:`cmatrix` -:type:`cmatrix` :type:`number` :type:`cmatrix` +:type:`cmatrix` :type:`number` :type:`cmatrix` :type:`cmatrix` :type:`complex` :type:`cmatrix` -:type:`cmatrix` :type:`matrix` :type:`cmatrix` +:type:`cmatrix` :type:`matrix` :type:`cmatrix` :type:`cmatrix` :type:`cmatrix` :type:`cmatrix` ================= ================== =============== @@ -44,13 +44,13 @@ The constructors for vectors and matrices are directly available from the :mod:` cvector(nrow) ivector(nrow) - Return a real, complex or integer column vector (i.e. a matrix of size :math:`[n_{\text{row}}\times 1]`) filled with zeros. If :var:`nrow` is a table, it is equivalent to :expr:`vector(#nrow):fill(nrow)`. + Return a real, complex or integer column vector (i.e. a matrix of size :math:`[n_{\text{row}}\times 1]`) filled with zeros. If :var:`nrow` is a table, it is equivalent to :expr:`vector(#nrow):fill(nrow)`. .. function:: matrix(nrow, ncol_) cmatrix(nrow, ncol_) imatrix(nrow, ncol_) - Return a real, complex or integer matrix of size :math:`[n_{\text{row}}\times n_{\text{col}}]` filled with zeros. If :var:`nrow` is a table, it is equivalent to :expr:`matrix(#nrow, #nrow[1] or 1):fill(nrow)`, and ignoring :var:`ncol`. Default: :expr:`ncol_ = rnow`. + Return a real, complex or integer matrix of size :math:`[n_{\text{row}}\times n_{\text{col}}]` filled with zeros. If :var:`nrow` is a table, it is equivalent to :expr:`matrix(#nrow, #nrow[1] or 1):fill(nrow)`, and ignoring :var:`ncol`. Default: :expr:`ncol_ = rnow`. .. function:: linspace([start_,] stop, size_) @@ -142,11 +142,11 @@ Sizes and Indexing .. function:: mat:getij (ij_, ri_, rj_) - Return two :type:`ivector` or :var:`ri` and :var:`rj` containing the indexes :expr:`(i,j)` extracted from the :type:`iterable` :var:`ij` for the real, complex or integer matrix :var:`mat`. If :var:`ij` is a number, the two returned items are also numbers. This method is the reverse method of :func:`mat:getidx()` to convert 1D indexes into 2D indexes for the given matrix sizes. Default: :expr:`ij_ = 1..#mat`. + Return two :type:`ivector` or :var:`ri` and :var:`rj` containing the indexes :expr:`(i,j)` extracted from the :type:`iterable` :var:`ij` for the real, complex or integer matrix :var:`mat`. If :var:`ij` is a number, the two returned items are also numbers. This method is the reverse method of :func:`mat:getidx()` to convert 1D indexes into 2D indexes for the given matrix sizes. Default: :expr:`ij_ = range(1,#mat)`. .. function:: mat:getidx (ir_, jc_, rij_) - Return an :type:`ivector` or :var:`rij` containing :expr:`#ir * #jc` vector indexes in row-major order given by the :type:`iterable` :var:`ir` and :var:`jc` of the real, complex or integer matrix :var:`mat`, followed by :var:`ir` and :var:`jc` potentially set from defaults. If both :var:`ir` and :var:`jc` are numbers, it returns a single number. This method is the reverse method of :func:`mat:getij()` to convert 2D indexes into 1D indexes for the given matrix sizes. Default: :expr:`ir_ = 1..nrow`, :expr:`jc_ = 1..ncol`. + Return an :type:`ivector` or :var:`rij` containing :expr:`#ir * #jc` vector indexes in row-major order given by the :type:`iterable` :var:`ir` and :var:`jc` of the real, complex or integer matrix :var:`mat`, followed by :var:`ir` and :var:`jc` potentially set from defaults. If both :var:`ir` and :var:`jc` are numbers, it returns a single number. This method is the reverse method of :func:`mat:getij()` to convert 2D indexes into 1D indexes for the given matrix sizes. Default: :expr:`ir_ = range(1,nrow)`, :expr:`jc_ = range(1,ncol)`. .. function:: mat:getdidx (k_) @@ -173,7 +173,7 @@ Getters and Setters .. function:: mat:getvec (ij_, r_) - Return a column vector or :var:`r` containing the values of the elements at the vector indexes given by the :type:`iterable` :var:`ij` of the real, complex or integer matrix :var:`mat`, i.e. interpreting the matrix as a vector. Default: :expr:`ij_ = 1..#mat`. + Return a column vector or :var:`r` containing the values of the elements at the vector indexes given by the :type:`iterable` :var:`ij` of the real, complex or integer matrix :var:`mat`, i.e. interpreting the matrix as a vector. Default: :expr:`ij_ = range(1,#mat)`. .. function:: mat:setvec (ij_, a, p_, s_) @@ -185,16 +185,16 @@ Getters and Setters - if :var:`a` is a :type:`callable`, then :var:`a` is considered as a *stateless iterator*, and the matrix will be filled with the values :var:`v` returned by iterating :expr:`s, v = a(p, s)`. - Default: :expr:`ij_ = 1..#mat`. + Default: :expr:`ij_ = range(1,#mat)`. .. function:: mat:insvec (ij, a) Return the real, complex or integer matrix :var:`mat` after inserting the elements at the vector indexes given by the :type:`iterable` :var:`ij`, i.e. interpreting the matrix as a vector, with the values given by :var:`a` depending of its kind: - + - if :var:`a` is a :type:`scalar`, it is will be used repetitively. - if :var:`a` is an :type:`iterable` then the matrix will be filled with values from :var:`a[n]` for :expr:`1 <= n <= #a`. - + The elements after the inserted indexes are shifted toward the end of the matrix in row-major order and discarded if they go beyond the last index. .. function:: mat:remvec (ij) @@ -224,17 +224,17 @@ Getters and Setters .. function:: mat:inssub (ir_, jc_, a) Return the real, complex or integer matrix :var:`mat` after inserting elements at the indexes :expr:`(i,j)` given by the :type:`iterable` :var:`ir` and :var:`jc` with the values given by :var:`a` depending of its kind: - + - if :var:`a` is a :type:`scalar`, it is will be used repetitively. - if :var:`a` is an :type:`iterable` then the rows and columns will be filled with values from :var:`a[n]` for :expr:`1 <= n <= #a` and recycled repetitively if :expr:`#a < #ir * #ic`. - + The values after the inserted indexes are pushed toward the end of the matrix, i.e. interpreting the matrix as a vector, and discarded if they go beyond the last index. If :expr:`ir = nil`, :expr:`jc ~= nil` and :var:`a` is a 1D :type:`iterable`, then the latter is used to filled the matrix in the column-major order. Default: as :func:`mat:getidx()`. .. function:: mat:remsub (ir_, jc_) Return the real, complex or integer matrix :var:`mat` after removing the rows and columns at the indexes given by the :type:`iterable` :var:`ir` and :var:`jc` and reshaping the matrix accordingly. Default: as :func:`mat:getidx()`. - + .. function:: mat:swpsub (ir_, jc_, ir2_, jc2_) Return the real, complex or integer matrix :var:`mat` after swapping the elements at indexes given by the iterable :type:`iterable` :var:`ir` and :var:`jc` with the elements at indexes given by :type:`iterable` :var:`ir2` and :var:`jc2`. Default: as :func:`mat:getidx()`. @@ -306,26 +306,26 @@ Cloning and Reshaping Same as :func:`mat:reshape()` except that :var:`nr` must be explicitly provided as this method allows for a larger size than :var:`mat` current size. A typical use of this method is to expand a vector after an explicit shrinkage, while keeping track of its original size, e.g. similar to :expr:`vector(100) :reshape(1):seti(1,1) :_reshapeto(2):seti(2,1)` that would raise an *"index out of bounds"* error without the call to :func:`_reshapeto()`. Default :expr:`nc_ = 1`. - *WARNING: This method is unsafe and may crash MAD-NG with, e.g. a* `Segmentation fault `__ *, if wrongly used. It is the responsibility of the user to ensure that* :var:`mat` *was created with a size greater than or equal to the new size.* + *WARNING: This method is unsafe and may crash MAD-NG with, e.g. a* `Segmentation fault `__ *, if wrongly used. It is the responsibility of the user to ensure that* :var:`mat` *was created with a size greater than or equal to the new size.* Matrix Properties ----------------- .. function:: mat:is_const (tol_) - Return true if all elements are equal within the tolerance :var:`tol`, false otherwise. Default: :expr:`tol_ = 0`. + Return true if all elements are equal within the tolerance :var:`tol`, false otherwise. Default: :expr:`tol_ = 0`. .. function:: mat:is_real (tol_) - Return true if the imaginary part of all elements are equal to zero within the tolerance :var:`tol`, false otherwise. Default: :expr:`tol_ = 0`. + Return true if the imaginary part of all elements are equal to zero within the tolerance :var:`tol`, false otherwise. Default: :expr:`tol_ = 0`. .. function:: mat:is_imag (tol_) - Return true if the real part of all elements are equal to zero within the tolerance :var:`tol`, false otherwise. Default: :expr:`tol_ = 0`. + Return true if the real part of all elements are equal to zero within the tolerance :var:`tol`, false otherwise. Default: :expr:`tol_ = 0`. .. function:: mat:is_diag (tol_) - Return true if all elements off the diagonal are equal to zero within the tolerance :var:`tol`, false otherwise. Default: :expr:`tol_ = 0`. + Return true if all elements off the diagonal are equal to zero within the tolerance :var:`tol`, false otherwise. Default: :expr:`tol_ = 0`. .. function:: mat:is_symm ([tol_,] [sk_,] c_) @@ -384,7 +384,7 @@ Filling and Moving - otherwise :var:`a` is considered as a *generator*, and the matrix will be filled with values returned by calling :expr:`a(mat:get(i,j), i, j)`. - if :var:`a` is an :type:`iterable` then: - + - if :var:`a[1]` is also an :type:`iterable`, the matrix will be filled with the values from :var:`a[i][j]` for :expr:`1 <= i <= nrow` and :expr:`1 <= j <= ncol`, i.e. treated as a 2D container. - otherwise the matrix will be filled with values from :var:`a[n]` for :expr:`1 <= n <= #mat`, i.e. treated as a 1D container. @@ -392,7 +392,7 @@ Filling and Moving .. function:: mat:rev (d_) Reverse the elements of the matrix :var:`mat` according to the direction :var:`d`: - + - If :expr:`d = 'vec'`, it reverses the entire matrix. - If :expr:`d = 'row'`, it reverses each row. - If :expr:`d = 'col'`, it reverses each column. @@ -402,7 +402,7 @@ Filling and Moving .. function:: mat:roll (nr_, nc_) - Return the real, complex or integer matrix :var:`mat` after rolling its rows by :var:`nr` :math:`\in \mathbb{Z}` and then columns by :var:`nc` :math:`\in \mathbb{Z}`. Default: :expr:`nr_ = 0`, :expr:`nc_ = 0`. + Return the real, complex or integer matrix :var:`mat` after rolling its rows by :var:`nr` :math:`\in \mathbb{Z}` and then columns by :var:`nc` :math:`\in \mathbb{Z}`. Default: :expr:`nr_ = 0`, :expr:`nc_ = 0`. .. function:: mat:movev (i, j, k, r_) @@ -419,11 +419,11 @@ Mapping and Folding .. function:: mat:foreach ([ij_,] f) - Return the real, complex or integer matrix :var:`mat` after applying the :type:`callable` :var:`f` to the elements at the indexes given by the :type:`iterable` :var:`ij` using :expr:`f(mat[n], n)`, i.e. interpreting the matrix as a vector. Default: :expr:`ij_ = 1..#mat`. + Return the real, complex or integer matrix :var:`mat` after applying the :type:`callable` :var:`f` to the elements at the indexes given by the :type:`iterable` :var:`ij` using :expr:`f(mat[n], n)`, i.e. interpreting the matrix as a vector. Default: :expr:`ij_ = range(1,#mat)`. .. function:: mat:filter ([ij_,] p, r_) - Return a matrix or :var:`r` filled with the values of the elements of the real, complex or integer matrix :var:`mat` at the indexes given by the :type:`iterable` :var:`ij` if they are selected by the :type:`callable` `predicate `_ :var:`p` using :expr:`p(mat[n], n) = true`, i.e. interpreting the matrix as a vector. This method returns next to the matrix, a :type:`table` if :var:`r` is a table or a :type:`ivector` otherwise, containing the indexes of the selected elements returned. Default: :expr:`ij_ = 1..#mat`. + Return a matrix or :var:`r` filled with the values of the elements of the real, complex or integer matrix :var:`mat` at the indexes given by the :type:`iterable` :var:`ij` if they are selected by the :type:`callable` `predicate `_ :var:`p` using :expr:`p(mat[n], n) = true`, i.e. interpreting the matrix as a vector. This method returns next to the matrix, a :type:`table` if :var:`r` is a table or a :type:`ivector` otherwise, containing the indexes of the selected elements returned. Default: :expr:`ij_ = range(1,#mat)`. .. function:: mat:filter_out ([ij_,] p, r_) @@ -431,7 +431,7 @@ Mapping and Folding .. function:: mat:map ([ij_,] f, r_) - Return a matrix or :var:`r` filled with the values returned by the :type:`callable` (or the operator string) :var:`f` applied to the elements of the real, complex or integer matrix :var:`mat` at the indexes given by the :type:`iterable` :var:`ij` using :expr:`f(mat[n], n)`, i.e. interpreting the matrix as a vector. If :expr:`r = 'in'` or :expr:`r = nil` and :expr:`ij ~= nil` then it is assigned :var:`mat`, i.e. map in place. If :expr:`r = nil` still, then the type of the returned matrix is determined by the type of the value returned by :func:`f()` called once before mapping. Default: :expr:`ij_ = 1..#mat`. + Return a matrix or :var:`r` filled with the values returned by the :type:`callable` (or the operator string) :var:`f` applied to the elements of the real, complex or integer matrix :var:`mat` at the indexes given by the :type:`iterable` :var:`ij` using :expr:`f(mat[n], n)`, i.e. interpreting the matrix as a vector. If :expr:`r = 'in'` or :expr:`r = nil` and :expr:`ij ~= nil` then it is assigned :var:`mat`, i.e. map in place. If :expr:`r = nil` still, then the type of the returned matrix is determined by the type of the value returned by :func:`f()` called once before mapping. Default: :expr:`ij_ = range(1,#mat)`. .. function:: mat:map2 (y, [ij_,] f, r_) @@ -439,7 +439,7 @@ Mapping and Folding .. function:: mat:map3 (y, z, [ij_,] f, r_) - Equivalent to :func:`mat:map()` but with three arguments passed to :var:`f`, i.e. using :expr:`f(mat[n], y[n], z[n], n)`. Note that :var:`f` cannot be an operator string, as only unary and binary operators are avalaible in such form. + Equivalent to :func:`mat:map()` but with three arguments passed to :var:`f`, i.e. using :expr:`f(mat[n], y[n], z[n], n)`. Note that :var:`f` cannot be an operator string, as only unary and binary operators are avalaible in such form. .. function:: mat:foldl (f, [x0_,] [d_,] r_) @@ -691,7 +691,7 @@ Operator-like Methods .. function:: mat:tmul (mat2, r_) Equivalent to :expr:`mat:t() * mat2` with the possibility to place the result in :var:`r`. - + .. function:: mat:mult (mat2, r_) Equivalent to :expr:`mat * mat2:t()` with the possibility to place the result in :var:`r`. @@ -699,7 +699,7 @@ Operator-like Methods .. function:: mat:dmul (mat2, r_) Equivalent to :expr:`mat:getdiag():diag() * mat2` with the possibility to place the result in :var:`r`. If :var:`mat` is a vector, it will be interpreted as the diagonal of a square matrix like in :func:`mat:diag()`, i.e. omitting :func:`mat:getdiag()` is the previous expression. - + .. function:: mat:muld (mat2, r_) Equivalent to :expr:`mat * mat2:getdiag():diag()` with the possibility to place the result in :var:`r`. If :var:`mat2` is a vector, it will be interpreted as the diagonal of a square matrix like in :func:`mat2:diag()`, i.e. omitting :func:`mat2:getdiag()` is the previous expression. @@ -710,7 +710,7 @@ Operator-like Methods .. function:: mat:inv ([r_,] rcond_) - Equivalent to :expr:`mat.div(1, mat, r_, rcond_)`. + Equivalent to :expr:`mat.div(1, mat, r_, rcond_)`. .. function:: mat:pinv ([r_,] [rcond_,] ncond_) @@ -729,9 +729,9 @@ Operator-like Methods Equivalent to :expr:`mat .. mat2` with the possibility to place the result in :var:`r` and to specify the direction of the concatenation: - If :expr:`d = 'vec'`, it concatenates the matrices (appended as vectors) - - If :expr:`d = 'row'`, it concatenates the rows (horizontal) + - If :expr:`d = 'row'`, it concatenates the rows (horizontal) - If :expr:`d = 'col'`, it concatenates the columns (vectical) - + Default: :var:`d_ = 'row'`. Special Methods @@ -779,7 +779,7 @@ Special Methods .. function:: mat:center (d_) Return the centered matrix :var:`mat` to have zero mean equivalent to :expr:`mat:sub(mat:mean(),mat)`. The direction :var:`d` indicates how the centering must be performed: - + - If :expr:`d = 'vec'`, it centers the entire matrix by substracting its mean. - If :expr:`d = 'row'`, it centers each row by substracting their mean. - If :expr:`d = 'col'` , it centers each column by substracting their mean. @@ -872,7 +872,7 @@ Solvers and Decompositions .. function:: mat:eigen (vr_, vl_) - Return the complex vector filled with the eigenvalues followed by the by the status :var:`info` and the two optional real or complex matrices :var:`vr` and :var:`vl` containing the right and the *transposed* left eigenvectors resulting from the `Eigen Decomposition `_ of the real or complex square matrix :var:`mat`. The eigenvectors are normalized to have unit Euclidean norm and their largest component real, and satisfy :math:`A v_r = \lambda v_r` and :math:`v_l^\tau A = \lambda v_l^\tau`. + Return the complex vector filled with the eigenvalues followed by the by the status :var:`info` and the two optional real or complex matrices :var:`vr` and :var:`vl` containing the right and left eigenvectors resulting from the `Eigen Decomposition `_ of the real or complex square matrix :var:`mat`. The eigenvectors are normalized to have unit Euclidean norm and their largest component real, and satisfy :math:`A v_r = \lambda v_r` and :math:`A^\tau v_l = \lambda v_l`. .. function:: mat:det () @@ -910,7 +910,7 @@ The methods described is this section are based on the `FFTW ` .. function:: mat:nfft (p_, r_) - Return the complex vector, matrix or :var:`r` resulting from the 1D or 2D *Nonequispaced* `Fourier Transform `_ of the real or complex vector or matrix :var:`mat` respectively at :var:`p` time nodes. + Return the complex vector, matrix or :var:`r` resulting from the 1D or 2D *Nonequispaced* `Fourier Transform `_ of the real or complex vector or matrix :var:`mat` respectively at :var:`p` time nodes. .. function:: mat:infft (p_, r_) @@ -932,10 +932,10 @@ The methods described is this section are based on the `FFTW ` Return the real or complex vector or matrix resulting from the zero padding of the matrix :var:`mat` extended to the sizes :var:`nr` and :var:`nc`, following the direction :var:`d`: - - If :expr:`d = 'vec'`, it pads the zeros at the end of the matrix equivalent :expr:`x:same(nr,nc) :setvec(1..#x,x)`, i.e. interpreting the matrix as a vector. - - If :expr:`d = 'row'`, it pads the zeros at the end of the rows equivalent :expr:`x:same(x.nrow,nc) :setsub(1..x.nrow,1..x.ncol,x)`, i.e. ignoring :var:`nr`. - - If :expr:`d = 'col'`, it pads the zeros at the end of the columns equivalent :expr:`x:same(nr,x.ncol) :setsub(1..x.nrow,1..x.ncol,x)`, i.e. ignoring :var:`nc`. - - otherwise, it pads the zeros at the end of the rows and the columns equivalent to :expr:`x:same(nr,nc) :setsub(1..x.nrow,1..x.ncol,x)`. + - If :expr:`d = 'vec'`, it pads the zeros at the end of the matrix equivalent to :expr:`x:same(nr,nc):setvec(range(1,#x),x)`, i.e. interpreting the matrix as a vector. + - If :expr:`d = 'row'`, it pads the zeros at the end of the rows equivalent to :expr:`x:same(x.nrow,nc):setsub(range(1,x.nrow),range(1,x.ncol),x)`, i.e. ignoring :var:`nr`. + - If :expr:`d = 'col'`, it pads the zeros at the end of the columns equivalent to :expr:`x:same(nr,x.ncol):setsub(range(1,x.nrow),range(1,x.ncol),x)`, i.e. ignoring :var:`nc`. + - otherwise, it pads the zeros at the end of the rows and the columns equivalent to :expr:`x:same(nr,nc):setsub(range(1,x.nrow),range(1,x.ncol),x)`. If the zero padding does not change the size of :var:`mat`, the orignal :var:`mat` is returned unchanged. @@ -1006,7 +1006,7 @@ Conversions .. function:: mat:totable ([d_,] r_) - Return the table or :var:`r` containing the real, complex or integer matrix converted to tables, i.e. one per row unless :var:`mat` is a vector or the direction :expr:`d = 'vec'`. + Return the table or :var:`r` containing the real, complex or integer matrix converted to a table. Default: :expr:`d = 'vec'`, i.e. the matrix is flattened in row-major order. If :var:`mat` is not a vector and :expr:`d ~= 'vec'`, the result is a table of rows. Input and Output ---------------- @@ -1117,7 +1117,7 @@ Operators mat / num mat / mat2 - Return a :type:`matrix` resulting from the division of the left and right operands that must have compatible sizes. If the right operand is a scalar, the operator will be applied individually to all elements of the matrix. If the left operand is a scalar the operation :expr:`x/Y` is converted to :expr:`x (I/Y)` where :var:`I` is the identity matrix with compatible sizes. If the right operand is a matrix, the operation :expr:`X/Y` is performed using a system solver based on LU, QR or LQ factorisation depending on the shape of the system. + Return a :type:`matrix` resulting from the division of the left and right operands that must have compatible sizes. If the right operand is a scalar, the operator will be applied individually to all elements of the matrix. If the left operand is a scalar the operation :expr:`x/Y` is converted to :expr:`x (I/Y)` where :var:`I` is the identity matrix with compatible sizes. If the right operand is a matrix, the operation :expr:`X/Y` is performed using a system solver based on LU, QR or LQ factorisation depending on the shape of the system. .. function:: num / cmat cpx / mat @@ -1161,7 +1161,7 @@ Operators num == cmat num == imat cpx == mat - cpx == cmat + cpx == cmat mat == num mat == cpx mat == mat2 @@ -1199,12 +1199,12 @@ Iterators .. function:: ipairs(mat) :noindex: - Return an :type:`ipairs` iterator suitable for generic :const:`for` loops. The returned values are those given by :func:`mat[i]`. + Return an :type:`ipairs` iterator suitable for generic :const:`for` loops. The returned values are those given by :func:`mat[i]`. C API ===== -This C Application Programming Interface describes only the C functions declared in the scripting language and used by the higher level functions and methods presented before in this chapter. For more functions and details, see the C headers. The :const:`const` vectors and matrices are inputs, while the non-:const:`const` vectors and matrices are outpouts or are modified *inplace*. +This C Application Programming Interface describes only the C functions declared in the scripting language and used by the higher level functions and methods presented before in this chapter. For more functions and details, see the C headers. The :const:`const` vectors and matrices are inputs, while the non-:const:`const` vectors and matrices are outpouts or are modified *inplace*. Vector ------ @@ -1302,7 +1302,7 @@ Vector .. c:function:: void mad_cvec_conj (const cpx_t x[], cpx_t r[], ssz_t n) - Return in :var:`r` the conjugate of the complex vector :var:`x` of size :var:`n`. + Return in :var:`r` the conjugate of the complex vector :var:`x` of size :var:`n`. .. c:function:: void mad_vec_abs (const num_t x[], num_t r[], ssz_t n) void mad_cvec_abs (const cpx_t x[], num_t r[], ssz_t n) @@ -1405,12 +1405,12 @@ Matrix void mad_cmat_rev (cpx_t x[], ssz_t m, ssz_t n, int d) void mad_imat_rev (idx_t x[], ssz_t m, ssz_t n, int d) - Reverse in place the matrix :var:`x` following the direction :expr:`d in {0,1,2,3}` for respectively the entire matrix, each row, each column and the diagonal. + Reverse in place the matrix :var:`x` following the direction :expr:`d in {0,1,2,3}` for respectively the entire matrix, each row, each column and the diagonal. .. c:function:: void mad_mat_center (num_t x[], ssz_t m, ssz_t n, int d) void mad_cmat_center (cpx_t x[], ssz_t m, ssz_t n, int d) - Center in place the matrix :var:`x` following the direction :expr:`d in {0,1,2,3}` for respectively the entire matrix, each row, each column and the diagonal. + Center in place the matrix :var:`x` following the direction :expr:`d in {0,1,2,3}` for respectively the entire matrix, each row, each column and the diagonal. .. c:function:: void mad_mat_roll (num_t x[], ssz_t m, ssz_t n, int mroll, int nroll) void mad_cmat_roll (cpx_t x[], ssz_t m, ssz_t n, int mroll, int nroll) @@ -1533,7 +1533,7 @@ Matrix .. c:function:: int mad_mat_eigen (const num_t x[], cpx_t w[], num_t vl[], num_t vr[], ssz_t n) int mad_cmat_eigen (const cpx_t x[], cpx_t w[], cpx_t vl[], cpx_t vr[], ssz_t n) - Fill the column vector :var:`w` of size :var:`n` with the eigenvalues followed by the status :var:`info` and the two optional matrices :var:`vr` and :var:`vl` of sizes :expr:`[n, n]` containing the left and right eigenvectors resulting from the `Eigen Decomposition `_ of the square matrix :var:`x` of sizes :expr:`[n, n]`. The eigenvectors are normalized to have unit Euclidean norm and their largest component real, and satisfy :math:`X v_r = \lambda v_r` and :math:`v_l X = \lambda v_l`. + Fill the column vector :var:`w` of size :var:`n` with the eigenvalues followed by the status :var:`info` and the two optional matrices :var:`vr` and :var:`vl` of sizes :expr:`[n, n]` containing the right and left eigenvectors resulting from the `Eigen Decomposition `_ of the square matrix :var:`x` of sizes :expr:`[n, n]`. The eigenvectors are normalized to have unit Euclidean norm and their largest component real, and satisfy :math:`X v_r = \lambda v_r` and :math:`X^\tau v_l = \lambda v_l`. .. c:function:: int mad_mat_det (const num_t x[], num_t *r, ssz_t n) int mad_cmat_det (const cpx_t x[], cpx_t *r, ssz_t n) @@ -1566,12 +1566,12 @@ Matrix .. c:function:: void mad_mat_sympconj (const num_t x[], num_t r[], ssz_t n) void mad_cmat_sympconj(const cpx_t x[], cpx_t r[], ssz_t n) - Return in :var:`r` the symplectic 'conjugate' of the vector :var:`x` of size :var:`n`. + Return in :var:`r` the symplectic 'conjugate' of the vector :var:`x` of size :var:`n`. .. c:function:: num_t mad_mat_symperr (const num_t x[], num_t r_[], ssz_t n, num_t *tol_) num_t mad_cmat_symperr (const cpx_t x[], cpx_t r_[], ssz_t n, num_t *tol_) - Return the norm of the symplectic error and fill the optional matrix :var:`r` with the symplectic deviation of the matrix :var:`x`. The optional argument :var:`tol` is used as the tolerance to check if the matrix :var:`x` is symplectic or not, and saves the result as :const:`0` (non-symplectic) or :const:`1` (symplectic) within tol for output. + Return the norm of the symplectic error and fill the optional matrix :var:`r` with the symplectic deviation of the matrix :var:`x`. The optional argument :var:`tol` is used as the tolerance to check if the matrix :var:`x` is symplectic or not, and saves the result as :const:`0` (non-symplectic) or :const:`1` (symplectic) within tol for output. .. c:function:: void mad_vec_dif (const num_t x[], const num_t y[], num_t r[], ssz_t n) void mad_vec_difv (const num_t x[], const cpx_t y[], cpx_t r[], ssz_t n) @@ -1654,7 +1654,7 @@ References .. [#f1] For *true* Functional Programming, see the module :mod:`MAD.lfun`, a binding of the `LuaFun `_ library adapted to the ecosystem of MAD-NG. -.. [#f2] The solvers are based, among others, on the following Lapack drivers: +.. [#f2] The solvers are based, among others, on the following Lapack drivers: - :func:`dgesv()` and :func:`zgesv()` for LU factorization. - :func:`dgelsy()` and :func:`zgelsy()` for QR or LQ factorization. @@ -1663,4 +1663,4 @@ References - :func:`dgglse()` and :func:`zgglse()` for equality-constrained linear Least Squares problems. - :func:`dggglm()` and :func:`zggglm()` for general Gauss-Markov linear model problems. -.. [#f3] MICADO stands for "Minimisation des CArrés des Distortions d'Orbite" in french. +.. [#f3] MICADO stands for "Minimisation des CArrés des Distortions d'Orbite" in french. diff --git a/refman/source/mad_mod_miscfuns.rst b/refman/source/mad_mod_miscfuns.rst index fa2fbe5..ed52eca 100644 --- a/refman/source/mad_mod_miscfuns.rst +++ b/refman/source/mad_mod_miscfuns.rst @@ -133,6 +133,8 @@ Generic Functions .. function:: totable (a, ...) + Return :var:`a` converted to a :type:`table`. Tables are returned unchanged, scalars become single-item tables, objects with tablable semantic delegate to their :expr:`__totable` metamethod, and iterables are collected into a list. This generic function therefore forwards to object-specific conversions such as :func:`mat:totable()`, :func:`rng:totable()` or :func:`mono:totable()`. + .. function:: toboolean (a) Special Functions @@ -145,5 +147,3 @@ Special Functions .. function:: runonce (fun, ...) .. function:: collectlocal (fun_, env_) - - diff --git a/refman/source/mad_mod_monomial.rst b/refman/source/mad_mod_monomial.rst index f1486dc..760e767 100644 --- a/refman/source/mad_mod_monomial.rst +++ b/refman/source/mad_mod_monomial.rst @@ -5,7 +5,7 @@ Monomials ********* -This chapter describes `Monomial `_ objects useful to encode the variables powers of `Multivariate `_ `Taylor Series `_ used by the `Differential Algebra `_ library of MAD-NG. The module for monomials is not exposed, only the contructor is visible from the :mod:`MAD` environment and thus, monomials must be handled directly by their methods. Monomial objects do not know to which variables the stored orders belong, the relationship is only through the indexes. Note that monomials are objects with reference semantic that store variable orders as 8-bit unsigned integers, thus arithmetic on variable orders occurs in the ring :math:`\mathbb{N}/2^8\mathbb{N}`. +This chapter describes `Monomial `_ objects useful to encode the variables powers of `Multivariate `_ `Taylor Series `_ used by the `Differential Algebra `_ library of MAD-NG. The module for monomials is not exposed, only the contructor is visible from the :mod:`MAD` environment and thus, monomials must be handled directly by their methods. Monomial objects do not know to which variables the stored orders belong, the relationship is only through the indexes. Note that monomials are objects with reference semantic that store variable orders as 8-bit unsigned integers, thus arithmetic on variable orders occurs in the ring :math:`\mathbb{N}/2^8\mathbb{N}`. Constructors ============ @@ -48,9 +48,9 @@ The optional argument :var:`r_` represents a destination placeholder for results Return :var:`mono` with the variable orders set to the values given by :var:`ord`. Default: :expr:`ord_ = 0`. - If :var:`ord` is a :type:`number` then all variable orders are set to the value of :var:`ord`. - + - If :var:`ord` is a :type:`list` then all variable orders are set to the values given by :var:`ord`. - + - If :var:`ord` is a :type:`string` then all variable orders are set to the values given by :var:`ord`, where each character in the set :const:`[0-9A-Za-z]` is interpreted as a variable order in the `Basis 62 `_, e.g. the string :const:`"Bc"` will be interpreted as a monomial with variable orders 11 and 38. Characters not in the set :const:`[0-9A-Za-z]` are not allowed and lead to an undefined behavior, meaning that orders :math:`\ge 62` cannot be safely specified through strings. .. function:: mono:min() @@ -61,17 +61,25 @@ The optional argument :var:`r_` represents a destination placeholder for results Return the maximum variable order of :var:`mono`. -.. function:: mono:ord() +.. function:: mono:ord([n_ [, o_]]) - Return the order of :var:`mono`, that is the sum of all the variable orders. + Return the sum of the variable orders of :var:`mono` over the slice starting + at the zero-based offset :var:`o_` and ending at the inclusive upper bound + :var:`n_`. Default: :expr:`n_ = #mono`, :expr:`o_ = 0`. -.. function:: mono:ordp(step_) +.. function:: mono:ordp([n_ [, o_ [, step_]]]) - Return the product of the variable orders of :var:`mono` at every :var:`step`. Default: :expr:`step_ = 1`. + Return the product of the variable orders of :var:`mono` over the slice + starting at the zero-based offset :var:`o_`, ending at the inclusive upper + bound :var:`n_`, and sampled every :var:`step_`. Default: + :expr:`n_ = #mono`, :expr:`o_ = 0`, :expr:`step_ = 1`. -.. function:: mono:ordpf(step_) +.. function:: mono:ordpf([n_ [, o_ [, step_]]]) - Return the product of the factorial of the variable orders of :var:`mono` at every :var:`step`. Default: :expr:`step_ = 1`. + Return the product of the factorials of the variable orders of :var:`mono` + over the slice starting at the zero-based offset :var:`o_`, ending at the + inclusive upper bound :var:`n_`, and sampled every :var:`step_`. Default: + :expr:`n_ = #mono`, :expr:`o_ = 0`, :expr:`step_ = 1`. .. function:: mono:add(mono2, r_) @@ -142,14 +150,14 @@ Iterators .. function:: ipairs(mono) :noindex: - Return an :type:`ipairs` iterator suitable for generic :const:`for` loops. The generated values are those returned by :func:`mono[i]`. + Return an :type:`ipairs` iterator suitable for generic :const:`for` loops. The generated values are those returned by :func:`mono[i]`. C API ===== .. c:type:: ord_t - The variable order type, which is an alias for 8-bit unsigned integer. In the C API, monomials are arrays of variable orders with their size :var:`n` tracked separately, i.e. :var:`a[n]`. + The variable order type, which is an alias for 8-bit unsigned integer. In the C API, monomials are arrays of variable orders with their size :var:`n` tracked separately, i.e. :var:`a[n]`. .. c:function:: ssz_t mad_mono_str (ssz_t n, ord_t a[n], str_t s) diff --git a/refman/source/mad_mod_numrange.rst b/refman/source/mad_mod_numrange.rst index 0e11c5c..8498a55 100644 --- a/refman/source/mad_mod_numrange.rst +++ b/refman/source/mad_mod_numrange.rst @@ -10,12 +10,7 @@ This chapter describes :type:`range` and :type:`logrange` objects that are usefu Constructors ============ -The constructors for :type:`range` and :type:`logrange` are directly available from the :mod:`MAD` environment, except for the special case of the concatenation operator applied to two or three :type:`number`, which is part of the language definition as a MAD-NG extension. The :type:`logrange` behave as a the :type:`range` but they work on logarithmic scale. All constructor functions adjust the value of :var:`step` to ensure stable sizes and iterators across platforms (see the method :func:`adjust` for details). - -.. constant:: start..stop - start..stop..step - - The concatenation operator applied to two or three numbers creates a :type:`range` and does not perform any adjustment of :var:`step`. The default step for the first form is one. +The constructors for :type:`range` and :type:`logrange` are directly available from the :mod:`MAD` environment. Literal strings of the form :const:`"a..b"` or :const:`"a..b..c"` are produced by :func:`rng:tostring()` and decoded by :func:`torange()`, but the operator :const:`..` itself is not a range constructor. The :type:`logrange` behaves like :type:`range` on a logarithmic scale. All constructor functions adjust the value of :var:`step` to ensure stable sizes and iterators across platforms (see the method :func:`adjust` for details). .. function:: range([start_,] stop, step_) @@ -56,19 +51,16 @@ Attributes ========== .. constant:: rng.start - rng.logstart + rng.stop + rng.step - The component *start* of the :type:`range` and the :type:`logrange` on a linear scale. + The linear-scale components of a :type:`range`. For a :type:`logrange`, use :func:`rng:ranges()` to retrieve the linear-scale triple. -.. constant:: rng.stop +.. constant:: rng.logstart rng.logstop - - The component *stop* of the :type:`range` and the :type:`logrange` on a linear scale. - -.. constant:: rng.step rng.logstep - The component *step* of the :type:`range` and the :type:`logrange` on a linear scale, which may slighlty differ from the value provided to the constructors due to adjustment. + The logarithmic-scale components of a :type:`logrange`. They store :math:`\log(\text{start})`, :math:`\log(\text{stop})` and :math:`\log(\text{step})` respectively. Functions ========= @@ -101,7 +93,7 @@ Unless specified, the object :var:`rng` that owns the methods represents either .. function:: rng:ranges() - Return the values of :var:`start`, :var:`stop` and :var:`step`, fully characterising the range :var:`rng`. + Return the values of :var:`start`, :var:`stop` and :var:`step`, fully characterising the range :var:`rng`. For :type:`logrange`, these are returned on the linear scale. .. function:: rng:size() @@ -109,15 +101,15 @@ Unless specified, the object :var:`rng` that owns the methods represents either .. function:: rng:value(x) - Return the interpolated value at :var:`x`, i.e. interpreting the range :var:`rng` as a (log)line with equation :expr:`start + x * step`. + Return the interpolated value at :var:`x`. For :type:`range` this is :expr:`start + x * step`. For :type:`logrange` this is :expr:`\exp(logstart + x * logstep)`. .. function:: rng:get(x) - - Return :func:`rng:value(x)` if the result is inside the range's bounds, :const:`nil` otherwise. + + Return :func:`rng:value(x)` if the result is inside the range's bounds, :const:`nil` otherwise. .. function:: rng:last() - Return the last value inside the bounds of the range :var:`rng`, :const:`nil` otherwise. + Return the last value inside the bounds of the range :var:`rng`, :const:`nil` otherwise. .. function:: rng:adjust() @@ -128,7 +120,7 @@ Unless specified, the object :var:`rng` that owns the methods represents either - :expr:`#range(start, stop, step) == size` - :expr:`nrange(start, stop, size):step() == step` - :expr:`range (start, stop, step):value(size-1) == stop` - + The maximum adjustment is :expr:`step = step * (1-eps)^2`, beyond this value it is the user reponsibility to provide better inputs. .. function:: rng:bounds() @@ -138,7 +130,7 @@ Unless specified, the object :var:`rng` that owns the methods represents either .. function:: rng:overlap(rng2) Return :const:`true` if :var:`rng` and :var:`rng2` overlap, i.e. have intersecting bounds, :const:`false` otherwise. - + .. function:: rng:reverse() Return a range which is the reverse of the range :var:`rng`, i.e. swap :var:`start` and :var:`stop`, and reverse :var:`step`. @@ -188,12 +180,12 @@ Operators .. function:: -rng - Equivalent to :expr:`rng:unm()`. + Equivalent to :expr:`rng:unm()`. .. function:: rng + num num + rng - Equivalent to :expr:`rng:add(num)`. + Equivalent to :expr:`rng:add(num)`. .. function:: rng - num @@ -222,4 +214,4 @@ Iterators .. function:: ipairs(rng) :noindex: - Return an :type:`ipairs` iterator suitable for generic :const:`for` loops. The generated values are those returned by :func:`rng:value(i)`. + Return an :type:`ipairs` iterator suitable for generic :const:`for` loops. The generated values are those returned by :func:`rng:value(i)`.