\documentclass{article}
\usepackage[affil-it]{authblk}
\usepackage{graphicx}
\usepackage[space]{grffile}
\usepackage{latexsym}
\usepackage{textcomp}
\usepackage{longtable}
\usepackage{tabulary}
\usepackage{booktabs,array,multirow}
\usepackage{amsfonts,amsmath,amssymb}
\providecommand\citet{\cite}
\providecommand\citep{\cite}
\providecommand\citealt{\cite}
% You can conditionalize code for latexml or normal latex using this.
\newif\iflatexml\latexmlfalse
\AtBeginDocument{\DeclareGraphicsExtensions{.pdf,.PDF,.eps,.EPS,.png,.PNG,.tif,.TIF,.jpg,.JPG,.jpeg,.JPEG}}
\usepackage[utf8]{inputenc}
\iflatexml
\documentclass[11pt,a4paper,twoside]{report}
\fi
\usepackage{xspace}
\usepackage[dvipsnames,svgnames]{xcolor}
% \usepackage{a4wide} % Not (yet) supported by LaTeXML.
\usepackage{amsmath}
% \usepackage[english]{babel} % Not (yet) supported by LaTeXML.
\usepackage{graphicx}
\usepackage{multirow}
\usepackage{longtable}
% \usepackage{parskip} % Not (yet) supported by LaTeXML.
\usepackage{float}
\usepackage{makeidx}
\usepackage{color}
% \usepackage[totoc]{idxlayout} % Not (yet) supported by LaTeXML.
\usepackage{hyperref}
% \usepackage{madstyle} % Not (yet) supported by LaTeXML.
\includeonly{
coverpage, copyright, changelog, contributors,
conventions, format, programflow, control, files, tables, beams, seqedit,
definitions, elements, ranges, line, sequence,
tfs, c6t, sxf, plot, index, rplot_index,
survey, twiss, match, emit, aperture, makethin, error, cororbit, sodd, touschek, ibs, thintrack,
ptc_general, ptc_track, ptc_twiss, ptc_normal, ptc_auxiliaries,
defects, pitfalls
}
\hypersetup{pdfauthor={Ghislain Roy},
pdftitle={MAD-X User's Guide},
colorlinks,
citecolor=blue, linkcolor=blue}
\hyperbaseurl{http://madx.web.cern.ch/madx/madX/doc/usrguide/}
\makeindex
\begin{document}
\title{MADX Demo: Control}
\author{Deyan Ginev}
\affil{Affiliation not available}
\date{\today}
\maketitle
\include{coverpage}
\include{copyright}
\tableofcontents
\newpage
\listoftables
\listoffigures
\part{Control}
\chapter{Conventions}
\label{chap:conventions}
\index{conventions}
\section{Reference System}
\label{sec:reference}
\index{reference!system}
\index{reference!orbit}
\index{local coordinates}
\index{coordinates!local}
The accelerator and/or beam line to be studied is described as a
sequence of beam elements placed sequentially along a reference
orbit.
The reference orbit is the path of a charged particle having the
central design momentum of the accelerator through idealised magnets
with no fringe fields (see Figure~\ref{F-REF}).\selectlanguage{english}
\begin{figure}[h!]
\begin{center}
\includegraphics[width=0.70\columnwidth]{figures/FREF/default-figure}
\caption{{\label{F-REF} Local Reference System%
}}
\end{center}
\end{figure}
The reference orbit consists of a series of straight line segments and
circular arcs. It is defined under the assumption that all elements are
perfectly aligned. The accompanying tripod of the reference orbit spans
a local curvilinear right handed coordinate system {\it (x,y,s)} The
local {\it s}-axis is the tangent to the reference orbit. The two
other axes are perpendicular to the reference orbit and are labelled
{\it x} (in the bend plane) and {\it y} (perpendicular to the bend
plane).
\section{Closed Orbit}
\label{sec:closed_orbit}
Due to various errors like misalignment errors, field errors, fringe
fields etc., the closed orbit does not coincide with the reference
orbit. The closed orbit also changes with the momentum error.
The closed orbit is described with respect to the reference orbit, using
the local reference system ({\it x, y, s}). It is evaluated including
any nonlinear effects.
\madxalso computes the betatron and synchrotron oscillations with respect
to the closed orbit. Results are given in the local ({\it x, y,
s})-system defined by the reference orbit.
\section{Global Reference System}
\label{sec:global_ref}
The global reference orbit of the accelerator is
uniquely defined by the sequence of physical elements. The local
reference system ({\it x, y, s}) may thus be
referred to a global Cartesian coordinate system ({\it X, Y, Z})
(see Figure~\ref{F-GLOB}).
The positions between beam elements are indexed with $i=0,\ldots n$.
The local reference system ({$x_i$, $y_i$, $s_i$}) at position
{\it i}, i.e. the displacement and direction of the reference orbit
with respect to the system ({\it X, Y, Z}) are
defined by three displacements ($X_i$, $Y_i$, $Z_i$) and three angles
($\theta_i$, $\phi_i$, $\psi_i$)\selectlanguage{english}
\begin{figure}[h!]
\begin{center}
\includegraphics[width=0.70\columnwidth]{figures/FGLOB/default-figure}
\caption{{\label{F-GLOB} Global Reference System showing the global
Cartesian system ($X, Y, Z$) in black and the local reference system ($x, y,
s$) in red after translation ($X_i , Y_i, Z_i$) and rotation ($\theta_i,
\phi_i, \psi_i$). The projections of the local reference system axes onto the
horizontal $ZX$ plane of the Cartesian system are figured with blue dashed
lines. The intersections of planes $ys$, $xy$ and $xs$ of the local reference
system with the horizontal $ZX$ plane of the Cartesian system are figured in
green dashed lines.%
}}
\end{center}
\end{figure}
The above quantities are defined more precisely as follows:
\begin{madlist}
\ttitem{X} Displacement of the local origin in {\it X}-direction.
\ttitem{Y} Displacement of the local origin in {\it Y}-direction.
\ttitem{Z} Displacement of the local origin in {\it Z}-direction.
\ttitem{THETA} $\theta$ is the angle of rotation (azimuth) about the
global {\it Y}-axis, between the global {\it Z}-axis and the
projection of the reference orbit onto the ({\it Z},
{\it X})-plane. A positive angle THETA forms a right-hand screw
with the {\it Y}-axis.
\ttitem{PHI} $\phi$ is the elevation angle, i.e. the angle between the
reference orbit and its projection onto the ({\it Z},
{\it X})-plane. A positive angle PHI correspond to increasing
{\it Y}. \\
If only horizontal bends are present, the reference
orbit remains in the ({\it Z}, {\it X})-plane and PHI is always zero.
\ttitem{PSI} $\psi$ is the roll angle about the local {\it s}-axis,
i.e. the angle between the line defined by the intersection of the
({\it x, y})-plane and ({\it Z, X})-plane on one hand, and the local
{\it x}-axis on the other hand.
A positive angle PSI forms a right-hand screw with the {\it s}-axis.
\end{madlist}
The angles ($\theta$, $\phi$, $\psi$) are {\bf not} the Euler
angles. The reference orbit starts at the origin and points by default
in the direction of the positive {\it Z}-axis. The initial local axes
({\it x}, {\it y}, {\it s}) coincide with the global axes
({\it X}, {\it Y}, {\it Z}) in this order. The initial values
($X_0$, $Y_0$, $Z_0$, $\theta_0$, $\phi_0$, $\psi_0$) are therefore all zero
unless the user specifies different initial conditions.
Internally the displacement is described by a vector {\it V} and the
orientation by a unitary matrix {\it W}. The column vectors of
{\it W} are the unit vectors spanning the local coordinate axes in
the order ({\it x, y, s}). {\it V} and {\it W} have the values:
\begin{equation}
V =
\begin{pmatrix}
X \\
Y \\
Z
\end{pmatrix}
, \qquad
W=\Theta \quad \Phi \quad \Psi
\end{equation}
where
\begin{equation}
\Theta =
\begin{pmatrix}
\cos \theta & 0 & \sin \theta \\
0 & 1 & 0 \\
-\sin \theta & 0 & \cos \theta
\end{pmatrix}
, \quad
\Phi =
\begin{pmatrix}
1 & 0 & 0 \\
0 & \cos \phi & \sin \phi \\
0 & -\sin \phi & \cos \phi
\end{pmatrix}
, \quad
\Psi =
\begin{pmatrix}
\cos \psi & -\sin \psi & 0 \\
\sin \psi & \cos \psi & 0 \\
0 &0 & 1
\end{pmatrix}
\end{equation}
The reference orbit should be closed, and it should not be twisted.
This means that the displacement of the local reference system must be
periodic with the revolution frequency of the accelerator, while the
position angles must be periodic (modulo $2\pi$) with the revolution
frequency. If $\psi$ is not periodic (modulo $2\pi$), coupling effects are
introduced.
When advancing through a beam element, \madx computes
$V_i$ and $W_i$ by the recurrence relations
\begin{equation}
V_i=W_{i-1}R_i+V_{i-1},
\qquad
W_i=W_{i-1}S_i
\end{equation}
The vector $R_i$ is the displacement and the matrix
$S_i$ is the rotation of the local reference system at the
exit of the element {\it i} with respect to the entrance of the same
element. The values of $R_i$ and $S_i$ are listed below
for different physical element types.
\section{Local Reference Systems}
\label{sec:local_ref}
\subsection{Reference System for Straight Beam Elements}
\label{subsec:local_straight}
In straight elements the local reference system is simply translated by
the length of the element along the local {\it s}-axis.
This is true for
\hyperref[sec:drift]{Drift spaces},\ttindex{drift}
\hyperref[sec:quadrupole]{Quadrupoles},\ttindex{quadrupole}
\hyperref[sec:sextupole]{Sextupoles},\ttindex{sextupole}
\hyperref[sec:octupole]{Octupoles},\ttindex{octupole}
\hyperref[sec:solenoid]{Solenoids},\ttindex{solenoid}
\hyperref[sec:crab_cavity]{Crab cavities},\ttindex{crab cavity}
\hyperref[sec:rf_cavity]{RF cavities},\ttindex{cavity}\ttindex{RF cavity}
\hyperref[sec:separator]{Electrostatic separators},\ttindex{separator}\ttindex{electrostatic separator}
\hyperref[sec:kicker]{Closed orbit correctors}\ttindex{corrector} and
\hyperref[sec:monitor]{Beam position monitors}\ttindex{monitor}.
The corresponding {\it R}, {\it S} are
\begin{equation}
R =
\begin{pmatrix}
0 \\
0 \\
L
\end{pmatrix}
, \quad
S =
\begin{pmatrix}
1 & 0 & 0 \\
0 & 1 & 0 \\
0 & 0 & 1
\end{pmatrix}
.
\end{equation}
A rotation of the element about the {\it S}-axis has no effect on
{\it R} and {\it S}, since the rotations of the reference system
before and after the element cancel.\selectlanguage{english}
\begin{figure}[h!]
\begin{center}
\includegraphics[width=0.70\columnwidth]{figures/FDRF/default-figure}
\caption{{\label{F-DRF} Reference System for Straight Beam Elements%
}}
\end{center}
\end{figure}
\subsection{Reference System for Bending Magnets}
\label{subsec:local_rbend}
\hyperref[sec:bend]{Bending magnets} have a curved reference orbit.
For both rectangular and sector bending magnets, the {\it R} and
{\it S} are expressed as function the bend angle $\alpha$:
\begin{equation}
R =
\begin{pmatrix}
\rho\,(\cos \alpha - 1) \\
0 \\
\rho\,\sin \alpha
\end{pmatrix}
, \quad
S =
\begin{pmatrix}
\cos \alpha & 0 & -\sin \alpha \\
0 & 1 & 0 \\
\sin \alpha & 0 & \cos \alpha
\end{pmatrix}
\end{equation}
A positive bend angle represents a bend to the right, i.e. towards
negative {\it x} values.
For sector bending magnets, the bend radius is given by $\rho$, and for
rectangular bending magnets it has the value $\rho = L / (2 \sin(\alpha/2))$.
If the magnet is rotated about the {\it s}-axis by an angle $\psi$,
{\it R} and {\it S} are transformed by
\begin{equation}
\overline{R}=TR,
\qquad
\overline{S}=TST^{-1}
\end{equation}
where {\it T} is the orthogonal rotation matrix
\begin{equation}
T =
\begin{pmatrix}
\cos \psi & -\sin \psi & 0 \\
\sin \psi & \cos \psi & 0 \\
0 &0 & 1
\end{pmatrix}
\end{equation}
The special value $\psi = \pi/2$ represents a bend down.\selectlanguage{english}
\begin{figure}[h!]
\begin{center}
\includegraphics[width=0.70\columnwidth]{figures/FRBND/default-figure}
\caption{{Couldn't find caption for this figure%
}}
\end{center}
\end{figure}\selectlanguage{english}
\begin{figure}[h!]
\begin{center}
\includegraphics[width=0.70\columnwidth]{figures/FSBND/default-figure}
\caption{{Couldn't find caption for this figure%
}}
\end{center}
\end{figure}
\section{Sign Conventions for Magnetic Fields}
\label{sec:sign_convention}
The \madx program uses the following Taylor expansion for the field on the
mid-plane $y=0$, described in \cite{slac75} (Note the factorial in the
denominator):
\begin{equation}
B_y(x,0)=\sum_{n=0}^{\infty} \frac{B_n\,x^n}{n!}
\end{equation}
The field coefficients have the following meaning:
\begin{madlist}
\item[$B_0$]
Dipole field, with a positive value in the
positive $y$ direction; a positive field bends a positively
charged particle to the right.
\item[$B_1$]
Quadrupole coefficient
\( B_1 = ( \partial B_y / \partial x ) \);
a positive value corresponds to horizontal focussing of a
positively charged particle.
\item[$B_2$]
Sextupole coefficient
\( B_2 = ( \partial^2 B_y / \partial x^2 ) \).
\item[$B_3$]
Octupole coefficient
\( B_3 = ( \partial^3 B_y / \partial x^3 ) \).
\item[\ldots] etc.
\end{madlist}
Using this expansion and the curvature {\it h} of the reference
orbit, the longitudinal component of the vector potential to order 4 is:
\begin{equation}
\begin{aligned}
A_s =
&+ B_0\,\Big(x-\frac{hx^2}{2(1+hx)}\Big)&
&+ B_1\,\Big(\frac{1}{2}(x^2-y^2) - \frac{h}{6}x^3 + \frac{h^2}{24}(4x^4-y^4)+\cdots\Big) \\
&+ B_2\,\Big(\frac{1}{6}(x^3-3xy^2) - \frac{h}{24}(x^4-y^4)+\cdots \Big)&
&+ B_3\,\Big(\frac{1}{24}(x^4-6x^2y^2+y^4) \cdots \Big)+\cdots
\end{aligned}
\end{equation}
Taking \(\vec{B} = \nabla \times \vec{A}\) in curvilinear coordinates,
the field components can be computed as
\begin{equation}
\label{eq:field_components}
\begin{aligned}
B_x(x,y) = &+ B_1\,\Big(y+\frac{h^2}{6}y^3+\cdots\Big) & \\
&+ B_2\,\Big(xy - \frac{h}{6}y^3+\cdots \Big) &+ B_3\,\Big(\frac{1}{6}(3x^2y-y^3)+ \cdots \Big)+\cdots\\
B_y(x,y)= &+ B_0 &+ B_1\,\Big(x-\frac{h}{2}y^2+\frac{h^2}{2}xy^2+\cdots \Big)\\
&+ B_2\,\Big(\frac{1}{2}(x^2-y^2)-\frac{h}{2}xy^2+\cdots \Big) &+ B_3\,\Big(\frac{1}{6}(x^3-3xy^2)+ \cdots \Big)+\cdots
\end{aligned}
\end{equation}
It can be easily verified that both \(\nabla \times \vec{B}\)
and \(\nabla . \vec{B}\) are zero to the order of the
\(B_3\) term.
Introducing the magnetic rigidity \(B \rho = p_s / q\) as the
momentum of the particle divided by its charge, the multipole
coefficients are computed as
\begin{equation}
\label{eq:kn}
K_n = q B_n / p_s = B_n / B \rho
\end{equation}
\section{Generalisation to normal and skew components}
\label{sec:normalskew}
The previous section assumed an expansion at the mid-plane ($y=0$),
symmetry around the mid-plane and considered only the vertical
component of the field.
An extension using complex notation for the position ($x + i y$)
and the field is given as
\begin{equation}
B_y + i B_x =\sum_{n=0}^{\infty} (b_n\,+ia_n) \frac{(x+iy)^n}{n^{n-1}}
\end{equation}
By introducing the normal and skew multipole coefficients
$KN$ and $KS$ at order $n$ as
\begin{equation}
\label{eq:knn}
KN_n = q\,b_n / p_s = b_n / B \rho
\end{equation}
and
\begin{equation}
\label{eq:kns}
KS_n = q\,a_n / p_s = a_n / B \rho
\end{equation}
the kicks received in each plane can be expressed as the summation
over all components
\begin{equation}
\Delta P_x - i \Delta P_y = \sum_{n=0}^{\infty} -(KN_n + i KS_n) \frac{(x+iy)^n}{n!}
\end{equation}
{\bf Remark:} need to add references to the $(a_n,b_n)$ field conventions
in the magnet world.
\section{Variables}
\label{sec:variables}
For each variable listed in this section, the physical units are given
between square brackets, where [1] denotes a dimensionless variable.
\subsection{Canonical Variables Describing Orbits}
\label{subsec:tables_canon}
\madxuses the following canonical variables to describe the motion of particles:
\begin{madlist}
\ttitem{X} Horizontal position $x$ of the (closed) orbit,
referred to the ideal orbit [m].
\ttitem{PX} Horizontal canonical momentum $p_x$ of the
(closed) orbit referred to the ideal orbit, divided by the
reference momentum: $\textrm{PX} = p_x / p_0$, [1].
\ttitem{Y} Vertical position $y$ of the (closed) orbit, referred
to the ideal orbit [m].
\ttitem{PY} Vertical canonical momentum $p_y$ of the (closed)
orbit referred to the ideal orbit, divided by the reference
momentum: $\textrm{PY} = p_y / p_0$, [1].
\ttitem{T} Velocity of light times the negative time difference with
respect to the reference particle: $\textrm{T} = - c t$, [m]. A
positive T means that the particle arrives ahead of the reference
particle.
\ttitem{PT} Energy error, divided by the reference momentum times the
velocity of light: $\textrm{PT} = \Delta E / p_s c$, [1].
This value is only non-zero when synchrotron motion is
present. It describes the deviation of the particle from the orbit
of a particle with the momentum error DELTAP.
\ttitem{DELTAP} {\bf Difference between the reference momentum and the design
momentum, divided by the design momentum: DELTAP =
$\Delta p / p_0$, [1].} This quantity is used to
\hyperref[chap:differences]{normalize} all element strengths.
\end{madlist}
The independent variable is:
\begin{madlist}
\ttitem{S} \index{arc length} Arc length {\it s} along the reference orbit,
[m].
\end{madlist}
In the limit of fully relativistic particles ($\gamma \gg 1$, $v = c$,
$p c = E$), the variables T, PT used here agree with the
longitudinal variables used in \cite{TRANSPORT}. This means that T
becomes the negative path length difference, while PT becomes the
fractional momentum error. The reference momentum $p_s$ must be
constant in order to keep the system canonical.
\subsection{Normalised Variables and other Derived Quantities}
\label{subsec:tables_normal}
\begin{madlist}
\ttitem{XN} The normalised horizontal displacement \quad
$x_n = Re ( E_1^T \, S\, Z )$, [sqrt(m)]
\ttitem{PXN} The normalised horizontal transverse momentum \quad
$p_{xn} = Im ( E_1^T\, S\, Z )$, [sqrt(m)]
\ttitem{WX} The horizontal Courant-Snyder invariant \quad
WX = $x_n^2 + p_{xn}^2$, [m].
\ttitem{PHIX} The horizontal phase \quad
$\phi_x = -\arctan ( p_{xn} / x_n ) / 2 \pi$, [1]
\ttitem{YN} The normalised vertical displacement \quad
$y_n = Re ( E_2^T \,S\, Z )$, [sqrt(m)]
\ttitem{PYN} The normalised vertical transverse momentum \quad
$p_{yn} = Im ( E_2^T\, S\, Z )$, [sqrt(m)]
\ttitem{WY} The vertical Courant-Snyder invariant \quad
WY = $y_n^2 + p_{yn}^2$, [m]
\ttitem{PHIY} The vertical phase \quad
$\phi_y = -\arctan ( p_{yn} / y_n ) / 2 \pi$, [1]
\ttitem{TN} The normalised longitudinal displacement \quad
$t_n = Re ( E_3^T \,S\, Z )$, [sqrt(m)]
\ttitem{PTN} The normalised longitudinal transverse momentum \quad
$p_{tn} = Im ( E_3^T\, S\, Z )$, [sqrt(m)]
\ttitem{WT} The longitudinal invariant \quad
WT = $t_n^2 + p_{tn}^2$, [m]
\ttitem{PHIT} The longitudinal phase \quad
$\phi_t = - atan ( p_{tn} / t_n ) / 2 \pi$, [1]
\end{madlist}
In the above formulas the vectors \(E_i\) are the three complex
eigenvectors, \(Z\) is the phase space vector, and the matrix {\it S}
is the ``symplectic unit matrix'':
\begin{equation}
Z = \left(
\begin{array}{l} x \\ p_x \\ y \\ p_y \\ t \\ p_t
\end{array} \right), \quad
S =
\begin{pmatrix}
0 & 1 & 0 & 0 & 0 & 0 \\
-1 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 1 & 0 & 0 \\
0 & 0 & -1 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 1 \\
0 & 0 & 0 & 0 & -1 & 0 \\
\end{pmatrix}
\end{equation}
\subsection{Linear Lattice Functions (Optical Functions)}
\label{subsec:tables_linear}
Several \madx commands refer to linear lattice functions or optical
functions.
Because \madx uses the canonical momenta ($p_x$, $p_y$) instead of the
slopes ($x'$, $y'$), the definitions of the linear lattice functions
differ slightly from those in Courant and Snyder\cite{Courant_Snyder1958}.
Notice that in \madx, PT substitutes DELTAP as longitudinal
variable.
Dispersive and chromatic functions are hence derivatives with
respect to PT.
And since PT=BETA*DELTAP, where BETA is the relativistic Lorentz
factor, those functions given by \madx must be multiplied by BETA a
number of time equal to the order of the derivative to find the
functions given in the literature.
The linear lattice functions are known to \madx under the following names:
\begin{madlist}
\ttitem{BETX} Amplitude function $\beta_x$, [m].
\ttitem{ALFX} Correlation function
$\alpha_x = - \frac{1}{2} (\partial \beta_x / \partial s)$, [1]
\ttitem{MUX} Phase function $\mu_x = \int ds / \beta_x$, [$2 \pi$]
\ttitem{DX} Dispersion of $x$: $D_x = (\partial x / \partial p_t)$, [m]
\ttitem{DPX} Dispersion of $p_x$: $D_{px} = (\partial p_x / \partial p_t) / p_s$, [1]
\ttitem{BETY} Amplitude function $\beta_y$, [m]
\ttitem{ALFY} Correlation function
$\alpha_y = - \frac{1}{2} ( \partial \beta_y / \partial s)$, [1]
\ttitem{MUY} Phase function $\mu_y = \int ds / \beta_y$, [$2 \pi$]
\ttitem{DY} Dispersion of $y$: $D_y = (\partial y / \partial p_t)$, [m]
\ttitem{DPY} Dispersion of $p_y$: $D_{py} = ( \partial p_y / \partial p_t) / p_s$, [1]
\ttitem{R11, R12, R21, R22} : Coupling Matrix
\end{madlist}
\subsection{Chromatic Functions}
\label{subsec:tables_chrom}
Several \madx commands refer to the chromatic functions.
Because \madx uses the canonical momenta ($p_x$, $p_y$) instead of the
slopes ($x'$, $y'$), the definitions of the chromatic functions differ
slightly from those in \cite{Montague1979}.
Notice also that in \madx, PT substitutes DELTAP as longitudinal
variable. Dispersive and chromatic functions are hence derivatives with
respects to PT.
And since PT=BETA*DELTAP, where BETA is the relativistic Lorentz
factor, those functions given by \madx must be multiplied by BETA a
number of time equal to the order of the derivative to find the
functions given in the literature.
The chromatic functions are known to \madx under the following names:
\begin{madlist}
\ttitem{WX} Chromatic amplitude function $W_x = \sqrt{a_x^2 + b_x^2}$ ,
[1], where \\
\[
b_x = \frac{1}{\beta_x} \frac{\partial \beta_x}{\partial p_t} ,\qquad
a_x = \frac{\partial \alpha_x}{\partial p_t} -
\frac{\alpha_x}{\beta_x}\frac{\partial \beta_x}{\partial p_t}
\]
%% the equation used to be the following, which is in contradiction
%% with MAD8 users' guide and Montague (LEP Note 165) where a and b
%% are exactly inverted.
%% \[
%% a_x = \frac{1}{\beta_x} \frac{\partial \beta_x}{\partial p_t} ,\qquad
%% b_x = \frac{\partial \alpha_x}{\partial p_t} -
%% \frac{\alpha_x}{\beta_x}\frac{\partial \beta_x}{\partial p_t}
%% \]
\ttitem{PHIX} Chromatic phase function $\Phi_x = \arctan (a_x / b_x)$, [$2 \pi$]
\ttitem{DMUX} Chromatic derivative of phase function:
$DMUX = (\partial \mu_x / \partial p_t)$, [$2 \pi$]
\ttitem{DDX} Chromatic derivative of dispersion $D_x$ :
$DDX = \frac{1}{2} (\partial^2 x / \partial p_t^2)$, [m]
\ttitem{DDPX} Chromatic derivative of dispersion $D_{px}$ :
$DDPX = \frac{1}{2} ( \partial^2 p_x / \partial p_t^2 ) / p_s $, [1]
\ttitem{WY} Chromatic amplitude function $W_y = \sqrt{a_y^2 + b_y^2}$ ,
[1], where \\
\[
b_y = \frac{1}{\beta_y} \frac{\partial \beta_y}{\partial p_t} ,\qquad
a_y = \frac{\partial \alpha_y}{\partial p_t} -
\frac{\alpha_y}{\beta_y}\frac{\partial \beta_y}{\partial p_t}
\]
\ttitem{PHIY} Chromatic phase function $\Phi_y = \arctan (a_y / b_y)$, [$2 \pi$]
\ttitem{DMUY} Chromatic derivative of phase function:
$DMUY = (\partial \mu_y / \partial p_t)$, [$2 \pi$]
\ttitem{DDY} Chromatic derivative of dispersion $D_y$ :
$DDY = \frac{1}{2} (\partial^2 y / \partial p_t^2)$, [m]
\ttitem{DDPY} Chromatic derivative of dispersion $D_{py}$ :
$DDPY = \frac{1}{2} ( \partial^2 p_y / \partial p_t^2 ) / p_s $, [1]
\end{madlist}
\subsection{Variables in the SUMM Table}
\label{subsec:tables_summ}
After a successful TWISS command a summary table, with name SUMM, is created which
contains the following variables:
\begin{madlist}
\ttitem{LENGTH} The length of the machine, [m].
\ttitem{ORBIT5} The T ($= c t$, [m]) component of the closed orbit.
\ttitem{ALFA} The momentum compaction factor $\alpha_c$, [1].
\ttitem{GAMMATR} The transition energy $\gamma_{tr}$, [1].
\ttitem{Q1} The horizontal tune $Q_1$ [1].
\ttitem{DQ1} The horizontal chromaticity $dq_1 = \partial Q_1 / \partial p_t$, [1]
\ttitem{BETXMAX} The largest horizontal $\beta_x$, [m].
\ttitem{DXMAX} The maximum of the absolute horizontal dispersion $D_x$, [m].
\ttitem{DXRMS} The r.m.s. of the horizontal dispersion $D_x$, [m].
\ttitem{XCOMAX} The maximum of the absolute horizontal closed orbit deviation [m].
\ttitem{XRMS} The r.m.s. of the horizontal closed orbit deviation [m].
\ttitem{Q2} The vertical tune $Q_2$ [1].
\ttitem{DQ2} The vertical chromaticity $dq_2 = \partial Q_2 / \partial p_t$, [1]
\ttitem{BETYMAX} The largest vertical $\beta_y$, [m].
\ttitem{DYMAX} The maximum of the absolute vertical dispersion $D_y$, [m].
\ttitem{DYRMS} The r.m.s. of the vertical dispersion $D_y$, [m].
\ttitem{YCOMAX} The maximum of the absolute vertical closed orbit deviation [m].
\ttitem{YCORMS} The r.m.s. of the vertical closed orbit deviation [m].
\ttitem{DELTAP} {\bf Momentum difference, divided by the reference
momentum: DELTAP = $\Delta p / p_0$ [1].}
\ttitem{SYNCH\_1} First synchrotron radiation integral
\ttitem{SYNCH\_2} Second synchrotron radiation integral
\ttitem{SYNCH\_3} Third synchrotron radiation integral
\ttitem{SYNCH\_4} Fourth synchrotron radiation integral
\ttitem{SYNCH\_5} Fifth synchrotron radiation integral
\end{madlist}
Notice that in \madx, PT substitutes DELTAP as longitudinal
variable. Dispersive and chromatic functions are hence derivatives with
respects to PT.
And since PT=BETA*DELTAP, where BETA is the relativistic Lorentz
factor, those functions given by \madx must be multiplied by BETA a
number of time equal to the order of the derivative to find the
functions given in the literature.
\subsection{Variables in the TRACK Table}
\label{subsec:tables_track}
The command RUN writes tables with the following variables:
\begin{madlist}
\ttitem{X} Horizontal position $x$ of the orbit, referred to the
ideal orbit [m].
\ttitem{PX} Horizontal canonical momentum $p_x$ of the orbit
referred to the ideal orbit, divided by the reference momentum.
\ttitem{Y} Vertical position $y$ of the orbit, referred to the
ideal orbit [m].
\ttitem{PY} Vertical canonical momentum $p_y$ of the orbit
referred to the ideal orbit, divided by the reference momentum.
\ttitem{T} Velocity of light times the negative time difference with
respect to the reference particle, $\hbox{\tt T}=-c\Delta t$, [m].
A positive T means that the particle arrives ahead of the reference
particle.
\ttitem{PT} Energy difference, divided by the reference momentum times
the velocity of light, [1].
\end{madlist}
When tracking Lyapunov companions, the TRACK table defines the following
dependent expressions:
\begin{madlist}
\ttitem{DISTANCE} the relative Lyapunov distance between the two particles.
\ttitem{LYAPUNOV} the estimated Lyapunov Exponent.
\ttitem{LOGDIST} the natural logarithm of the relative distance.
\ttitem{LOGTURNS} the natural logarithm of the turn number.
\end{madlist}
\section{Physical Units}
\label{sec:units}
\madxuses units derived from the ``Syst\`eme
International'' (SI). These units are summarised in the
\hyperlink{table}{Units table}.\selectlanguage{english}
\begin{table}
[ht]
\caption{{Physical Units used by \madx}}
\vspace{1ex}
\begin{center}
\index{length}
\index{angle}
\index{quadrupole}
\index{multipole}
\index{voltage}
\index{field}
\index{electric field}
\index{frequency}
\index{RF}
\index{energy}
\index{mass}
\index{momentum}
\index{current}
\index{charge}
\index{impedance}
\index{emittance}
\index{power}
\index{high order modes}
\begin{tabular}{|l|l|}
\hline
{\bf Quantity} & {\bf Unit} \\
\hline
Length & m (metres) \\
Angle & rad (radians) \\
Quadrupole coefficient & $m^{-2}$ \\
Multipole coefficient, 2n poles & $m^{-n}$ \\
Electric voltage & MV (Megavolts) \\
Electric field strength & MV/m \\
Frequency & MHz (Megahertz) \\
Phase angles & $2\pi$ \\
Particle energy & GeV \\
Particle mass & GeV/$c^2$ \\
Particle momentum & GeV/$c$ \\
Beam current & A (Amp\`eres) \\
Particle charge & e (elementary charges) \\
Impedance & M$\Omega$ (Megohms) \\
Emittance & $\pi * 10^{-3}$ m.rad \\ % To be checked (Ghislain)
RF power & MW (Megawatts) \\
Higher order mode loss factor & V/pc \\
\hline
\end{tabular}
\end{center}
\end{table}
\chapter{Command Format}
\section{Input Statements}
Input for \madx follows in broad lines the
\href{http://cern.ch/mad9}{\madnine}\index{MAD-9} format, i.e. free
format with commas (,) as separators, although blanks may be used as
separators outside \{...\} enclosures.
Blank input lines do not affect program execution.
The input is not case sensitive except for strings enclosed in double
quotes (" ").
The input file consists of a sequence of statements.
A statement may occupy any number of input lines.
Several statements may be placed on the same line.
A statement must be terminated by a semicolon (;).
Several statements may be grouped into a block enclosed inside a \{...\}
enclosure. In this case the terminating semmicolon can be omitted.
\madxmp{if (a $<$ 3) \{ a=b*b; b=2*b+4; \};}
or
\madxmp{if (a $<$ 3) \{ a=b*b; b=2*b+4; \}}
are both valid.
\section{Comments}
When an exclamation mark ({\tt !}) or double forward slash ({\tt //}) is
found in the input line, the remaining characters until the end of the
line are treated as a comment and are skipped.
A comment spreading over multiple lines starts with a "/*" and ends with a "*/".
\section{Commands}
The general format for a command is
\madbox{
label: keyword \{,attribute\} ;
}
where the {\tt \{ \}} are not part of the command and the items
enclosed in {\tt \{ \}} can be omitted or repeated any number of times.
A command contains three parts:
\begin{madlist}
\ttitem{label}\index{label}
A \href{label.html}{label} is required for a definition statement.
It gives a name to the stored command.
\ttitem{keyword}\index{keyword}
A \href{keyword.html}{keyword} identifies the action desired.
\ttitem{attributes}\index{attribute}
The \href{attribute.html}{attributes} are normally entered in the
form \madxmp{attribute-name = attribute-value}
and serve to define data for the command, where:
\begin{madlist}
\ttitem{attribute-name} selects the attribute, and
\ttitem{attribute-value} provides its value.
\end{madlist}
If a value is to be assigned to an attribute, the {\tt attribute-name} is
mandatory.
Whenever an attribute is not explicitly given a value, the default
{\tt attribute-value} specified in the command dictionary is assumed.
\section{Keywords}
\label{subsec:keyword}
A keyword begins with a letter and consists of letters and digits.
The \madx keywords are protected; using one of them as a label results
in a fatal error.
\section{Attribute Types}
The command attributes can have one of the following types:
\begin{itemize}
\item \href{string.html}{String attribute},
\item \href{logical.html}{Logical attribute},
\item \href{integer.html}{Integer attribute},
\item \href{real.html}{Real attribute},
\item \href{expression.html}{Expression},
\item \href{select.html}{Range selection},
\end{itemize}
Any integer or real attribute can be replaced by
a \href{expression.html}{real expression}; expressions are
normally deferred\index{deferred}
(see \hyperref[sec:defer]{deferred expression}), except in the
definition of constants where they are evaluated immediately.
When a command has a \href{label.html}{label}, \madx keeps this command
in memory. This allows repeated execution of the same command
by just entering EXEC label. This construct may be nested.
For an exhaustive list of valid declarations of constants or variables
see \href{declarations.html}{declarations}.
\section{Variable Declarations}
\label{subsec:var_declarations}
In the following, "=" means that the variable at the left receives the
current value of the expression at right, but does not depend on it any
further, whereas ":=" makes it depend on this expression, i.e. every
time the expression changes, the variable is re-evaluated, except for
"const" variables.
\madxmp{
var = expression; \\
var := expression; \\
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\= \kill
real var = expression; \>// identical \\
real var := expression; \>// to above \\
int var = expression; \>// truncated if expression is real \\
int var := expression; \\
const var = expression; \\
const var := expression; \\
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\= \kill
const real var = expression; \>// identical \\
const real var := expression; \>// to above \\
const int var = expression; \>// truncated if expression is real \\
const int var := expression;
}
\section{Identifiers or Labels}
\label{sec:label}
A label begins with a letter, followed by up to fifteen letters, digits,
decimal points (.), or underscores (\_). Characters beyond the sixteenth
are dropped, but should be avoided, and the resulting sequence must be
unique.
A label may refer to a keyword, an element, a beam-line, a sequence,
etc.
The \madx keywords are protected; using one of them as a label
results in a fatal error.
\section{Command Attributes}
\label{sec:attribute}
\begin{itemize}
\item A \href{name.html}{name or string attribute} refers to an object, or a string.
\item A \href{logical.html}{logical attribute} selects or deselects an option.
\item An \href{integer.html}{integer attribute} is a counter, as for repetition in a beam line.
\item A \href{real.html}{real attribute} defines a value stored
as double precisiom data.
\item A \href{expression.html}{real expression} defines a datum
for a command, it may be varied in matching. An expression is
built of a combination of
\href{expression.html#operator}{operator} and
\href{expression.html#operand}{operand}.
\item A \href{constraint.html}{constraint}, specifies a matching constraint.
\item A \href{variable.html}{variable name} selects a variable to be matched.
\end{itemize}
\section{Name or String Attributes}
\label{sec:name} \label{sec:string}
A name or string attribute often selects one of a set of options:
\madxmp{
xxxxxxxxxxxxxxxxxxxx\= \kill
USE, PERIOD=lhc; \>// expand the LHC sequence
}
It may also refer to a user-defined object:
\madxmp{
xxxxxxxxxxxxxxxxxxxxxxx\= \kill
TWISS, FILE=optics; \>// specifies the name of the OPTICS output file
}
It may also define a string:
\madxmp{
TITLE, "LHC version 6.2";
}
The case of letters is only significant if a string is enclosed in
quotes, otherwise all characters are converted to lowercase at
reading.
On the other hand, strings that do not contain blanks do not
need to be enclosed in quotes.
Example:
\madxmp{
CALL, FILE = "my.file"; \\
CALL, FILE = my.file; \\
CALL, FILE = MY.FILE; \\
CALL, FILE = "MY.FILE"; \\
CALL, FILE = 'MY.FILE';
}
In the first three cases, \madx will try to read a file named my.file, in the
last two it will try to read the file named MY.FILE.
A string attribute makes alphanumeric information available, e.g. a
title or a file name. It can contain any characters, enclosed in single
(') or double (") quotes, except for quotes of the type used as its
delimiter.
Examples:
\madxmp{
TITLE, 'This is a title for the program run "test"'; \\
SYSTEM, "ln -fns some-lengthy-directory-name local-link";
}
\section{Logical Attributes}
\label{sec:logical}
Many commands in \madx require the setting of logical values (flags) to
represent the on/off state of an option. A logical value "flag" can be
set in two ways:
\madxmp{flag | flag = true}
It can be reset by:
\madxmp{-flag | flag=false}
Example:
\madxmp{
OPTION, -ECHO; // switch off copying the input to the standard output
}
The default for a logical flag is normally false, but can be found e.g. for options by the command
\madxmp{HELP, option;}
\section{Integer Attributes}
\label{sec:integer}
An integer attribute usually denotes a count. Example:
\madxmp{myline: LINE = ( -3 * (a,b,c) );}
In this case, a litteral integer is requested; however, in the following
\madxmp{rfc: RFCAVITY, HARMON = 12345;}
or
\madxmp{rfc: RFCAVITY, HARMON = num;}
"num" may be an integer variable, a real variable, or an expression. In
the two latter cases, the value is truncated.
\section{Real Attributes}
\label{sec:real}
Most attributes are of type REAL and are treated internally as double
precision values. They may be set by integer values, real values, or
expressions.
Example:
\madxmp{
xxxxxxx\= \kill
ddd: \>drift, l = 1.2345; \\
dddd: \>drift, l = ddd-\textgreater l-0.3;
}
\section{Real Expressions}
\label{sec:expression}
To facilitate the definition of interdependent quantities, any real
value and integer value can be entered as an arithmetic expression. When
a value used in an expression is redefined by the user or changed in a
matching process, the expression is reevaluated. Expression definitions
may be entered in any order. \madx evaluates them in the correct order
before it performs any computation. At evaluation time all operands used
must have values assigned.
An expression is built from a combination of
\hyperlink{operator}{operator} and \hyperlink{operand}{operand}, and it
may contain \hyperlink{random}{random generators}.
\subsection{Operators in Arithmetic Expressions}
\label{subsec:operator}
An expression can be formed using the following operators:
\subsubsection{Arithmetic operators}
\begin{madlist}
\ttitem{+} Addition,
\ttitem{-} Subtraction,
\ttitem{*} Multiplication,
\ttitem{/} Division,
\ttitem{\^\ } Exponentiation.
\end{madlist}
\subsubsection{Ordinary Functions}
\label{subsubsec:function}
\begin{madlist}
\ttitem{SQRT(x)} square root,
\ttitem{LOG(x)} natural logarithm,
\ttitem{LOG10(x)} logarithm base 10,
\ttitem{EXP(x)} exponential,
\ttitem{SIN(x)} trigonometric sine,
\ttitem{COS(x)} trigonometric cosine,
\ttitem{TAN(x)} trigonometric tangent,
\ttitem{ASIN(x)} arc sine,
\ttitem{ACOS(x)} arc cosine,
\ttitem{ATAN(x)} arc tangent,
\ttitem{SINH(x)} hyperbolic sine,
\ttitem{COSH(x)} hyperbolic cosine,
\ttitem{TANH(x)} hyperbolic tangent,
\ttitem{SINC(x)} cardinal sine function,
\ttitem{ABS(x)} absolute value,
\ttitem{ERF(x)} Gauss error,
\ttitem{ERFC(x)} complementary error,
\ttitem{FLOOR(x)} floor, largest previous integer,
\ttitem{CEIL(x)} ceiling, smallest next integer,
\ttitem{ROUND(x)} round, closest integer;
\end{madlist}
\subsubsection{Random Number Generators}
\label{subsubsec:random}
\begin{madlist}
\ttitem{RANF()} random number, uniformly distributed in [0,1],
\ttitem{GAUSS()} random number, gaussian distribution with unit
standard deviation,
\ttitem{TGAUSS(x)} random number, gaussian distribution with unit
standard deviation, truncated at x standard deviations;
\end{madlist}
in the above cases, "x" can be any expression, i.e. contain other
functions, variable or constant expressions. To initialize the \madx
random generator use the \hyperref[sec:eoption]{\tt EOPTION} command.
\subsubsection{Table Access Functions}
\label{subsubsec:table}
\begin{madlist}
\ttitem{TABLE(x,z)} accesses value of the named table column "z"
of table "x"; example: table(summ,q1) returns the hor. tune of
the Twiss summary table "summ".
\ttitem{TABLE(x,y,z)} accesses value of the named table column "z"
for element "y" (first table row with that name) of table "x";
example: table(twiss,mb.12,betx) returns the beta\_x at
element mb.12 from the Twiss table "twiss". When the element
is called with its proper name, as in the example above, the
value is returned at the first occurrence of the element of
this name. If the value is needed at a occurrence number: NNN,
then "[NNN]" has to be appended to the name, e.g. in the above
example one obtains the betx of the 23th occurrence of the
element "mb.12" by changing the example to:
"table(twiss,mb.12[23],betx)". Mind you that the old, but
little known, form: "table(twiss,mb.12-\textgreater 23,betx)"
continues to work. Lastly, if NNN exceeds the maximum
occurrence number the return value is arbitrarily small.
\end{madlist}
Beware:
\begin{itemize}
\item Unnamed Drifts are not included in the table name
database, so as to speed up the search for "real"
elements. Therefore, those unnamed drifts cannot be
found. However, named drifts can be searched for.
\item Due to the importance of finding elements in the table
for a proper functioning of the \madx runs, the programs
throws a "fatal\_error" if an element cannot be found in the
table.
\end{itemize}
There is a second option of this function with 3 entries
\begin{itemize}
\item table(x,z,N\_row): accesses the value of the named table
column "z" at the "N\_row" number of rows of table "x" (row
numbers start at 1); example: table(twiss,betx,370) returns
the beta\_x at row number "370" of the Twiss table
"twiss". The return value is zero if "N\_row" is outside of
the allowed range.
\end{itemize}
Note that "N\_row" has to be a number and not a variable. However, the
\hyperref[sec:macro]{Macro} facility in \madx allows
the use of a variable instead.
A typical example could look like this, in fact the square root of betx
(user defined variable myvar) is added to the twiss table:
\begin{verbatim}
myvar := sqrt(table(twiss,betx));
select, flag=twiss, column=name, s, myvar, betx;
twiss, file;
\end{verbatim}
Or another arbitrary test case of adding k1l taken from the Twiss table:
Define macro:
\begin{verbatim}
mymacro(xx,yy,zz): macro = {myval = table(xx,yy,zz);};
\end{verbatim}
Use macro in loop:
\begin{verbatim}
i = 0;
incval = 0;
while (i < 100) {
value, i;
exec, mymacro(twiss,k1l,$i);
incval = incval + myval;
value, i, myval, incval;
i = i + 1;
}
\end{verbatim}
\subsection{Operands in Arithmetic Expressions}
\label{subsec:operand}
An expression may contain the following operands:
\subsubsection{Literal Constants}
Numerical values are entered like FORTRAN constants. Real values are
accepted in INTEGER or REAL format. The use of a decimal exponent,
marked by the letter D or E, is permitted.
Examples:
\madxmp{
1, 10.35, 5E3, 314.1592E-2
}
\subsubsection{Symbolic constants}
\label{subsubsec:symbolic_const}
\madxrecognizes some \hyperlink{constant}{mathematical and physical
constants}. Their names must not be used for user-defined labels.
Additional symbolic constants may be defined to simplify their repeated
use in statements and expressions.
\madbox{
CONST name=constant-expression;
}
defines a real constant with the name given. An existing symbolic
constant can be redefined, but it cannot change in a matching procedure.
Example:
\madxmp{CONST IN = 0.0254;}
A number of predefined symbolic constants exist in \madx and can be used
in expressions. The values of physical constants are regularly updated
to reflect the values published by the Particle Data Group \cite{PDG2014}
The values published in 2014 (\cite{PDG2014}) have not changed with respect to
the values published in 2012 (\cite{PDG2012}).\selectlanguage{english}
\begin{table}
[ht]
\caption{{Predefined Symbolic Constants in \madx}}
\vspace{1ex}
\begin{center}
\begin{tabular}{|l|c|c|c|}
\hline
\textbf{\madx name} & \textbf{symbol} & \textbf{value} & \textbf{unit} \\
\hline
PI & $\pi$ & 4 * atan(1) & 1 \\
TWOPI & $2\pi$ & 2 * PI & 1 \\
DEGRAD & $180/\pi$ & 180 / PI & deg/rad \\
RADDEG & $\pi/180$ & PI / 180 & rad/deg \\
E & e & exp(1) & 1 \\
EMASS & $m_e$ & $0.510998928\times 10^{-3}$& GeV \\
PMASS & $m_p$ & 0.938272046 & GeV \\
NMASS & $u$ & 0.931494061 & GeV \\
MUMASS & $m_\mu$ & 0.1056583715 & GeV \\
CLIGHT & $c$ & $2.99792458\times 10^{8}$ & m/s \\
QELECT & $e$ & $1.602176565\times 10^{-19}$ & A.s \\
HBAR & $\hbar$ & $6.58211928\times 10^{-25}$ & MeV.s\\
ERAD & $r_e$ & $2.8179403267\times 10^{-15}$ & m\\
PRAD & $r_e (m_e / m_p)$ & ERAD*EMASS/PMASS & m \\
\hline
\end{tabular}
\end{center}
\end{table}
Note that the {\tt NMASS} constant in \madx is the unified atomic mass unit and
not the neutron mass.
\subsubsection{Parameter labels}
Often a set of numerical values depends on a common variable
parameter. Such a parameter must be defined as a
\href{parameter.html}{global parameter}. A global parameter always has a
current value; however, this value may be re-evaluated or not, depending
on the parameter definition:
\begin{verbatim}
x = a;
\end{verbatim}
x is set to the current value of a and not changed, even if a
changes. This makes assignments such as
\begin{verbatim}
x = x + 1;
\end{verbatim}
perfectly valid (this replaces the old SET instruction).
The definition of the deferred expression
\begin{verbatim}
x := a;
\end{verbatim}
assign the current value of a to x every time x is used, i.e. it is
re-evaluated using the latest value of a; therefore,
\begin{verbatim}
x := x + 1;
\end{verbatim}
results in an infinite loop (!) when x is used (error abort).
Of course, the following definitions are equivalent:
\begin{verbatim}
x = 0.1;
x := 0.1;
\end{verbatim}
When such a parameter is used in an expression, \madx uses the current
value of the parameter if the expression is deferred:
Example:
\madxmp{
x := 1.0; \\
d1: drift, l = x; \\
d2: drift, l := 2.0 - x; \\
}
When the value of x is changed, the length of the drift d1 remains
unchanged, that of d2 is recalculated.
\subsubsection{Element or Command Attributes}
In arithmetic expressions the attributes of physical elements or
commands can occur as operands. They are named respectively by
\madbox{
element-name->attribute-name\\
command-name->attribute-name
}
Values are assigned to attributes in element definitions or commands.
Example:
\madxmp{
xxxxxxxx\= \kill
D1: \>DRIFT, L= 1.0; \\
D2: \>DRIFT, L= 2.0 - D1->L;
}
\texttt{D1-\textgreater L} refers to the length L of the drift space D1.
\subsection{Expressions and Random Values}
\label{subsec:expr_rnd}
The definition of random machine imperfections requires evaluation of
expressions containing random functions. These are evaluated like any
other expression when the expression is used, i.e. only once if a "="
assignment refers to it, or every time if the assignment is ":="; this
latter case is used by the error generation routines.
Example:
\madxmp{
a := 3*ranf();
}
Every time a is used, it gets a random value assigned from a uniform
distribution between 0 and 3.
\madxmp{
error: ealign, range, dx:=sigma*gauss();
}
All elements in range are assigned independent random displacements
sampled from a Gaussian distribution with standard deviation sigma.
\section{Logical Expressions}
\label{sec:logicalexpr}
In matching it is desired to specify equality constraints, as well as
lower and upper limits for a quantity. \madx accepts the following forms
of constraints:
\madbox{
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\= \kill
name = expression \>! equality constraint \\
name < expression \>! upper limit \\
name > expression \>! lower limit \\
name < expression, name > expression \>! both upper and lower limit \\
\>! for the same name
}
\section{Variable Names}
\label{sec:variable}
A variable name can have one of the formats:
\madbox{
parameter-name \\
element-name->attribute-name \\
command-name->attribute-name \\
beam\%sequence-name->attribute-name \\
table(table-name,..,..)
}
The first format refers to the value of the \href{parameter.html}{global
parameter} "parameter-name".
The second and third formats refer to the
\href{real.html}{real attribute} "attribute-name" of the element
"element-name", or the command "command-name".
The fourth format is specific
to beams belonging to a particular sequence (for details see
\href{sequence.html#beam}{sequences and beams}).
The fifth format allows
extraction of variables from existing tables, as specified in
\href{expression.html#table}{table access}.
\section{Regular Expressions}
\label{sec:regex}
Some commands allow selection of items via "regular expression"
strings. Such a pattern string \textbf{must} be enclosed in single or
double quotes. \madx follows regexp (Unix regular expression patterns)
for matching. The following features are implemented:
A "search string" below is the string containing the pattern, a "target
string" is the string being searched for a possible match with the
pattern.
\begin{madlist}
\ttitem{"\textasciicircum"} at the start of the search string: Match
following search string at the start of the target string;
otherwise the search string can start anywhere in the target
string. To search for a genuine "\textasciicircum" anywhere, use
"$\backslash$\textasciicircum".
\ttitem{"\$"} at the end of the search string: Match preceding search
string at the end of the target string; otherwise the search string
can end anywhere in the target string. To search for a genuine
"\$" anywhere, use "$\backslash$\$".
\ttitem{"."} stands for an arbitrary character; to search for a genuine
".", use "$\backslash$."
\ttitem{"[xyz]"} stands for one character belonging to the string
contained in brackets (example: "[abc]" means one of a, b, c).
\ttitem{"[a-ex-z]"} stands for ranges of characters (example:
"[a-zA-Z]" means any letter).
\ttitem{"[\textasciicircum xyz]"} (i.e. a "\textasciicircum" as first
character in a square bracket) stands for exclusion of all
characters in the list, i.e. "[\textasciicircum a-z]" means "any
character but a lower case letter".
\ttitem{"*"} allows zero or more repetitions of the preceding
character, either specified directly, or from a list. (examples:
"a*" means zero or more occurrences of "a", "[A-Z]*" means zero or
more upper-case letters).
\ttitem{"$\backslash$c"} (e.g. "$\backslash$.") removes the special
meaning of character c.
\end{madlist}
All other characters stand for themselves.
Example:
\madxmp{
SELECT, FLAG=twiss, PATTERN="\textasciicircum d..\$" ; \\
SELECT, FLAG=twiss, PATTERN="\textasciicircum k.*qd.*$\backslash$.r1\$" ;
}
The first command selects all elements whose names have exactly three
characters and begin with the letter "D". The second command selects
elements beginning with the letter "K", containing the string "QD", and
ending with the string ".R1". The two occurrences of ".*" each stand for
an arbitrary number (including zero) of any character, and the
occurrence "$\backslash$." stands for a literal period.
\section{Relations between Variable Parameters}
\label{sec:relations} \label{sec:defer}
A relation is established between variables by one of two statements
\madbox{
xxxxxxxxxxxxxxxx\= \kill
parameter-name \>= expression; \\
parameter-name :\>= expression;
}
The first form evaluates the expression on the right immediately and
assigns its value to the parameter. It is an immediate assignment.
The second form assigns the value by evaluating the expression on the
right every time the parameter is actually used. It is a deferred
assignment.
This mechanism holds as well for element parameters that can be defined
with either immediate or deferred assignments.
Attention! If you want
to modify e.g. the strength of a quadrupole later (e.g. in a match, or
by entering a new value for a parameter on which it depends) then the
defition has to be
\madxmp{QD: QUADRUPOLE, K1 := ak1;}
and not
\madxmp{QD: QUADRUPOLE, K1 = ak1;}
In the latter case, K1 will be set to the current value of ak1 at the
time of declaration, and will not change when ak1 later changes.
Parameters that have not yet been defined at time of evaluation have a
zero value.
Example:
\madxmp{
gev = 100; \\
BEAM, ENERGY=gev;
}
The parameter on the left may appear on the right as well in the
computer science form of assignments:
\madxmp{x = x+1;}
increases the value of x by 1. \\
Successive definitions are allowed in the first form of relations or
immediate assignments:
\madxmp{
a = b + 2; \\
b = a * b;
}
But circular definitions in the second form of relations, or
deferred assignments, are forbidden:
\madxmp{
a := b + 2; \\
b := a * b;
}
results in an error.
\chapter{Program Flow Statements}
\section{IF...ELSEIF...ELSE}
\label{sec:if}
\madbox{
IF (logical\_expression) \{ statements; \} \\ \\
ELSEIF (logical\_expression) \{ statements; \} \\ \\
ELSE \{ statements; \}
}
where "logical\_expression" is one of
\madxmp{
xxxxxxx\=xxxxxxxxxxxxxxxx\=xxxxx\= \kill
expr1 \>oper expr2 \\
expr11 \>oper1 expr12 \>\&\& \>expr21 oper2 expr22 \\
expr11 \>oper1 expr12 \>|| \>expr21 oper2 expr22
}
and {\tt oper} is one of
\begin{madlist}
\ttitem{==} equal
\ttitem{<>} not equal
\ttitem{<} less than
\ttitem{>} greater than
\ttitem{<=} less than or equal
\ttitem{>=} greater than or equal
\end{madlist}
The expressions are arithmetic expressions of type real. The statements
in the curly brackets are executed if the logical expression is true.
{\tt ELSEIF} constructs are only possible (in any number) behind an
{\tt IF}, or another {\tt ELSEIF}; the branch is executed if
"logical\_expression" is true, and if none of the preceding {\tt IF}
or {\tt ELSEIF} logical conditions was true.
{\tt ELSE} construct is only possible once behind an {\tt IF}, or
an {\tt ELSEIF}; the branch is executed if "logical\_expression" is
true, and if none of the preceding {\tt IF} or {\tt ELSEIF}
logical conditions was true.
{\bf Warning:}\\
Because {\tt IF ... ELSEIF ... ELSE} constructs are a \madx special
feature and not part of a full language, \madx does not deal gracefully with
other special constructs such as {\tt MACRO} or {\tt LINE} when they are placed
inside {\tt IF ...
ELSEIF ... ELSE} statements: this can lead to silent and/or catastrophic errors
and is due to the fact that {\tt MACRO} and {\tt LINE} constructs contain,
either explicitly or implicitly, a closing curly bracket that unbalances the
{\tt IF ... ELSEIF ... ELSE} statements.
However it is possible to nest {\tt IF ... ELSEIF ... ELSE} constructs to at
least six levels deep.
\section{WHILE}
\label{sec:while}
\madbox{
WHILE (logical\_condition) \{ statements; \}
}
executes the statements in curly brackets while the logical\_expression
is true.
{\bf Warning:}\\
Because {\tt WHILE} constructs are a \madx special
feature and not part of a full language, \madx does not deal gracefully with
other special constructs such as {\tt MACRO} or {\tt LINE} when they are placed
inside {\tt WHILE} statement blocks: this can lead to silent and/or
catastrophic errors and is due to the
fact that {\tt MACRO} and {\tt LINE} constructs contain, either explicitly or
implicitly, a closing curly bracket that unbalances the {\tt WHILE} statements.
However it is possible to nest {\tt WHILE} statements to at least six levels
deep.
Example giving the value of the first ten factorials:
\madxmp{
n = 1; m = 1; \\
while (n <= 10) \{ \\
\qquad m = m * n; value, m; \\
\qquad n = n + 1; \\
\};
}
\section{MACRO}
\label{sec:macro}
The MACRO construct allows the execution of a group of statements via a
single command. Optionally the MACRO construct takes arguments.
\madbox{
label: MACRO = \{ statements; \}; \\
label(arg1, \ldots ,argn): MACRO = \{ statements; \};
}
The first form allows the execution of the defined group of statements via a
single command,
\madxmp{EXEC, label;}
that executes the statements defined between curly brackets exactly
once. The {\tt EXEC} command can then be issued any number of times.
The second form allows to replace strings anywhere inside the statements
in curly brackets by other strings, or integer numbers prior to
execution. This is a powerful construct and should be handled with care.
Simple example:
\madxmp{
simple(xx,yy): MACRO = \{ xx = yy*yy + xx; VALUE, xx;\}; \\
a = 3; \\
b = 5; \\
EXEC, simple(a,b);
}
{\bf Passing arguments}\\
In the following example we use the fact that a "\$" in front of an
argument means that the truncated integer value of this argument is used
for replacement, rather than the argument string itself.
\madxmp{
tricky(xx,yy,zz): MACRO = \{mzz.yy: xx, l = 1.yy, kzz = k.yy;\}; \\
n=0; \\
WHILE \=(n < 3) \{ \\
\>n = n+1; \\
\>EXEC, tricky(quadrupole, \$n, 1); \\
\>EXEC, tricky(sextupole, \$n, 2); \\
\};
}
Whereas the actual use of the preceding example is NOT recommended,
a real life example, showing the full power (!) of macros is to be
found under \href{foot.html}{macro usage} for the usage, and
under \href{foot.html#macro}{macro definition} for the
definition.
Because {\tt MACRO} statements are a \madx
construct and not part of a full language, \madx allows only one level
of inclusion of another {\tt IF ... ELSEIF ... ELSE}, {\tt WHILE}
or {\tt MACRO} statements.
Macros cannot be called with number arguments but always with string
arguments. In case numerical values should be passed to a {\tt MACRO} in an
{\tt EXEC} statement, one can conveniently use variables names:
\madxmp{
n1=99; n2=219;\\
EXEC, thismacro(\$n1, \$n2);
}
instead of
\madxmp{
EXEC, thismacro(\$99, \$129); ! fails...
}
\chapter{General Control Statements}
\madxconsists of a core program, and modules for specific tasks such as
twiss parameter calculation, matching, thin lens tracking, and so on.
The statements listed here are those executed by the program core. They
deal with the I/O, element and sequence declaration, sequence
manipulation, statement flow control (e.g. IF, WHILE), MACRO
declaration, saving sequences onto files in \madx or \madeight format,
and so on.
\section{EXIT, QUIT, STOP}
\label{sec:exit} \label{sec:quit} \label{sec:stop}
Any of these three commands ends the execution of \madx:
\madbox{
EXIT;
}
\madbox{
QUIT;
}
\madbox{
STOP;
}
\section{HELP}
\label{sec:help}
The HELP command prints all parameters, and their defaults values, for
the statement given; this includes basic element types.
\madbox{
HELP, statement\_name;
}
\section{SHOW}
\label{sec:show}
The SHOW command prints the "command" (typically "beam", "beam\%sequ",
or an element name), with the actual value of all its parameters.
\madbox{
SHOW, command;
}
\section{VALUE}
\label{sec:value}
The VALUE command evaluates the current value of all listed expressions,
constants or variables, and prints the result in the form of \madx
statements on the assigned output file.
\madbox{
VALUE, expression\{, expression\} ;
}
Example: \\
\madxmp{
a = clight/1000.; \\
value, a, pmass, exp(sqrt(2));
}
results in
\madxmp{
a = 299792.458 ; \\
pmass = 0.938272046 ; \\
exp(sqrt(2)) = 4.113250379 ; \\
}
\section{OPTION}
\label{sec:option}
The {\tt OPTION} commands sets the logical value of a number of flags
that control the behavior of \madx.
\madbox{
OPTION, flag=logical;
}
Because all attributes of {\tt OPTION} are logical flags, the
following two statements are identical:
\madxmp{
OPTION, flag = true;\\
OPTION, flag;
}
And the following two statements are also identical:
\madxmp{
OPTION, flag = false;\\
OPTION, -flag;
}
Several flags can be set in a single {\tt OPTION} command, e.g.
\madxmp{
OPTION, ECHO, WARN=true, -INFO, VERBOSE=false;
}
The available flags, their default values and their effect on \madx when
they are set to {\tt TRUE} are listed in table \ref{table:options}.\selectlanguage{english}
\begin{table}
[ht]
\caption{{Flags available to {\tt OPTION} command}}
\vspace{1ex}
\begin{center}
\label{table:options}
\begin{tabular}{|l|c|l|}
\hline
{\bf FLAG } & {\bf default} & {\bf effect if {\tt TRUE}} \\
\hline
{\tt ECHO} & true & echoes the input on the standard output file \\
{\tt WARN} & true & issues warning statements\\
{\tt INFO} & true & issues information statements\\
{\tt DEBUG} & false & issues debugging information \\
{\tt ECHOMACRO} & false & issues macro expansion printout for debugging \\
{\tt VERBOSE} & false & issues additional printout in makethin \\
{\tt TRACE} & false & prints the system time after each command \\
{\tt VERIFY} & false & issues a warning if an undefined variable is used
\\
\hline
{\tt TELL} & false & prints the current value of all options \\
{\tt RESET} & false & resets all options to their defaults \\
\hline
{\tt NO\_FATAL\_STOP} & false & Prevents madx from stopping in case of a
fatal error \\
& & {\bf Use at your own risk !} \\
\hline
{\tt RBARC} & true & converts the RBEND straight length into the arc
length \\
{\tt THIN\_FOC} & true & enables the 1/(rho**2) focusing of thin dipoles \\
{\tt BBORBIT} & false & the closed orbit is modified by beam-beam kicks
\\
{\tt SYMPL} & false & all element matrices are symplectified in Twiss
\\
{\tt TWISS\_PRINT} & true & controls whether the twiss command produces
output \\
{\tt THREADER} & false & enables the threader for closed orbit finding in
Twiss \\
& & (see Twiss module) \\
\hline
\end{tabular}
\end{center}
\end{table}
The option {\tt RBARC} is implemented for backwards compatibility
with \madeight up to version 8.23.06 included; in this version, the
RBEND length was just taken as the arc length of an SBEND with inclined
pole faces, contrary to the \madeight manual.
\section{EXEC}
\label{sec:exec}
Each statement may be preceded by a label, when parsed and executed the
statement is then also stored and can be executed again with
\madbox{
EXEC, label;
}
This mechanism can be invoked any number of times, and the executed
statement may be calling another {\tt EXEC}, etc.
Note however, that the main usage of this \madx construct is the
execution of a \href{special.html#macro}{macro}.
\madxmp{
tw: TWISS, FILE, SAVE; ! first execution of TWISS \\
... \\
EXEC, tw; ! second execution of the same TWISS command \\
}
\section{SET}
\label{sec:set}
The {\tt SET} command is used in two forms:
\madbox{
SET, FORMAT=string \{, string\} ;\\
SET, SEQUENCE=string;
}
The first form of the {\tt SET} command defines the formats for the
output precision that \madx uses with the {\tt SAVE}, {\tt SHOW},
{\tt VALUE} and {\tt TABLE} commands. The formats can be
given in any order and stay valid until replaced.
The formats follow the C convention and must be included in double
quotes. The allowed formats are \\
{\tt {\it n}d} for integers with a field-width = {\it n}, \\
{\tt {\it n}.{\it m}f} or {\tt {\it n}.{\it m}g} or {\tt {\it
n}.{\it m}e} for floats with field-width = {\it n} and precision =
{\it m}, \\
{\tt {\it n}s} for strings with a field-width = {\it n}.\\
The default is "right adjusted", a "-" changes it to "left adjusted".
{\bf Example:}\\
\madxmp{
SET, FORMAT="12d", "-18.5e", "25s";
}
The default formats are {\tt "10d", "18.10g"} and {\tt "-18s"}.
Example:
\begin{verbatim}
set,format="22.14e";
\end{verbatim}
changes the current floating point format to 22.14e; the other formats remain untouched.
\begin{verbatim}
set,format="s","d","g";
\end{verbatim}
sets all formats to automatic adjustment according to C conventions.
The second form of the {\tt SET} command allows to select the
current sequence without the "USE" command, which would
bring back to a bare lattice without errors. The command only works
if the chosen sequence has been previously activated with a {\tt USE} command,
otherwise a warning is issued and \madx continues with the
unmodified current sequence. This command is particularly useful for
commands that do not have the sequence as an argument like "EMIT" or
"IBS".
\section{SYSTEM}
\label{sec:system}
\madbox{
SYSTEM, "string";
}
transfers the quoted string to the system for execution. The quotes are
stripped and no check of the return status is performed by \madx.
{\bf Example:}\\
\madxmp{
SYSTEM,"ln -s /afs/cern.ch/user/j/joe/public/some/directory shortname";
}
makes a local link to an AFS directory with the name "shortname" on a
UNIX system.
Attention: Although this command is very convenient, it is clearly not portable
across systems and it should probably be avoided if one intends to share \madx
scripts with collaborators working on other platforms.
\section{TITLE}
\label{sec:title}
\madbox{
TITLE, "string";
}
the string in quotes is inserted as title in various table outputs and
plot results.
\section{USE}
\label{sec:use}
\madxoperates on beamlines that must be loaded and expanded in memory
before other commands can be invoked. The {\tt USE} allows this
loading and expansion.
\madbox{
USE, \=PERIOD=sequence\_name, SEQUENCE=sequence\_name, \\
\>RANGE=range, \\
\>SURVEY=logical;
}
The attributes to the {\tt USE} command are:
\begin{madlist}
\ttitem{SEQUENCE} name of the sequence to be loaded and expanded.
\ttitem{PERIOD} name of the sequence to be loaded and expanded. \\
{\tt PERIOD} is an alias to {\tt SEQUENCE} that was kept for
backwards compatibility with \madeight and only one of them should be
specified in a {\tt USE} statement.
\ttitem{RANGE} specifies a \hyperref[sec:range]{range}.
restriction so that only the specified part of the named sequence is
loaded and expanded.
\ttitem{SURVEY} option to plug the survey data into the sequence elements
nodes on the first pass (see \hyperref[chap:survey]{\tt SURVEY}).
\end{madlist}
Note that reloading a sequence with the {\tt USE} command reloads a
bare sequence and that any {\tt ERROR} or orbit correction previously
assigned or associated to the sequence are forgotten.
A mechanism to select a sequence without this side effect of the
{\tt USE} command is provided with the {\tt SET, SEQUENCE=...} command.
\section{SELECT}
\label{sec:select}
Some \madx commands can perform specific operations on selected elements
or ranges of elements and can produce specific output for selected
elements or ranges of elements.
The selection is made through the {\tt SELECT} command and applies to
subsequent commands.
\madbox{
SELECT, \=FLAG=string, RANGE=string, CLASS=string, PATTERN=string, \\
\>SEQUENCE=string, FULL=logical, CLEAR=logical,\\
\>COLUMN=string\{,string\}, SLICE=integer, THICK=logical;
}
The attributes to the {\tt SELECT} command are:
\begin{madlist}
\ttitem{FLAG} determines the applicability of the
{\tt SELECT} statement and the attribute value can be one of
the following:
\begin{madlist}
\ttitem{SEQEDIT} selection of elements for the
\hyperref[sec:seqedit]{\tt SEQEDIT} module.
\ttitem{ERROR} selection of elements for the
\hyperref[chap:error]{error assignment} module.
\ttitem{MAKETHIN} selection of elements for the
\hyperref[chap:makethin]{\tt MAKETHIN} command that
converts the sequence into one with thin elements.
\ttitem{SECTORMAP} selection of elements for the
\hyperref[subsec:sectormap]{\tt SECTORMAP} output file
from the \hyperref[chap:twiss]{\tt TWISS} module.
\ttitem{SAVE} selection of elements for the
\hyperref[sec:save]{\tt SAVE} command.
\ttitem{tablename} is a table name such as {\tt twiss},
{\tt track} etc., and the rows and columns to be written are
selected.
\end{madlist}
\ttitem{RANGE} the range of elements to be selected as defined in
section \ref{sec:range} on \hyperref[sec:range]{range} selection.
\ttitem{CLASS} the class of elements to be selected as defined in
section \ref{sec:class} on \hyperref[sec:class]{class} selection.
\ttitem{PATTERN} the regular expression pattern for the element names
to be selected as defined in section \ref{sec:regex} on selection via
\hyperref[sec:regex]{regular expressions}.
\ttitem{SEQUENCE} the name of a sequence to which the selection is applied.
\ttitem{FULL} a logical falg to select ALL positions in the sequence
for the named flag. \\
For the flag {\tt TWISS}, this attribute includes all standard
columns for a {\tt TWISS} table, and therefore the following two
statements are equivalent:
\madxmp{
SELECT, FLAG=twiss, COLUMN= name, s, betx, ..., var1; \\
SELECT, FLAG=twiss, FULL, COLUMN= var1;
}
{\tt FULL=true} is the default for the {\tt MAKETHIN} flag and for tables:
{\sl eg} {\tt SELECT, FLAG=makethin;} is equivalent to {\tt SELECT,
FLAG=makethin, FULL;}
\ttitem{CLEAR} deselects ALL positions in the sequence for the flag
"name". This is the default for {\tt ERROR} and {\tt SEQEDIT}
flags. \\
{\sl eg} {\tt SELECT, FLAG=error;} is equivalent to {\tt SELECT, FLAG=error, CLEAR;}
\ttitem{COLUMN} is only valid for tables and takes as attribute value
a list of columns to be written into the TFS file. The special "\_name"
argument refers to the actual name of the element.
\ttitem{SLICE} is the number of slices into which the selected
elements have to be cut and is only used by
\hyperref[chap:makethin]{\tt MAKETHIN}. (Default = 1).
\ttitem{THICK} is a logical flag to indicate whether the selected
elements are treated as thick elements by the \hyperref[chap:makethin]{\tt
MAKETHIN} command. \\
This only applies up to now to \hyperref[sec:quadrupole]{\tt
QUADRUPOLE}s and \hyperref[sec:bend]{\tt BEND}s for which thick maps
have been explicitely derived.
\vskip5mm
{\bf Composition of {\tt SELECT} statements:} \\
The selection criteria provided on a single {\tt SELECT} statement are logically
{\tt AND}ed, {\sl ie} selected elements have to fulfill {\bf all}
provided criteria in the single {\tt SELECT} statement.
The selection criteria on different {\tt SELECT} statements are logically
{\tt OR}ed, {\sl ie} selected elements have to fulfill {\bf any} of the
selection criteria provided by the different {\tt SELECT} statements.
All selections for a given flag remain valid until a {\tt SELECT} statement
with the {\tt CLEAR} argument is specified for the same flag.
Note that because of these composition rules, it is considered good
practice to start by clearing the selection for a given flag before
making a new selection, eg:
\madxmp{
SELECT, FLAG=twiss, CLEAR; \\
SELECT, FLAG=twiss, CLASS=MQ; \\
SELECT, FLAG=twiss, RANGE=MQ[5]/MQ[7]; \\
...
}
\vskip5mm
{\bf Examples:}
\madxmp{
SELECT, FLAG = ERROR, CLASS = quadrupole, RANGE = mb[1]/mb[5];\\
SELECT, FLAG = ERROR, PATTERN = "\textasciicircum mqw.*";
}
selects all quadrupoles in the range mb[1] to mb[5], as well as all
elements (in the whole sequence) with name starting with "mqw", for
treatment by the \hyperref[chap:error]{\tt ERROR} module.
\vskip5mm
\madxmp{
SELECT, FLAG=SAVE, CLASS=variable, PATTERN="abc.*"; \\
SAVE, FILE=mysave;
}
saves all variables (and sequences) containing "abc" in their name,
but does not save elements with names containing "abc" since the class
"variable" does not exist.
\vskip5mm
\madxmp{
sig1 := sqrt(beam->ex*table(twiss,betx)); \\
SELECT, FLAG=twiss, COLUMN= \_name, s, betx, ..., sig1; ! or equivalently \\
SELECT, FLAG=twiss, FULL, COLUMN= sig1; ! default columns + new
}
writes the current value of ``sig1'' into the {\tt TWISS} table each
time a new line is added; Note that the values from the same (current)
line can be are accessed by the variable ``sig1''.
The \hyperref[chap:plot]{\tt PLOT} command also accepts the new variable
in the table.
\label{chap:files}
Note that the filenames given as attribute values in File Handling statements
must be explicit names and should not contain wildcard characters since the
filename strings are not passed to the underlying Operating System for evaluation.
\section{ASSIGN}
\label{sec:assign}
\madbox{
ASSIGN, ECHO="filename", TRUNCATE;
}
where "filename" is the name of an output file, or "terminal" and
{\tt TRUNCATE} specifies if the file must be truncated when opened (ignored
for terminal).
This allows switching the echo stream to a file or back,
but only for the commands \hyperref[sec:value]{\tt VALUE},
\hyperref[sec:show]{\tt SHOW}, and \hyperref[sec:print]{\tt PRINT}.
Allows easy composition of future \madx input files. A real life example
(always the same) is to be found under \href{foot.html}{footprint example}.
\section{CALL}
\label{sec:call}
\madbox{
CALL, FILE="filename";
}
where "filename" is the name of an input file. This file will be read
until a "RETURN" statement, or until End\_Of\_File; The file being
"called" may in turn contain any number of {\tt CALL} statements
itself, and so on to any depth.
\section{RETURN}
\label{Sec:return}
\madbox{
RETURN;
}
ends reading from a "called" file; if encountered in the standard input
file, it ends the program execution.
\section{PRINT}
\label{sec:print}
\madbox{
PRINT, TEXT="string";
}
prints the quoted text string to the current output file (see ASSIGN
above). The text can be edited with the help of a
\href{special.html#macro}{macro statement}. For more details, see
there. [TBC]
\section{PRINTF}
\label{sec:printf}
\madbox{
PRINTF, TEXT="string", VALUE= expr{,expr};
}
prints the numerical values specified in the value field, formatted
according to the string format provided in the text field, to the
current output file.
The string format can take numeric C or \madx format specifiers for
double real values; integer and string formats are not supported but
can be approximated with the \%g in the case of integers, and via
\hyperref[sec:macro]{\tt MACRO} statements, which perform string
substitution, themselves containing a \hyperref[sec:print]{\tt PRINT}
statement.
The maximum number of values that can be printed in one
statement is limited to 100.
If the number of format specifiers given in the string is higher
than the number of values in the value field, undefined values are printed
where they are not explicitly provided.
If the number of format specifiers given in the string is lower
than the number of values in the value field, the values that
do not correspond to a format specifier are ignored.
{\bf Example:}
\madxmp{
xxxxxxx\=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\= \kill
a = 1.2; b = 3.4/0.3; c := 0.8*a/b; \\
PRINTF, \>TEXT="String with floats a=\%f, b=\%.3g, text and MAD float c=\%F;", \\
\>VALUE = a,b,c; \\
PRINTF, \>TEXT="More specifiers than values: \%f, \%.3g, \%F", \>VALUE = a,b; \\
PRINTF, \>TEXT="More values than specifiers: \%f, \%.3g", \>VALUE = a,b,c;
}
produces the following output:
\begin{verbatim}
String with floats a=1.200000, b=11.3, text and MAD float c= 0.08470588235;
More specifiers than values: 1.200000, 11.3, 6.953222976e-310
More values than specifiers: 1.200000, 11.3
\end{verbatim}
Note that {\tt PRINTF}, like {\tt PRINT}, produces output that
cannot be read back by \madx. For output that can be read back by \madx,
use the command {\tt VALUE} or TFS tables.
Note also that a percent sign (\%) can be printed using the format
\verb|text="%%"|.
\section{RENAMEFILE}
\label{sec:renamefile}
\madbox{
RENAMEFILE, FILE="filename", TO="new\_filename";
}
renames the file "filename" to "new\_filename" on disk. \\
It is more portable than an equivalent \hyperref[sec:system]{\tt SYSTEM} call:
\madxmp{
SYSTEM("mv filename new\_filename"); ! Unix specific
}
\section{COPYFILE}
\label{sec:copyfile}
\madbox{
COPYFILE, FILE="filename", TO="new\_filename", APPEND=logical;
}
copies the file "filename" to the file "new\_filename" on disk.
The attribute {\tt APPEND=true} causes {\tt COPYFILE} to append the content of
"filename" at the end of the file "new\_filename".\\
The default value {\tt APPEND=false} causes the
replacement of the content of "new\_filename" with the content of "filename".
{\tt COPYFILE, APPEND=true...} is more portable than an equivalent \hyperref[sec:system]{\tt SYSTEM} call:
\madxmp{
SYSTEM("copy /y filename new\_filename"); ! Windows specific
}
\section{REMOVEFILE}
\label{sec:removefile}
\madbox{
REMOVEFILE, FILE="filename";
}
removes the file "filename" from disk. \\
It is more portable than an equivalent \hyperref[sec:system]{\tt SYSTEM} call:
\madxmp{
SYSTEM("rm filename"); ! Unix specific
}
\label{chap:tables}
\section{CREATE}
\label{sec:create}
\madbox{
CREATE, TABLE=tabname, COLUMN= var\{, var\} \{, \_name\} ;
}
creates a table with the specified variables as columns.
This table is initially empty and can be subsequently filled, and
eventually written to file in TFS format.
The special variable name attribute "\_name" adds
the element name to the table at the specified column.
See the \href{../Introduction/select.html#ucreate}{user table I}
example;
or an example of joining 2 tables of different length in one table
including the element name:
\href{../Introduction/select.html#screate}{user table II}
\section{DELETE}
\label{sec:delete}
\madbox{
DELETE, SEQUENCE=seqname, TABLE=tabname;
}
deletes a sequence with name "seqname" or a table with name "tabname"
from memory. The sequence deletion is done without influence on other
sequences that may have elements that were in the deleted sequence.
\section{READTABLE}
\label{sec:readtable}
\madbox{
READTABLE, FILE="filename";
}
reads the TFS file "filename" containing a \mad table and loads the
table back into memory. This table can then be manipulated as any other
table, i.e. its values can be accessed, it can be plotted, written out
again etc.
\section{READMYTABLE}
\label{sec:readmytable}
\madbox{
READMYTABLE, FILE="filename", TABLE=tabname;
}
reads a TFS file "filename" containing a \mad table and loads the table
into memory with the name "tabname". This table
can then be manipulated as any other table, i.e. its values can be
accessed, it can be plotted, written out again etc.
An internal name for the table can be freely assigned while for the
command READTABLE the tabname is taken from the information section of
the table itself.
This feature allows to store multiple tables of the same type in memory without
overwriting existing ones.
\section{TABSTRING}
\label{sec:tabstring}
Note: this is not a command and should appear in the variables section
\madbox{
TABSTRING(arg1,arg2,arg3)
}
The "string function" TABSTRING(arg1,arg2,arg3) with exactly three
arguments; arg1 is a table name (string), arg2 is a column name
(string), arg3 is a row number (integer), count starts at 0. The
function can be used in any context where a string appears; in case
there is no match, it returns "\_void\_".
\section{WRITE}
\label{sec:write}
\madbox{
WRITE, TABLE=tabname, FILE="filename";
}
writes the table "tabname" onto the file "filename"; only the rows and
columns of a preceding \texttt{SELECT, FLAG=table,...;} are written.
If no \texttt{SELECT} has been issued for this table, only the header is
written to file.
If the FILE argument is omitted, the table is written to standard output.
\section{SETVARS}
\label{sec:setvars}
The \texttt{SETVARS} command sets the variables with values extracted
from the row of a table.
\madbox{
SETVARS, TABLE=tabname, ROW=integer;
}
The attributes of \texttt{SETVARS} are:
\begin{madlist}
\ttitem{TABLE} the name of the table. (Default: none)
\ttitem{ROW} the row number containing the values. (Default: -1)
\end{madlist}
Negative \texttt{ROW} values are allowed and count the row numbers from
the last row, allowing access to the table in reverse order of rows:
\texttt{ROW~=~-1} accesses the last row of the table,
\texttt{ROW~=~-2} accesses the penultimate (one before last) row,
etc\ldots
Trying to access the table forward beyond the last row, i.e. \texttt{ROW}
strictly greater than {\tt nrow} the number of rows in the table, or
trying to access the table backwards before the first row, i.e. \texttt{ROW}
strictly lower than {\tt -nrow}, or trying to access the illegal
\texttt{ROW=0}, all result in a ``row out of bound'' message and no
variable values are returned and set.
\section{SETVARS\_LIN}
\label{sec:setvars_lin}
The {\tt SETVARS\_LIN} command sets the variables with values calculated
by linear interpolation, or extrapolation, between two rows of a table.
\madbox{
SETVARS\_LIN, TABLE=tabname, ROW1=integer, ROW2=integer, PARAM=string;
}
The attributes of \texttt{SETVARS\_LIN} are:
\begin{madlist}
\ttitem{TABLE} the name of the table. (Default: none)
\ttitem{ROW1} a first row number with values for interpolation. (Default: 0)
\ttitem{ROW2} a second row number with values for interpolation. (Default: 0)
\ttitem{PARAM} a string containing the linear interpolation factor or
the name of a variable or expression containing the interpolation
factor. If the resulting value of {\tt PARAM} is outside the
$[0,1]$ interval, the result is a linear extrapolation. \\
(Default: "interp", itself defaulting to a value of 0.0 when evaluated)
\end{madlist}
{\tt SETVARS\_LIN} sets the variables with values calculated through
the following formula that \madx constructs internally as a deferred
expression which is immediately evaluated:
\madxmp{value := value(row1)*(1-param) + value(row2)*param;}
Both the expression and the value of the expression are available to the
user through respectively the commands \hyperref[sec:show]{\tt SHOW}
and \hyperref[sec:value]{\tt VALUE}.
When the values are represented as strings, e.g. the name or
keyword of elements, the resulting value is the string in {\tt ROW1}.
Negative {\tt ROWi} values are allowed and count the row numbers from
the last row, allowing access to the table in reverse order of rows:
{\tt ROWi~=~-1} accesses the last row of the table,
{\tt ROWi~=~-2} accesses the penultimate (one before last) row,
etc\ldots
Trying to access the table forward beyond the last row, i.e. {\tt ROWi}
strictly greater than {\tt nrow} the number of rows in the table, or
trying to access the table backwards before the first row, i.e. {\tt ROWi}
strictly lower than {\tt -nrow}, or trying to access the illegal
{\tt ROWi=0}, all result in a ``row out of bound'' message and the
expression is not constructed or evaluated.
{\bf Example:}
\madxmp{
! extracts the position of the centre of each element from a standard \\
! TWISS table giving positions at end of elements: \\
len = table(twiss,tablelength); \\
interpolate = 0.5; \\
i = 2;\\
WHILE \=(i < len) \{ \\
\>SETVARS\_LIN, TABLE=twiss, ROW1=i-1, ROW2=i, PARAM=interpolate; \\
\>! now variables are interpolated at the center of the elements. \\
\>! in particular S holds the position of the center of the element. \\
\>SHOW, s; VALUE, s; \\
\>\ldots \\
\>i = i + 1; \};
}
\section{FILL}
\label{sec:fill}
The {\tt FILL} command fills a row of a table with the current values
of all declared column variables of the table.
\madbox{
FILL, TABLE=tabname, ROW=integer;
}
The FILL command takes two arguments:
\begin{madlist}
\ttitem{TABLE} is the name of the table to be filled. The table must
have been \hyperref[sec:create]{created} beforehand.
The table can then be \hyperref[sec:write]{written} to file in {\tt TFS}
format.
\ttitem{ROW} is the row number to be filled with the current values of
all column variables. \\
{\tt ROW=0}, or {\tt ROW=nrow + 1}, where {\tt nrow} is the current
number of rows in the table, causes {\tt FILL} to add a row at
the end of the table and fill it with the current values of all
column variables. \\ (Default: 0)
\end{madlist}
Negative {\tt ROW} values are allowed and count the row numbers from
the last row, allowing access to the table in reverse order of rows:
{\tt ROW = -1} accesses the last row of the table,
{\tt ROW = -2} accesses the penultimate (one before last) row,
etc\ldots
Trying to access the table forward beyond the last row, i.e. \texttt{ROW}
strictly greater than {\tt nrow + 1}, where {\tt nrow} is the number of
rows in the table, or trying to access the table backwards before the
first row, i.e. \texttt{ROW} strictly lower than {\tt -nrow}, both
result in a ``row out of bound'' message and no values are filled in the
table.
{\bf Reminder:} One can get access to the current number of rows in a
table using the variable \madxmp{TABLE(tablenanme, TABLELENGTH)}
See as well the \href{../Introduction/select.html#ucreate}{user table}
example.
\section{SHRINK}
\label{sec:shrink}
The {\tt SHRINK} command removes a number of rows at the end of a table.
\madbox{
SHRINK, TABLE=tabname, ROW=integer;
}
The {\tt SHRINK} command takes two arguments:
\begin{madlist}
\ttitem{TABLE} is the name of the table from which rows should be removed.
The table must have been previously \hyperref[sec:create]{created} and
\hyperref[sec:fill]{filled} or read from file with \hyperref[sec:readtable]
{\tt READTABLE} or \hyperref[sec:readmytable]{\tt READMYTABLE}.
\ttitem{ROW} is the number of the last row to be kept in the table.
All rows beyond the given row number are removed. \\
Negative values are allowed and count the row numbers from
the last row, allowing access to the table in reverse order of rows:
\texttt{ROW~=~-1} removes the last row of the table,
\texttt{ROW~=~-2} removes the last two rows of the table,
etc\ldots \\
(Default: -1)
\end{madlist}
Trying to access the table forward beyond the last row, i.e. \texttt{ROW}
strictly greater than {\tt nrow}, where {\tt nrow} is the number of
rows in the table, or trying to access the table backwards before the
first row, i.e. {\tt ROW} strictly lower than {\tt -nrow}, both
result in a ``row out of bound'' message and no values are filled in the
table.
\label{chap:beam}
Many commands in \mad require the prior setting of various quantities related
to the beam in the machine. Therefore, \mad will stop with a fatal
error if an attempt is made to expand (\hyperref[sec:use]{\tt USE}) a sequence
for which no {\tt BEAM} command has been issued before.
\section{BEAM}
\label{sec:beam}
The quantities are entered by a {\tt BEAM} command:
\madbox{
BEAM, \= PARTICLE=string, MASS=real, CHARGE=real,\\
\> ENERGY=real, PC=real, GAMMA=real, BETA=real, BRHO=real,\\
\> EX=real, EXN=real, EY=real, EYN=real,\\
\> ET=real, SIGT=real, SIGE=real,\\
\> KBUNCH=integer, NPART=real, BCURRENT=real,\\
\> BUNCHED=logical, RADIATE=logical, BV=integer, SEQUENCE=string;
}
The attributes of the {\tt BEAM} command are:
\begin{madlist}
\ttitem{PARTICLE} The name of particles in the beam. Default= {\tt POSITRON}\\
\mad knows the restmass and the charge for the following particles:
\begin{madlist}
\ttitem{POSITRON} The particles are positrons ({\tt MASS=$m_e$, CHARGE=1})
\ttitem{ELECTRON} The particles are electrons ({\tt MASS=$m_e$, CHARGE=-1})
\ttitem{PROTON} The particles are protons ({\tt MASS=$m_p$, CHARGE=1})
\ttitem{ANTIPROTON} The particles are anti-protons ({\tt MASS=$m_p$,
CHARGE=-1})
\ttitem{POSMUON} The particles are positive muons ({\tt MASS=$m_{\mu}$,
CHARGE=1})
\ttitem{NEGMUON} The particles are negative muons ({\tt MASS=$m_{\mu}$,
CHARGE=-1})
\ttitem{ION} The particles are simple generic ions ({\tt MASS=$m_n$,
CHARGE=1})
\end{madlist}
\ttitem{MASS} the restmass of the particles in the beam in GeV. \\
(Default=$m_e \approx 0.511\ 10^{-3}$ GeV).\\
Note that a zero mass particle is not allowed in \mad.
\ttitem{CHARGE}\label{beam_charge} the electrical charge of the
particles in the beam in units of $q_p$, the proton charge. (Default=1) \\
Note that a zero charge particle is not allowed in \mad.
The order of precedence for arguments is: {\tt particle->(mass+charge)}\\
If the particle name given is recognized in the list above, the restmass
and charge are set directly by \madx, and the {\tt MASS} and {\tt CHARGE}
arguments provided in the {\tt BEAM} command are
simply ignored. For other particles, and in particular for ions, any
combination of name, mass and charge can be entered independently.
\begin{madlist}
\ttitem{ENERGY} \label{beam_energy} Total energy per particle in
GeV.\\ If given, it must be greater than the particle
restmass. (Default=1 GeV)
\ttitem{PC} Particle momentum times the speed of light, in GeV. \\
If given, it must be greater than zero.
\ttitem{GAMMA} Relativistic factor, {\sl ie} ratio between total
energy and rest energy of the particles: {\tt GAMMA = ENERGY/MASS = $E / m_0
c^2$}.
\\ {\tt GAMMA} must be greater than one.
\ttitem{BETA} Ratio between the speed of the particle
and the speed of light: ${\tt BETA} = v / c$.\\
{\tt BETA} must be strictly less than one.
\ttitem{BRHO} Magnetic rigidity of the particles in T.m. \\
{\tt BRHO = $P / abs(q)$ = PC / ( abs(CHARGE) * c * 1.e-9)}.
\end{madlist}
The order of precedence for arguments is: {\tt energy->pc->gamma->beta->brho}
Note that if the restmass is changed after the energy has been set, ie
in separate {\tt BEAM} commands, the energy is left unchanged and the momentum
{\tt PC} and relativistic factor {\tt GAMMA} are recalculated.
\begin{madlist}
\ttitem{EX} The horizontal emittance $\epsilon_x$ (default: 1 m).
\ttitem{EY} The vertical emittance $\epsilon_y$ (default: 1 m).
\ttitem{ET} The longitudinal emittance $\epsilon_t$ (default: 1 m).
\ttitem{EXN} The normalised horizontal emittance [m]:
$\epsilon_{xn} = \sqrt{\gamma^2 - 1} \ \epsilon_x = \beta \gamma\ \epsilon_x$
\ttitem{EYN} The normalised vertical emittance [m]:
$\epsilon_{yn} = \sqrt{\gamma^2 - 1} \ \epsilon_y = \beta \gamma\ \epsilon_y$
\ttitem{SIGT} The bunch length $c\ \sigma_t$ in [m].
\ttitem{SIGE} The \emph{relative} energy spread
$\sigma_E / E$ in [1].
\end{madlist}
Note that up to version 5.02.04 the definition of normalised emittance used in
\madxwas referring to the so-called 2-sigma geometric emittance:
$\epsilon_{n} = 4 \sqrt{\gamma^2 - 1} \ \epsilon = 4 \beta \gamma\ \epsilon$
This definition was different from the definition usually found in literature
and used for example in the \hyperref[chap:aperture]{\tt APERTURE} module.\\
The standard one sigma definition is now used across all \madx modules.
Certain commands compute the synchrotron tune $Q_s$ taking into account
the settings of RF cavities.
If $Q_s$ is non-zero, the relative energy spread and
the bunch length are calculated with
\begin{align}
\sigma_E / p_0 c &= \sqrt{\epsilon_t\ \frac{2 \pi Q_s}{\eta\ C}} \\
c\ \sigma_t &= \sqrt{\epsilon_t\ \frac{\eta\ C}{2 \pi Q_s}}
\end{align}
where $C$ is the machine circumference, and
\begin{equation}
\eta = 1/\gamma^2 - 1/\gamma_t^2
\end{equation}
\begin{madlist}
\ttitem{KBUNCH} The number of particle bunches in the
machine (default: 1).
\ttitem{NPART} \label{beam_npart} The number of particles per bunch (default: 0).
\ttitem{BCURRENT} The bunch current (default: 0 A).
\ttitem{BUNCHED} A logical flag. If set, the beam is
treated as bunched whenever this makes sense.
\ttitem{RADIATE} \label{beam_radiate} A logical flag. If set, synchrotron
radiation is considered in all dipole magnets.
\ttitem{BV} an integer specifying the direction of the
particle movement in a beam line; either +1 (default), or -1. For a
detailed explanation see the section below on bv flag.
\ttitem{SEQUENCE} attaches the defined beam to the named sequence; if
the name is omitted, the BEAM command refers to the default beam
which is always present. Sequences without attached beam use this
default beam. When updating a beam with a corresponding sequence name,
tye sequence name must always be mentioned.
\end{madlist}
{\bf \underline{Order and Precedence:}}\\
Internally the BEAM command processes the parameters in the following
order and with the following precedence (left to right):
{\bf Warning:} BEAM updates, i.e. it replaces attributes explicitly
mentioned, may calculate other attributes according to the precedence rules
given, but does NOT return attributes not specified to default values!
In order to reset to reset BEAM attributes to their default values, use
the {\tt RESBEAM} command.
{\bf \underline{Additional variables:}}\\
Some \mad modules may also compute and store data into a beam data
block. These attributes may NOT be set directly through the BEAM
command. The corresponding variables are:
\begin{madlist}
\ttitem{CIRC} total length or circumference of the machine [m]
\ttitem{FREQ0} revolution frequency [Hz]
\ttitem{DTBYDS} ???
\ttitem{DELTAP} momentum deviation
\ttitem{ALFA} momentum compaction factor
\ttitem{U0} radiation loss per turn [GeV]
\ttitem{QS} synchrotron tune [1]
\ttitem{ARAD} classical particle radius [m]
\ttitem{PDAMP} damping partition numbers; Default is {1,1,2}
\ttitem{N1MIN} minimum available aperture, set by the APERTURE module
\end{madlist}
\section{RESBEAM}
\label{sec:resbeam}
The {\tt RESBEAM} command resets the default values of the beam belonging to
the specified sequence, or of the default beam if no sequence is given.
\madbox{
RESBEAM, SEQUENCE=string;
}
The only argument to {\tt RESBEAM} is a string for the sequence name.
If the sequence name is omitted, the default beam is reset.\selectlanguage{english}
\begin{table}
[h]
\caption{{Default Beam Data}}
\vspace{1ex}
\begin{center}
\begin{tabular}{|l|l|l|}
\hline
{\bf Attribute} & {\bf Value} & {\bf Unit} \\
\hline
\texttt{PARTICLE} & \texttt{POSITRON} & \\
\texttt{ENERGY} & 1 & GeV \\
\texttt{EX} & 1 & rad.m \\
\texttt{EY} & 1 & rad.m \\
\texttt{ET} & 1 & rad.m \\
\texttt{KBUNCH} & 1 & \\
\texttt{NPART} & 0 & \\
\texttt{BCURRENT} & 0 & A \\
\texttt{BUNCHED} & \texttt{TRUE} & \\
\texttt{RADIATE} & \texttt{FALSE} & \\
\hline
\end{tabular}
\end{center}
\end{table}
\section{Referring to BEAM data attributes}
Expressions may refer to data in the beam data block using the
notation
\madbox{
BEAM->attribute-name
}
or
\madbox{
BEAM\%sequence-name->attribute-name.
}
This notation refers to the value of attribute-name found in the default
{\tt BEAM}, respectively the beam belonging to the sequence {\tt
sequence-name}.
This can be used for receiving or using values, e.g.
\madxmp{value, beam\%lhcb2->bv;}
but also for storing values in the beam bank, e.g.
\madxmp{beam->charge=-1;}
Note however that this does NOT trigger an update of dependent variables
and you are strongly advised against setting {\tt BEAM} parameters with this
method.
The current values in the {\tt BEAM} bank can be obtained by the command
\madbox{SHOW, BEAM;}
or to obtain the data for a beam linked to a named sequence:
\madbox{SHOW, BEAM\%sequence-name;}
{\bf \underline{Example:}}
\madxmp{
! select electrons, set energy and emittances\\
BEAM, PARTICLE=ELECTRON, ENERGY=50, EX=1.E-6, EY=1.E-8, SIGE=1.E-3;\\
...\\
! turn on synchrotron radiation\\
BEAM, RADIATE;\\
...\\
! reset all values to their defaults, \\
! ie positrons, energy = 1GeV, default emittances, no radiation...\\
RESBEAM;\\
...\\
! select new emittances\\
BEAM, EX=2.E-5, EY=3.E-7, SIGE=4.E-3;
}
\section{BV FLAG}
\label{sec:bvflag}
When reversing the direction ($\vec V$) of a particle in a magnetic field
($\vec B$) while keeping its charge constant, the resulting force $\vec
V \times \vec B$ changes sign. This is equivalent to flipping the field,
but not the direction.
For practical reasons the properties of all elements of the LHC are
defined in the \madx input as if they apply to a clockwise proton beam
("LHC beam 1"). This allows a single definition for elements traversed
by both beams. Their effects on a beam with identical particle charge
but running in the opposite direction ("LHC beam 2") must then be
reversed inside the program.
In \madx this may be taken into account by setting the value of
the BV attribute in the {\tt BEAM} commands. In the case of LHC beam 1
(clockwise) and beam 2 (counter-clockwise), that are both treated in
\madxas clockwise proton beams, the {\tt BEAM} commands must look as follows:
\madxmp{
BEAM, SEQUENCE=lhcb1, PARTICLE=proton, PC=450, BV = +1;\\
BEAM, SEQUENCE=lhcb2, PARTICLE=proton, PC=450, BV = -1;}
\chapter{Sequence Editor}
\label{chap:seqedit}
With the help of a few commands, an existing sequence may be
modified in many ways: in the case of a circular machine, the starting point of
the sequence can be moved to another place;
the order of elements can be inverted; elements can be inserted one by
one, or as a whole group with one single command; single elements, or
classes thereof can be removed; elements can be replaced by others;
finally, the sequence can be "flattened", i.e. all inserted sequences
are replaced by their actual elements, such that a flattened sequence
contains only elements.
It is good practice to add a \hyperref[sec:flatten]{\tt FLATTEN}
statement at the end of a {\tt SEQEDIT} operation to ensure a fully
operational sequence. This is particularly useful for the
\hyperref[sec:save]{\tt SAVE} command to properly save {\it shared sequences}
and to write them out in \madeight format.
\section{SEQEDIT}
\label{sec:seqedit}
\madxprovides an environment for the edition of sequences that is invoked with
the command:
\madbox{SEQEDIT, SEQUENCE=string;}
The only attribute is the name of the sequence to be edited.
The editing is performed on the sequence as provided by the user and before it
is expanded with the \hyperref[sec:use]{\tt USE} command.
At the end of sequence edition, the resulting sequence must be expanded through
the \hyperref[sec:use]{\tt USE} command as necessary.
\section{FLATTEN}
\label{sec:flatten}
Sequences can be built from elements but also sub-sequences resulting in a
nested structure (see chapter \ref{chap:sequence} on sequence definition).
The positioning of elements within a sequence can also be specified with values
or expressions, and by reference to other elements.
\madxprovides a command to resolve these dependencies and transform a complex
sequence into a simple list of elements with positioning values referring to
the start of the sequence, discarding the user-specified expressions for the
positioning.
This command takes no argument:
\madbox{
FLATTEN;
}
If the sequence being edited contains sub-sequences, {\tt FLATTEN} recursively
includes all sub-sequences until the sequence is only composed of a simple list
of elements.
{\tt FLATTEN} also resolves the positioning of each element within the sequence
to a single value with reference to the start of the sequence and updates the
{\tt AT} attribute of that element while also discarding the user-specified
expression if present.
The {\tt FLATTEN} command is recommended at the beginning of sequence edition
as well as at the very end as in
\madxmp{
SEQEDIT, \=SEQUENCE=name; \\
\>FLATTEN; \\
\>\ldots commands to edit the named sequence\ldots \\
\>FLATTEN; \\
ENDEDIT;
}
\section{CYCLE}
\label{sec:cycle}
\madbox{
CYCLE, START=string;
}
This makes the sequence start at the location given as attribute value of the {\tt START}
attribute. The element named by the {\tt START} attribute must be a marker. \\
In the case there is a shared sequence in the used sequence, the
command {\tt FLATTEN} has to be used before the command {\tt CYCLE}. \\
Example:
\madxmp{
FLATTEN; \\
CYCLE, START=place;
}
Note that the {\tt FLATTEN} command inserts another marker before the start location,
with a name composed of the name of the sequence being edited, followed by the
start location name and the string "\_P\_".
\section{REFLECT}
\label{sec:reflect}
\madbox{REFLECT;}
This inverts the order of element in the sequence, starting from the
last element. \\
If there are shared sequences inside the \hyperref[sec:use]{\tt USE}d sequence,
the command
{\tt FLATTEN} must be used before the command {\tt REFLECT}.
Alternatively each shared sequence must first be reflected. Example:
\madxmp{
FLATTEN;\\
REFLECT;
}
\section{INSTALL}
\label{sec:install}
\madbox{
INSTALL, ELEMENT=string, CLASS=string, AT=real, FROM=\{string|SELECTED\};
}
where the parameters have the following meaning:
\begin{madlist}
\ttitem{ELEMENT} name of the (new) element to be inserted (mandatory)
\ttitem{CLASS} class of the new element to be inserted (mandatory)
\ttitem{AT} position where the element is to be inserted; if no "from"
is given,this is relative to the start of the sequence. If "from"
is given, it is relative to the position specified there.
\ttitem{FROM} either a place (i.e. the name(+occurrence count) of an
element already existing in the sequence, e.g. mb[15], or
mq.a..i1..4 etc.; or the string {\tt SELECTED}; in the latter case an
element of the type specified will be inserted behind all elements
in the sequence that are currently selected by one or several
\hyperref[sec:select]{\tt SELECT} commands of the type
\madxmp{SELECT, FLAG=seqedit, CLASS=.., PATTERN=.., RANGE=..;}
\end{madlist}
{\bf Note:} No element definition can occur inside a {\tt SEQEDIT ... ENDEDIT}
block.
\section{MOVE}
\label{sec:move}
\madbox{
MOVE, ELEMENT=\{string|SELECTED\}, BY=real, TO=real, FROM=string;
}
\begin{madlist}
\ttitem{ELEMENT} name of the existing element to be moved, or
"SELECTED", in which case all elements from existing
\hyperref[sec:select]{\tt SELECT} commands will be moved;
in the latter case, the {\tt BY} attribute must be given.
\ttitem{BY} distance by which the element(s) is/are to be moved; no {\tt TO}
or {\tt FROM} attributes should be given in this case.
\ttitem{TO} position to which the element has to be moved; if no {\tt FROM}
attribute is given, the position is relative to the start of the sequence; otherwise, it
is relative to the location given in the {\tt FROM} argument
\ttitem{FROM} place in the sequence with respect to which the element
is to be positioned.
\end{madlist}
\section{REMOVE}
\label{sec:remove}
\madbox{
REMOVE, ELEMENT=\{string|SELECTED\};
}
\begin{madlist}
\ttitem{ELEMENT} name of existing element(s) to be removed. \\
The special case {\tt ELEMENT = SELECTED} removes all elements previously
selected by \hyperref[sec:select]{\tt SELECT} commands
\end{madlist}
{\bf Note:} \madx expects to find some special markers in a beam line and it
is therefore dangerous to remove all markers from a sequence! In particular the
{\tt START=...} marker and markers added by a \hyperref[sec:cycle]{\tt CYCLE}
command must never be removed from a sequence.
\section{REPLACE}
\label{sec:replace}
\madbox{
REPLACE, ELEMENT=\{string|SELECTED\}, BY=string;
}
The parameters are defined as:
\begin{madlist}
\ttitem{ELEMENT} names the elements to be replaced. \\
The special case {\tt ELEMENT = SELECTED} replaces all elements previously
selected by \hyperref[sec:select]{\tt SELECT} commands
\ttitem{BY} names the elements replacing the elements selected for
replacement.
\end{madlist}
\section{EXTRACT}
\label{sec:extract}
A new sequence can be extracted as a subset of an existing sequence. The
extracted sequence is given a new name and can be \hyperref[sec:use]{\tt USE}d
as any user defined sequence.
\madbox{
EXTRACT, SEQUENCE=string, FROM=string, TO=string, NEWNAME=string;
}
The parameters are defined as:
\begin{madlist}
\ttitem{SEQUENCE} the name of the existing sequence from which the new sequence
is extracted.
\ttitem{FROM} the name of an element in the sequence that becomes the first
element of the extracted sequence.
\ttitem{TO} the name of an element in the sequence that becomes the last
element of the extracted sequence.
\ttitem{NEWNAME} the name of the extracted sequence.
\end{madlist}
The extracted sequence is declared as \hyperref[sec:sequence]{\tt SHARE}d and
can therefore be combined e.g. into the cycled original sequence.
{\bf Note:} the element given by the {\tt FROM} attribute must be located, in
the existing sequence, before the element given by the {\tt TO} attribute, or
\madxfails with a fatal error.
In the case of circular sequences, this can be ensured by performing a
\hyperref[sec:cycle]{\tt CYCLE} of the original sequence with {\tt START}
pointing to the same element given in the {\tt FROM} attribute of the {\tt
EXTRACT} command.
\section{ENDEDIT}
\label{sec:endedit}
The sequence editing environment is closed with the command
\madbox{ENDEDIT;}
The nodes in the sequence are finally renumbered according to their occurrence
which might have changed during editing.
\section{SAVE}
\label{sec:save}
The {\tt SAVE} command saves a sequence to a specified file together with all
relevant information.
The parameters are defined as:
\begin{madlist}
\ttitem{SEQUENCE} lists the sequences to be saved, separated by commas.
This attribute is optional and when omitted, all known
sequences are saved. \\
However, because of internal inconsistencies that can result in spurious
entries in the output file, the user is strongly advised to always provide
explicitly the names of sequences to be saved.
\ttitem{FILE} the filename of the output file. (Default: "save")
\ttitem{BEAM} an optional flag to specify that all beams linked to the
specified sequences are saved at the top of the output file.
\ttitem{BARE} an optional flag to save only the sequence without the
element definitions nor beam information. This allows to re-read in a
sequence with might otherwise create a stop of the program. This is
particularly useful to turn a line into a sequence in order to further edit
it with \hyperref[sec:seqedit]{\tt SEQEDIT}.
\ttitem{MAD8} an optional flag to request that the sequences should be
saved using \madeight input format.
\ttitem{NOEXPR} an optional flag to save values of expressions
instead of the expressions themselves: the expressions in commands
and variables are expanded and evaluated before saving.
This option must be used with care because the exported values were not deeply
checked and the code that writes variables and commands is widely spread
in the internal structure. \\
This option does not apply only for the saving of sequences in \madeight format.
\ttitem {NEWNAME} provides a name for the saved sequence, overriding the
original name. (see \hyperref[sec:extract]{\tt EXTRACT} above)
\end{madlist}
Any number of {\tt SELECT, FLAG=save, ...} commands may precede
the {\tt SAVE} command. In that case, the names of elements, variables, and
sequences must match the pattern(s) if given, and in addition the
elements must be of the class(es) specified.
See here for a
\href{../Introduction/select.html#save_select}{SAVE with SELECT}
example.
The precision of the output of the {\tt SAVE} command depends on the defined
output precision for \madx, which can be adjusted with the
\hyperref[sec:set]{\tt SET, FORMAT...} command.
Note that with {\tt BARE=false} the saved sequence may contain redundant
efinitions of elements, ie the same element is defined in the declaration
of elements in the form {\tt label:\ type...} and in the sequence itself
in the form {\tt label:\ type, at=...}. This is flagged by \madx as implicit
element redefinition and is ignored but a warning is issued.
Example:
\begin{verbatim}
tl3: LINE = ( ldl6, qtl301, mqn, qtl301, ldl7, qtl302,
mqn, qtl302, ldl8, ison);
dltl3: LINE=(delay, tl3);
Use, period=dltl3;
Save, sequence=dltl3, file=t1, bare; // only sequence is saved
Call, file=t1; // sequence is read in and is now a "real" sequence
// if the two preceding lines are suppressed, seqedit will print a warning
// and else do nothing
Use, period=dltl3;
Twiss, save, betx=bxa, alfx=alfxa, bety=bya, alfy=alfya;
Plot, vaxis=betx, bety, haxis=s, colour:=100;
SEQEDIT, SEQUENCE=dltl3;
remove,element=cx.bhe0330;
remove,element=cd.bhe0330;
ENDEDIT;
Use, period=dltl3;
Twiss, save, betx=bxa, alfx=alfxa, bety=bya, alfy=alfya;
\end{verbatim}
\section{DUMPSEQU}
\label{sec:dumpsequ}
\madbox{
DUMPSEQU, SEQUENCE=string, LEVEL=integer;
}
This command is actually more of a debug statement, but it may come handy at certain
occasions. The argument of the {\tt SEQUENCE} attribute is the name of an
already expanded (i.e. \hyperref[sec:use]{\tt USE}d) sequence. The amount of
detail in the output is controlled by the {\tt LEVEL} argument:
\begin{itemize}
\item[$=0$ : ] print only the cumulative node length = sequence length
\item[$>0$ : ] print all node (element) names except drifts
\item[$>2$ : ] print all nodes with their attached parameters
\item[$>3$ : ] print all nodes, and their elements with all parameters
\end{itemize}
\bibliographystyle{unsrt}
\printindex
\selectlanguage{english}
\FloatBarrier
\bibliographystyle{plain}
\bibliography{bibliography/converted_to_latex.bib%
}
\end{document}