Welcome to SAD/FFS & SADScript

   The FFS commands are shown in uppercases. The minimum abbreviated form 
of each command is enclosed in ().    Down to that form each command can be
shorten.   The optional arguments for the commands are usually enclosed in
[].

SAD/FFS Examples


 
   ABORT
   APPEND(APP)
   ATTRIBUTE(ATTR)
   BYE
   command-syntax
   components
   CALCULATE(CAL)
   CHROMATICITY(CHRO)
   CLOSE(CLO)
   COUPLE(COUP)
   DISPLAY(DISP)
      ACCELERATION(A)
      ALL
      BEAM(B)
      DUMPOPTICS(D)
      GEOMETRY(G)
      OGEOMETRY(OG)
      ORBIT(O)
      pattern-string
      PHYSICAL(P)
      region
      RMATRIX(R)
   DRAW
   DUMP
   elements
      APERT
      BEND
         AE1
         AE2
         ANGLE
         DISFRIN
         DISRAD
         DROTATE
         DX
         DY
         E1
         E2
         F1
         FB1
         FB2
         FRINGE
         K0
         K1
         L
         ROTATE
         transformation
      CAVI
         DISFRIN
         DPHI
         DX
         DY
         FREQ
         HARM
         L
         PHI
         ROTATE
         V02
         V1
         V11
         V20
         VOLT
      COORD
      default-keyword
      DECA
         DISFRIN
         DISRAD
         DX
         DY
         K4
         L
         ROTATE
         transformation
      DODECA
         DISFRIN
         DISRAD
         DX
         DY
         K5
         L
         ROTATE
         transformation
      DRIFT
         L
         RADIUS
         transformation
      keywords
      MARK
         OFFSET
      MULT
         AE1
         AE2
         ANGLE
         DISFRIN
         DISRAD
         DPHI
         E1
         E2
         F1
         F2
         FB1
         FB2
         FREQ
         FRINGE
         HARM
         K0
         K1
         K10
         K11
         K12
         K13
         K14
         K15
         K16
         K17
         K18
         K19
         K2
         K20
         K21
         K3
         K4
         K5
         K6
         K7
         K8
         K9
         L
         misalignments
         multipole_with_nonzero_ANGLE
         PHI
         RADIUS
         SK0
         SK1
         SK10
         SK11
         SK12
         SK13
         SK14
         SK15
         SK16
         SK17
         SK18
         SK19
         SK2
         SK20
         SK21
         SK3
         SK4
         SK5
         SK6
         SK7
         SK8
         SK9
         VOLT
      OCT
         DISFRIN
         DISRAD
         DX
         DY
         K3
         L
         ROTATE
         transformation
      QUAD
         DISFRIN
         DISRAD
         DX
         DY
         F1
         F2
         FRINGE
         K1
         L
         ROTATE
         transformation
      SEXT
         DISFRIN
         DISRAD
         DX
         DY
         K2
         L
         ROTATE
         transformation
      SOL
         BOUND
         BZ
         DISFRIN
         DPX
         DPY
         DX
         DY
         F1
         GEO
   expressions
      (-)
      (/)
      AddTo(+=)
      Alternatives(|)
      And(&&)
      Apply(@@)
      CompoundExpression(;)
      Decrement(--)
      DivideBy(/=)
      Dot(.)
      Equal(==)
      Function(&)
      Greater(>)
      GreaterEqual(>= or =>)
      Increment(++)
      Less(<)
      LessEqual(<= or =<)
      List({})
      Map(/@)
      MapAll(//@)
      Member(@)
      MessageName(::)
      Not(~)
      Or(||)
      Part([[]])
      PatternTest(?)
      Plus(+)
      Power(^)
      Repeated(..)
      RepeatedNull(...)
      ReplaceAll(/.)
      ReplaceRepeated(//.)
      Rule(->)
      RuleDelayed(:>)
      SameQ(===)
      Sequence([])
      Set(=)
      SetDelayed(:=)
      StringJoin(//)
      SubtractFrom(-=)
      TagSet(/:)
      Times(*)
      TimesBy(*=)
      Unequal(<>)
      UnsameQ(<=>)
      Unset(=.)
   extended-Twiss-parameters
      definitions
   ELSE
   ELSEIF
   EMITTANCE(EMIT)
   END
   ENDIF
   EXECUTE(EXEC)
   flags
      ABSW
      BIPOL
      CELL
      CMPLOT
      COD
      CODPLOT
      CONV
      CONVCASE
      DAMPONLY
      DAPERT
      EMIOUT
      FFSPRMPT
      FIXSEED
      FLUC
      GAUSS
      GEOCAL
      GEOFIX
      IDEAL
      INS
      INTRA
      JITTER
      LWAKE
      MOVESEED
      PHOTONS
      PRSVCASE
      PSPAC
      QUIET
      RAD
      RADCOD
      RADLIGHT
      REAL
      RELW
      RFSW
      RING
      SELFCOD
      SPAC
      STABLE
      TRPT
      TWAKE
      UNIFORM
      UNIPOL
      UNSTABLE
      WSPAC
   functions
      Beam-line-functions
         BeamLine
         BeamLineName
         ExtractBeamLine
         PrintBeamLine
         WriteBeamLine
      Data-Manipulation
         Fit
         PolynomialFit
         Spline
         NIntegrate
      DownhillSimplex
      FFS-dedicated-functions
         AccelerateParticles
         BeamMatrix
         DynamicApertureSurvey
         Element
            key-strings
         Emittance
         ExternalMap
         FFS
         FitValue
         FitWeight
         GeoBase
         LINE
            key-strings
         OptimizeOptics
         OrbitGeo
         RadiationField
         RadiationSpectrum
         SetElement
         SurvivedParticles
         SymplecticJ
         SynchroBetaEmittance
         TouschekLifetime
         TrackParticles
         Twiss
         VariableRange
         VariableWeight
         WakeFunction
      Functional-operations
         Difference
         FixedPoint
         FixedPointList
         SelectCases
         SwitchCases
      Graphics
         ListPlot
         ColumnPlot
         HistoPlot
         ListContourPlot
         ListDensityPlot
         GeometryPlot
         BeamPlot
         OpticsPlot
         FitPlot
         Plot
      Multiprocessing
         Fork
         OpenShared
         Shared
         SharedSize
      Object-oriented-programing
         Class
      Random-number-functions
         Random
         GaussRandom
         ParabolaRandom
         SeedRandom
         ListRandom
      System-interface
         System
         TemporaryName
      Utilities
         DateString
   FIT
   FITPOINTS(FITP)
   FIX
   FREE
      default-keyword
   geometrical-functions
   GEO
   GO
   IF
   INPUT(IN)
   machine-error-commands
   matching-function-commands
   multi-turn-tracking
   MATRIX(MAT)
   MEASURE(MEA)
   off-momentum-matching
   optical-functions
   OUTPUT(OUT)
   PRINT(PRI)
   QUIT
   RADINT
   READ
   RECOVER(REC)
   REJECT(REJ)
   REPEAT(REP)
   RESET
   REVERSE(REV)
   set-value-of-element
      keywords
      default-keyword
   special-symbols
   special-variables
      $FORM
      CASE
      CHARGE
      CONVERGENCE
      DAPWIDTH
      DP
      DP0
      DTSYNCH
      EFFVCRATIO
      ElementValues
      EMITX
      EMITXE
      EMITY
      EMITYE
      EMITZ
      EMITZE
      FFS$NumericalDerivative
      FitFunction
      FSHIFT
      GCUT
      InitialOrbits
      LOSSAMPL
      LOSSDZ
      MatchingAmplitude
      MatchingResidual
      MASS
      MINCOUP
      MOMENTUM
      NBUNCH
      NetResidual
      NP
      OffMomentumWeight
      OMEGA0
      OpticsEpilog
      OpticsProlog
      PageWidth
      PBUNCH
      PhotonList
      PHICAV
      SpeedOfLight
      StabilityLevel
      STACKSIZ
      TITLE
   SAVE
   SEED
   SHOW
   SPLIT
   STATUS(STAT)
   STOP
   TDR
   TERMINATE(TERM)
   TYPE(T)
   UNTIL
   USE
   VARIABLES(VAR)
   VARY
   VISIT
   wildcards
   x-y-coupling


ABORT

Stops SAD immediately.

APPEND(APP)

APP {filename | file-number} switches the output stream to the specified 
file or the file number.   The output is appended to the existing file.

ATTRIBUTE(ATTR)

Usage: ATTR element-pattern

prints out the current value, minimum and maximum values, COUPLEd element 
and its coefficient for elements which match the element-pattern.

BYE

Exits from the current beam line and returns to the original beam line 
where VISIT command was issued.   All information specific to the beam line,
such as matching conditions are restored.
   Note that BYE does neither SAVE the values of elements of the leaving 
beam line, nor RESET the values of elements of the returning beam line.

command-syntax

The command syntax in FFS is

     expression1 [param1..] [;] expression2..

(1) The input is first evaluated as an expression.   If the expression
    returns a Symbol with the same name as the expression itself, it is
    interpreted as an FFS command, otherwise the returned value is printed
    out unless it is Null.
(2) Each command takes succeeding its parameters if necessary.   A command with
    indefinite number of parameters can be terminated by semicolon.
    Most commands terminate itself at the end of line.
(3) A line can be continued to the next line if a backslash is placed at the
    end of the line.
(4) An expression continues to the next line if it is not closed in the line.
(5) An exclamation mark comments out the rest of the line.

Example: A command line

          QF* .1

means the set-value-of-element command as unless the symbol QF has been defined otherwise.
If QF has been defines as a number, such as QF=2.5, the above command line
is interpreted as Times[QF,.1] then returns .25 .

components

Components are the objects which consist the beam line.   A component simulates
an individual magnet, drift space, or rf-cavity.   The parameters of a 
component is specified the values in the corresponding element with the
same name as the component, which simulates a power supply.   Many 
components can be attached to the same element.   Parameters of each 
component may deviate from the corresponding element if machine errors are
given.
   A component is specified with the form name[.order][{+-}offset], where
name is the name of the component.    The number order means the order-th 
component which belongs to name element, counted from the beginning of the
line starting from 1.   Offset is a positive or negative number to specify 
the downstream or upstream components from the given component.   If order 
is omitted, the first element is assumed, and if offset is omitted, zero is
assumed.
   The end of line is specified by $$$.   The first component can be
specified by ^^^.

CALCULATE(CAL)

Usage: (1) CALC [[NO]EXPAND]]
       (2) CALC matching-function1[-] [matching-function2[-]..]
 
(1) With no argument or with an option [NO]EXPAND, calculates the optics 
and the matching-functions using the current values of the components. 
It prints out the values of the matching-functions specified either by the 
matching-function-commands or the second usage of CALC, as described below.
If an option EXPAND is given(default), it expands the beam line before the 
calculation.   If NOEXPAND is given, it calculates without any expansion.
   FFS["CAL"] and FFS["GO"] returns the result as a list, whose format
is

   {dp, kind, reslist, function-values},

where

dp:        a list contains dp/p0 .
kind:      a list of kind of the orbit (ususally 0, but 1 to 6 for the
           finite amplitude matching, see special-variables:MatchingAmplitude).
reslist:   a list of {residual, xstab, ystab}, where
           residual: matching residual,
           xstab:    True when the matrix is stable in X,
           ystab:    True when the matrix is stable in Y, for each orbit.

Above are lists with length nf (== number of orbits).

function-values: a list of length nc (== number of calculated items). Each
           element has the form:

           {component1, component2, function, list-of-values},

           where

           component1, component2: fit locations (see FIT).
           function: name of the function (see matching-function-commands).
           list-of-values: list of the value of the function for each orbit.
                           Length nf.
           The central orbit comes at the Floor[(n+1)/2]-th element.

(2) With matching-fuction names, sets the matching-functions at the current
fit point to be printed out after calculation.   If the matching-function is
followed by a minus sign, it suppresses the print-out.
 
Example: CALC BX BY CALC

CHROMATICITY(CHRO)

CHRO prints out the chromaticity of QUAD and SEXT in the entire beam 
line using the simplest formula:

     xi_{x,y}=Integrate[-(K1/L) beta_{x,y}(s) ds] for QUAD,
     xi_{x,y}=Integrate[-(K2/L) eta_x (s) beta_{x,y}(s) ds] for SEXT.

These formula are not valid when there is x-y coupling or vertical 
dispersion.

CLOSE(CLO)

   CLOSE [INPUT(IN)] closes the current input stream and switches it to 
the previous input stream.
   CLOSE OUTPUT(OUT) suspends the current output and switches it to the 
previous output stream.

COUPLE(COUP)

Usage: COUP slave-element master-element coefficient

sets the value of the default-keyword of slave-element to be equal to 
coefficient times the value of the default-keyword of master-element.
COUPLE(COUP) cannot be cascaded.   The master-element cannot be COUPLEd to 
any other element.   To reset COUPLE, say COUP slave-element slave-element 1.

DISPLAY(DISP)

Usage: DISP_LAY [keywords] [pattern-string] [region]

Displays values of various optical-/geometric-functions at the components
given by the pattern-string in the region (see region) in the current beam
line.
   It has several display modes specified by the keywords.  As the default,
it displays AX, BX, NX, EX, EPX, AY, BY, NY, EY, EPY, LENG, the length and 
the value of the default-keyword of the component.
   Each line refers to the entrance of each component of the line.  
The end of the beam line has the name "$$$".   The first component can be 
specified by "^^^".
   DISP does not calculate the functions to be displayed, so CALCULATE(CALC)
is necessary whenever values of components are updated.

DRAW

Usage: DRAW [begin end] fun1 [fun2..] [& fun11 [fun12..]] [element-pattern]

prints out the TopDrawer commands of the plots of functions fun1...
Available functions are all matching-functions (except LENG, TRX, TRY, GX,
GY, GZ, CHI1, CHI2, CHI3) and additional functions.   If functions are
separated by ampersand (&), these are plotted in a separated window.
   If begin- and end-components are specified, the plot region is limited
between them.   If the end-component comes earlier than the 
begin-components, it wraps the plot around the beam line.
   If the optional element-pattern is given, it draws the beam-line lattice 
with the labels for elements which match element-pattern.   If LAT is
specified for element-pattern, the lattice is drawn without label.

DUMP

Usage: DUMP component-pattern [compnent-pattern1..]

prints out the current machine errors of components which match component-
pattern.

elements

An element in FFS represents an object which has a unique name and 
several keywords with values.   This simulates a power supply of a magnet. 
An element has one or more components, which correspond to individual 
magnets in a beam line.   Each component may have different values from 
the values of the corresponding element.   This simulates the machine error 
which varies magnet to magnet.   
   The value of an element can be saved to or recovered from the 
element-save-buffer by SAVE or RESET commnads.   Different beam lines can 
share the same element, and their values can be different to each other,
but they have the common element-save-buffer.   Therefore the value of an 
element can be transferred between beam lines by SAVE and RESET command 
through the element-save-buffer.
   An element is created only in SAD MAIN level.   In the definition, if a
keyword is omitted, the previous definition is unchanged.  All keywords have
the default value zero.   In FFS, it is only possible to change their values.

expressions

An expression in FFS consists of a symbol, constants, and operators.

>>> A symbol is a characters of any length starting with an alphabet or $.
>>> There are two kinds of constants, real number and character-string.
    real number is a number in fortran-line format.
    character-string is a set of characters surrounded by "" or ''.
    special-characters can be specified with backslash.
>>> Available operators are (in the order of the priority):
    #,##,
    ?,
    ::,
    @,
    [],
    ++, --,
    /@, //@, @@,
    .,
    ^,
    *, /,
    +, -,
    ==, <>, >, <, >=, =>, <=, =<, 
    ===, <=>, 
    ~, 
    &&,
    ||,
    .., ...,
    |,
    :,
    ->, :>,
    /., //.,
    +=, -=, *=, /=,
    &,
    //,
    /:,
    =, :=, ^=, ^:=, =.
    ;,
    {}
An operator with higher priority is operated first.   An expression 
enclosed in () is evaluated first. Most mathematical operations are 
threaded into a list, i.e., {a,b} + {c,d} gives {a + b,c + d}, etc.
   Each operators can be used as a function using its name.  For example,
Plus[x,y] gives the same result as x + y.

extended-Twiss-parameters

A symplectic matrix such as the normal mode matrix can be expressed in terms
of the extended Twiss parameters.   In 6 by 6 case, those are

   AX  BX          ZX  EX
     PSIX         ZPX EPX
   R1  R2  AY  BY  ZY  EY
   R3  R4    PSIY ZPY EPY
                   AZ  BZ
                     PSIZ .

A(X,Y,Z), B(X,Y,Z) are alphas and betas in the usual sense, after a diagonalization to 2 by 2 submatrices.  PSI(X,Y,Z) are the rota
tion angle to set one
the coordinate to parallel to the (X,Y,Z) axes.   R(1,2,3,4) are the
components of the x-y coupling matrix (see x-y-coupling).   E(X,PX,Y,PY) are
"dispersions" which decouples synchro-beta coupling terms together with
Z(X,PX,Y,PY).   Those parameters should agree with what FFS calculates in
the case of no synchro-beta couplings.

ELSE

Usage: IF expr1 body1 [ELSEIF expr2 body2 [ELSEIF ..]] [ELSE body3] ENDIF

This is a FORTRAN77 like IF-structure.   If the expression expr1 is 
True(==1) or nonzero, executes commands in body1. If it is False(==0), skip
commands until ELSE, ELSEIF or ENDIF appears at the same level of the
IF-structure, and executes commands after ELSE or ENDIF, or executes the
ELSEIF command. If expr1 is not a real number, an error message is printed
and ignores the command line.

ELSEIF

Usage: IF expr1 body1 [ELSEIF expr2 body2 [ELSEIF ..]] [ELSE body3] ENDIF

This is a FORTRAN77 like IF-structure.   If the expression expr1 is 
True(==1) or nonzero, executes commands in body1. If it is False(==0), skip
commands until ELSE, ELSEIF or ENDIF appears at the same level of the
IF-structure, and executes commands after ELSE or ENDIF, or executes the
ELSEIF command. If expr1 is not a real number, an error message is printed
and ignores the command line.

EMITTANCE(EMIT)

Usage: (1) EMIT
       (2) EMIT dp

(1) EMIT calculates the closed orbit, the normal coordinate, and the
equilibrium emittance assuming the current beam line is a positron ring.
One of EMITTANCE(EMIT), the Emittance[] function, or the EMIT command
in the MAIN level are necessary to be done in prior to multi-turn tracking.
See multi-turn-tracking.

(2) EMIT dp, where dp is |df_rf/f_rf|/(alpha_p == momentum compaction), 
does EMIT for five rf frequencies:

   df_rf/f_rf/alpha_p = -|dp|, -|dp|/2, 0, |dp|/2, |dp|,

then prints out a table of the dependences of various quantities on the
frequency shift.

   The results of EMITTANCE(EMIT) are affected by flags COD, RADCOD, RFSW,
INTRA, WSPAC, EMIOUT, CODPLOT and special-variables MOMENTUM, CHARGE, FSHIFT, MINCOUP, 
PBUNCH. The flag TRPT or RING affects only Emittance[], as EMITTANCE(EMIT)
automatically set RING.
   EMITTANCE(EMIT) returns the equilibrium emittaces in variables EMITX,
EMITY, EMITZ, and the equilibrium bunch length in SIGZ, the relative
momentum spread in SIGE.

   The map used in EMIT is slightly different from that used in the tracking.
For instance, the edge angle of a bend is approximated by a thin quad.
If the edge angle is large and the curvature is small, EMIT may give a wrong 
answer.   This will be corrected in near future.

END

Closes the current output-stream and set the output stream to the 
standard output(6).   It also suspends all the input streams and switches 
to the standard input(5).   Since this command affects all input and output 
streams, you may consider to use TERMINATE(TERM) or CLOSE(CLO) to suspend 
or close them selectively.

ENDIF

Usage: IF expr1 body1 [ELSEIF expr2 body2 [ELSEIF ..]] [ELSE body3] ENDIF

This is a FORTRAN77 like IF-structure.   If the expression expr1 is 
True(==1) or nonzero, executes commands in body1. If it is False(==0), skip
commands until ELSE, ELSEIF or ENDIF appears at the same level of the
IF-structure, and executes commands after ELSE or ENDIF, or executes the
ELSEIF command. If expr1 is not a real number, an error message is printed
and ignores the command line.

EXECUTE(EXEC)

Usage: EXEC character-string-expression

executes the character-string-expression as FFS commands.

flags

Usage: [NO]flag

turns the flag on.   If NO is prepended to flag, the flag is turned off.
Some flags have antonym which works in the opposite way.   Flags can be 
accessed in the function-syntax with the form ?flag, which returns True (=1)
when the flag is on, or False (=0) otherwise.   Some flags can be 
accessed by the ON/OFF commands at the MAIN level.

functions

FFS functions:

Constants:
   Degree GoldenRatio I INF* Infinity NaN* Pi SpeedOfLight
Elementary-functions:
   ArcCos ArcCosh ArcSin ArcSinh ArcTan ArcTanh Cos Cosh Exp Log Sin Sinh
   Sqrt Tan Tanh
Special-functions:
   BesselI BesselJ BesselK BesselY BesselJZero Erf Erfc Factorial 
   Gamma LogGamma LogGamma1 GammaRegularized GammaRegularizedQ*
   GammaRegularizedP* GaussianCoulomb* GaussianCoulombU*
   GaussianCoulombFitted* LegendreP*
Numerical-functions:
   Abs Ceiling Floor Max Min MinMax* Mod Negative NonNegative Positive
   Round Sign
Matrix-operations:
   Det Eigensystem IdentityMatrix Inner LinearSolve Outer SingularValues*
   Transpose
Random-number:
   GaussRandom* Random* SeedRandom
Complex:
   Arg Complex ComplexQ Conjugate Im Re
Fourier-Transformation:
   Fourier InverseFourier
Data-Manupilation:
   FindRoot Fit* NIntegrate* PolynomialFit* Spline*
Calculus:
   D
Minimization:
   DownhillSimplex*
List-manipulations:
   Append Complement Delete Depth Difference* Dimensions Drop Extract Flatten
   FlattenAt HeldPart Insert Intersection Join Length Part Partition Prepend
   Product Range ReplacePart Rest Reverse RotateLeft RotateRight Select 
   Sort Sum Take Table Union
Character-strings:
   FromCharacterCode CharacterPosition Characters DigitQ LetterQ StringDrop
   StringFill* StringInsert StringLength StringPosition StringTrim*
   Symbol SymbolName ToCharacteCode ToLowerCase ToUpperCase ToExpression
Functional-Operations:
   Apply Cases Count DeleteCases Identity FixedPoint* FixedPointList*
   Fold Function Level Map MapAll MapAt MapIndexed MapThread Nest Position
   Replace Scan SelectCases* SwitchCases* Thread
Object-oriented programing and context:
   Begin BeginPackage Class* End EndPackage
Flow-Control:
   Break Catch Check Continue Do For Goto If Label Return Switch Throw Which
   While
Tests:
   AtomQ ComplexQ DirectoryQ* EvenQ FileQ* MatchQ MatrixQ MemberQ NearlySameQ* 
   Negative NonNegative NumberQ OddQ Order Positive RealQ StringQ* VectorQ
   BoundQ* FBoundQ*
Input/Output:
   Close Flush* Get OpenRead OpenWrite OpenAppend Print Read SeekFile*
   Short* StringToStream Write WriteString
File System:
   CopyDirectory CopyFile CreateDirectory DeleteDirectory DeleteFile
   DirectoryName FileByteCount FileDate FileNames FileType
   RenameDirectory RenameFile SetFileDate ToFileName
Scoping:
   Block Module With*
Attributes:
   Attributes* Clear Evaluate Head Hold Literal Protect ReleaseHold
   SetAttributes* Unevaluated Unprotect
GUI Widget:
   Window* PanedWindow* Frame* LabelFrame* Canvas* TextLabel* TextMessage*
   Button* CheckButton* RadioButton* Menu* OptionMenu* MenuButton*
   Entry* SpinBox* ListBox* ScrollBar* Scale* TextEditor*
Graphics:
   BeamPlot* ColumnPlot* HistoPlot* ListContourPlot ListDensityPlot 
   ListPlot Plot Show FitPlot* GeometryPlot* OpticsPlot* TkPhotoPutBlock*
System Interface:
   Directory Evironment GetEnv* GetGID* GetPID* GetUID* ProcessStatus* 
   SetDirectory SetEnv* System* TemporaryName* MkSecureTemp* RealPath*
Multiprocessing:
   BiPipe* Fork* OpenShared* Shared* Wait*
Utilities:
   Date DateString* Definition* FromDate* ToDate ToDateString* Pause
   MemoryCheck* Message Off On Sleep TimeUsed Timing TracePrint

Functions listed above work basically in the same way as Mathematica's 
except those marked by *.

FFS-dedicated-functions:
   BeamMatrix CalculateOptics DynamicApertureSurvey Element Emittance FFS
   FitValue FitWeight GeoBase LINE OptimizeOptics OrbitGeo RadiationField
   RadiationSpectrum SymplecticJ SetElement TrackParticles Twiss VariableRange
   TouschekLifetime WakeFunction
Beam-line-functions:
   BeamLine BeamLineName ExtractBeamLine PrintBeamLine WriteBeamLine

FIT

Usage: (1) FIT [component]
       (2) FIT component1 component2

sets the current location where the matching condition is applied. 
The component is given with the form name[.order][{+-}offset] (see 
components).    If component is omitted, the end of the beam line is chosen.
   If two components are given, it means a relative-fitting or zone-fitting.
If the fitting condition is not maximum-fitting, the condition means to 
make values at two components equal (for AX, BX, AY, BY, EX, EPX, EY, EPY,
R1, R2, R3, R4, DX, DPX, DY, DPY, PEX, PEPX, PEY, PEPY, CHI1, CHI2, CHI3), 
or have the specified difference (for NX, NY, LENG, GX, GY, GZ).
   If the fitting condition is maximum-fitting, the condition means a 
zone-fitting (for AX, BX, AY, BY, EX, EPX, EY, EPY, R1, R2, R3, R4, DX, DPX,
DY, DPY, PEX, PEPX, PEY, PEPY, CHI1, CHI2, CHI3), which
suppress the maximum of the function in the region between component1 and 
component2, or maximum-fitting for the difference of the function (for NX, 
NY, LENG, GX, GY, GZ).
   The fit region is shown in the first part of the prompt when FFSPRMPT is
ON.

Example: (1) FIT QF.2-10

sets the current fit point at  10 components upstream from the entrance of 
the second QF.

         (2) FIT QF QD NX 0.5 BXM 10

sets the two-point fitting between QF and QD, then set the difference of NX 
between QF and QD to be 0.5, and the maximum of BX to be 10 in the region 
between QF and QD.

FITPOINTS(FITP)

FITP n sets n to the number of off-momentum points in the off-momentum 
matching.   If the fitting condition is on-momentum only, it is not affected.

FIX

Usage: (1) FIX element-pattern [keyword] [element-pattern1 [keyword1]..]

removes elements which match element-pattern from the matching variables.  
The optional keyword specifies the non-default variables.   If the keyword 
is omitted, all keywords are removed.
   For the MARK element at the beginning of the beam line, a special form
can be used for the FIX command.   That is a form I 
(appending "I" to a matching-function name).

Example: FIX AXI BXI AYI BYI

removes incoming AX, BX, AY, and BY from the matching variables.

Usage: (2) FIX

sets the standard optics for the orbit correction commands.

FREE

Usage: FREE element-pattern [keyword] [element-pattern1 [keyword1]..]

specifies elements which match element-pattern as the matching variables.
The optional keyword specifies the non-default variables.   See
default-keyword. 
   For the MARK element at the beginning of the beam line, a special form
can be used for the FREE command.   That is a form I 
(appending "I" to a matching-function name) which means the incoming 
condition of the matching-function is varied in the matching.

Example: FREE AXI BXI AYI BYI

changes incoming AX, BX, AY, and BY to find the solution.

geometrical-functions

Available geometrical-functions are:

GX      geometrical coordinate xi
GY      geometrical coordinate eta
GZ      geometrical coordinate zeta
CHI1    geometrical rotation angle ch1_1
CHI2    geometrical rotation angle ch1_2
CHI3    geometrical rotation angle ch1_3

The geometrical coordinate {xi, eta, zeta} is set by the ORG command, and
its default origin is at the entrance of the beam line, and the default
directions are xi in s-direction, eta in -(x-direction), and zeta in
-(y-direction) at the entrance. The set {xi, eta, zeta} forms a right-hand
system.
   The rotation angles are defined so as to give the local {x,y,s} is 
written

    {x, y, s}_local
   = rotate[s, chi3] rotate[x, chi2] rotate[y, -chi1]{x, y, s}_origin,

where rotate[a, b] reads "rotate around the  new-a vector by b 
right-handedly".

GEO

prints out the TopDrawer commands for the geometric plot of the beam line.

GO

Usage: GO [[NO]EXPAND]

Does matching for fitting conditions given by matching-function-commands
with variables specified by FREE.

If an option EXPAND is given (default), it expands the beam line before the
calculation.   If NOEXPAND is given, it avoids any expansion.

   FFS["CAL"] and FFS["GO"] returns the result as a list, whose format
is

   {dp, kind, reslist, function-values},

where

dp:        a list contains dp/p0 .
kind:      a list of kind of the orbit (ususally 0, but 1 to 6 for the
           finite amplitude matching, see special-variables:MatchingAmplitude).
reslist:   a list of {residual, xstab, ystab}, where
           residual: matching residual,
           xstab:    True when the matrix is stable in X,
           ystab:    True when the matrix is stable in Y, for each orbit.

Above are lists with length nf (== number of orbits).

function-values: a list of length nc (== number of calculated items). Each
           element has the form:

           {component1, component2, function, list-of-values},

           where

           component1, component2: fit locations (see FIT).
           function: name of the function (see matching-function-commands).
           list-of-values: list of the value of the function for each orbit.
                           Length nf.
           The central orbit comes at the Floor[(n+1)/2]-th element.

IF

Usage: IF expr1 body1 [ELSEIF expr2 body2 [ELSEIF ..]] [ELSE body3] ENDIF

This is a FORTRAN77 like IF-structure.   If the expression expr1 is 
True(==1) or nonzero, executes commands in body1. If it is False(==0), skip
commands until ELSE, ELSEIF or ENDIF appears at the same level of the
IF-structure, and executes commands after ELSE or ENDIF, or executes the
ELSEIF command. If expr1 is not a real number, an error message is printed
and ignores the command line.

INPUT(IN)

IN {filename | file-number} switches the input stream to the specified 
file or the file-number.   The original stream is kept and to be returned 
by TERMINATE(TERM).   The input file is not rewound.

machine-error-commands

Usage: machine-error-command [options] amount component-pattern ..

where machine-error-command is one of

command    keyword affected     applicable types
DELX       DX                   BEND QUAD SEXT OCT DECA DODECA SOL CAV
DELY       DY                   BEND QUAD SEXT OCT DECA DODECA SOL CAV
DL         L                    DRIFT SOL
DTHETA     ROTATE               QUAD SEXT OCT DECA DODECA CAV
DTHETA     DROTATE              BEND
DK         default-keyword      DRIFT BEND QUAD SEXT OCT DECA DODECA MULT SOL CAV
DDK        K0 or DBZ            BEND SOL

   amount is the amount of the error,
   component-pattern is the pattern to specify the components to be applied.

   Options are

RANDOM(R)        Set amount*GaussRandom[] to the keyword.  
UNIFORM(U)       Set the specified amount to the keyword without random number.
INCOHERENT(INC)  GaussRandom[] is called for each component.   Default.
COHERENT(C)      GaussRandom[] is called once for each component-pattern.
PUT(P)           Set the error to the keyword.   Default.
ADD(A)           Add the error to the keyword.

matching-function-commands

Usage: (1) matching-function  goal-value [off-momentum-points]
       (2) matching-functionM goal-value [off-momentum-points]
       (3) matching-functionI incoming-value
       (4) matching-functionSCALE scale

(1) sets the matching condition for matching-function at the current 
fitting point or region with the goal-value and the 
off-momentum-points (see off-momentum-matching).   
   If off-momentum-points is omitted, the previous value for this 
matching-function at this fitting-point is assumed.   If the previous value
is not defined, 1 is assumed.   If -1 is given for off-momentum-points,
the matching-function is rejected from the matching (see REJECT(REJ)).
   If "*" is given for goal-value, the previous value is used if exists.

Example:   BX 10 3    (beta_x to be 10 at 3 momenta) 
           BX 20      (now beta_x to be 20 at 3 momenta (previous setting))
           BX *  5    (now beta_x to be 20 (previous setting) at 5 momenta)

(2) If the letter "M" is appended to matching-function, it means the 
maximum-fitting for the function.   The maximum of either the value (for
positive-definite functions) or the absolute value (for bipolar functions)
are to be limited in the matching.

(3) If the letter "I" is appended to matching-function, it specifies 
the value of the incoming beam.

(4) If SCALE is appended to matching-function, it sets the scale of
the input/output of the function to scale.   This scale is used in the
matching-function commands, DISPLAY(DISP), SHOW, etc.

   Available matching-functions are:
optical-functions (see optical-functions):
AX BX NX AY BY NY EX EPX EY EPY R1 R2 R3 R4 DX DPX DY DPY DZ DDP 
PEX PEPX PEY PEPY TRX TRY LENG
geometrical-functions (see geometrical-functions):
GX GY GZ CHI1 CHI2 CHI3

multi-turn-tracking

The multi-turn tracking can be done by the TRACK command of the MAIN
level, the TRACK command in FFS, or the DynamicApertureSurvey[] function
in FFS.   The latter only perform the DAPERT mode.

   The multi-turn tracking uses the closed orbit, normal coordinate, and 
the equilibrium emittances.   Therefore One of EMITTANCE(EMIT), the 
Emittance[] function, or the EMIT command in the MAIN level are necessary to
be done once in prior to the multi-turn-tracking.   The values of EMITX, 
EMITY, EMITZ, SIGE can be changed between EMITs and the multi-turn-tracking.

MATRIX(MAT)

Usage: MATRIX [{SYMPLECTIC(S) | PHYSICAL(P)}] [from to]

prints out the 4 by 5 transfer matrix from from-component to to-component.
If SYMPLECTIC(S) is specified (default), the symplectic transfer matrix on 
{x,px/p0,y,py/p0,dp/p0} where p0 is the nominal momentum at the entrance,
is given. Otherwise, in the case of TRPT, the transfer matrix on
{x,px/p0(s),y,py/p0(s),dp/p0(s)} is printed out.
   If the from- and to- components are omitted, entire beam line is assumed.
If to-component is upstream the from-component, it gives the inverse matrix
(TRPT) or one-turn-wrapped matrix (RING).

MEASURE(MEA)

Usage: MEA [end-component] [OUT file plot-spaces]

tracks particles from the entrance to end-component and prints out the
statistics at the end.   If end-component is omitted, the component end
used in the last MEASURE(MEA) (default: end of the beam line) is assumed.
   If OUT file plot-spaces are attached, it plots phase space 
disribution on file.   The phase-spaces are specified like as X-PX, 
or X-Y, etc., (up to any numbers).
   Parameters for the tracking are specified by special-variables and flags:

seed for the random-number generator:
     SeedRandom[seed_Real] or SeedRandom[{seeds__Real}]

special-variables (can be set with =):
     NP        number of particles 
     EMITX     horizontal emittance
     EMITY     vertical emittance
     DP        relative momentum spread
     DP0       relative momentum offset dp/p0
     GCUT      cut-off value of the Gaussian tail
flags:
     GAUSS/UNIFORM    Gaussian/uniform(default) momentum distribution
     JITTER/NOJITTER  off(default)/on nullifying the incoming centroid offset
     RFSW/NORFSW      switch on(default)/off the rf-cavities
     RAD/NORAD        synchrotron radiation on/off
     RADCOD/NORADCOD  off/on compensation of energy loss due to radiation
     FIXSEED/MOVESEED keep(default)/unkeep the initial random-number seed

   The initial transverse distribution is Gaussian.

off-momentum-matching

FFS matches the optical functions for an orbit with finite momentum 
deviation.

Example: 
   DP=0.01;      sets the range of momentum to DP0-0.01 < dp/p0 < DP0+0.01 .
   BX 10 9;      sets the goal of betax to 10 m, at 9 points.
                 in the range above, i.e.,
                 dp/p0 = {-0.01,-0.0075,-0.005,-0.0025,0,
                          0.0025,0.005,0.0075,0.01} + DP0 .
   GO            starts the matching.

As this example, the off-momentum points are chosen with equal separation.
If the off-momentum point n is an even number, the chosen points are same as
the case of n+1, but the on-momentum point (==DP0) is excluded.

optical-functions

Available optical functions for matching are:

AX      alpha_X
BX      beta_X
NX      psi_X, the default scale is 1/(2Pi)
AY      alpha_Y
BY      beta_Y
NY      psi_Y, the default scale is 1/(2Pi)
EX      eta_X   (dispersion_X)
EPX     eta_Px  (dispersion_PX) 
EY      eta_Y   (dispersion_Y)
EPY     eta_Py  (dispersion_PY)
R1      R_1     (see x-y-coupling)
R2      R_2     (see x-y-coupling)
R3      R_3     (see x-y-coupling)
R4      R_4     (see x-y-coupling)
DX      dx
DPX     dpx
DY      dy
DPY     dpy
DZ      dz
DDP     delta=dp/p0
PEX     eta_x   (dispersion_x)
PEPX    eta_px  (dispersion_px) 
PEY     eta_y   (dispersion_y)
PEPY    eta_yy  (dispersion_py)
TRX     trace(T_X), only defined at the end of the beam line.
TRY     trace(T_Y), only defined at the end of the beam line.
LENG    length of the design orbit

In the above, upper case X, Px, Y, Py represents the x-y decoupled 
coordinate.   EX, EPX, EY, EPY refer the decoupled coordinate, while
PEX, PEPX, PEY, PEPY are in the physical coordinate.   On the other hand, 
DX, DPX, DY, DPY refer the physical coordinate.

OUTPUT(OUT)

OUT {filename | file-number} switches the output stream to the specified 
file or the file-number.   The file is written from the beginning.

PRINT(PRI)

PRI expression  evaluates expression and prints out the result.

QUIT

Exits FFS and return to SAD/MAIN level, without saving the values of
the elements.

RADINT

RADINT prints out the radiation integrals involving the x-coupling
for all components of the beam line.

READ

READ {filename | file-number} switches the input stream to the specified 
file or the file-number.   The original stream is kept and to be returned 
by TERMINATE(TERM).   The input file is rewound.

RECOVER(REC)

REC exchanges the values of FREEd elements with those when the last 
GO command was issued.   FIXed elements are not affected.

REJECT(REJ)

Usage: (1) REJ matching-function-pattern [matching-function-pattern1..]
       (2) REJ TOTAL
       (3) REJ TOTALFIT

rejects the matching-functions which match matching-function-pattern at the 
current FIT location. If TOTAL or TOTALFIT is given, the entire matching conditions in
all locations are rejected, then output parameters by CALCULATE are reset when TOTAL
is given.

REPEAT(REP)

Usage: REP [n] body UNTIL [expr1]

executes commands in body n times until expr1 gives nonzero.   The number n
can be any expression which gives a number.   If n is omitted, infinity is
assumed.   If expr1 is omitted, False(==0) is assumed.

RESET

Usage: RESET [ALL] [element-pattern]

restores the value of the elements.   What are restored are the value 
of the default keyword of all elements, the values of the non-default 
keywords which have been changed manually or by the matching.   If ALL
is given, it resets all keywords. If element-pattern is given, reset is
limited to the elements which match the pattern.

REVERSE(REV)

REV changes the sign of AX, AY, EPX, EPY, R2, R3, DPX, DPY at the
entrance of the beam line.

set-value-of-element

Usage: element-pattern [keyword] [{MIN | MAX | MINMAX | MAXMIN}] value

sets value to the specified keyword of the elements which match 
element-pattern.   If keyword is omitted, the default-keyword is assumed.
   If MIN, MAX, MINMAX, MAXMIN are specified, it sets the limit of the
default-keyword.   Both MINMAX and MAXMIN means MIN=-Abs[value] and 
MAX=+Abs[value].
   If the keyword is not the default-keyword, it affects both the current 
and the saved value.

special-symbols

There are pre-defined special symbols in FFS:

symbol        value
True           1
False          0
Infinity       INF
INF            INF
NaN            NaN
Pi             ArcSin[1]*2
E              Exp[1]
I              Complex[0,1]
Degree         Pi/180
GoldenRatio    (1+Sqrt[5])/2
SpeedOfLight   299792458

special-variables

There are several variables which have special rolls in FFS.   Some 
of them are also accessible in the MAIN level.

SAVE

Usage: SAVE [element-pattern]

saves the values of the elements.   What are saved are the value of the
default keyword of all elements, the values of the non-default keywords 
which have been changed manually or by the matching. If ALL is given it
resets all keywords.   If element-pattern is given, it is only limited
to the elements which match the pattern, otherwise all elements are saved.

SEED

SEED command is removed. Use SeedRandom[] function instead of SEED command.

SHOW

SHOW prints out the current matching conditions.

   FFS["SHOW"] returns the current matching conditions as a list.
Each element has a form of

{component1, component2, function, goal-value, number-of-momentums, scale},

which corresponds to the new format of the print-out by SHOW.

SPLIT

Usage: SPLIT component length

splits the component into two pieces at the point where the distance from
the entrance is length.   The new components have the same name as the
original, and the strengths are proportional to the new lengths.
Only magnets and cavities can be split.   You should CALCULATE(CAL) after
SPLIT to get optical parameters after SPLIT.   Matching using SPLIT element
as a variable may degrade the speed of convergence.

STATUS(STAT)

STAT shows the current settings of flags, fit points, 
special-variables, the region for DISPLAY, seed of the random number 
generator, and elapsed CPU time, etc.

STOP

Exits FFS and returns to SAD/MAIN level, with saving the values of 
the elements.

TDR

Usage:   TDR {filename | file_number}

runs TopDrawer (tdr) using the file specified by filename or file_number as
the input.   It supports both Tek terminal and X-window.

Example:   OUT 'a' DRAW bx by & ex ey q* CLOSE OUT TDR 'a'

TDR does not work when SAD is running under EMACS without X-window.

TERMINATE(TERM)

   TERM [INPUT(IN)] suspends the current input stream and switches it to the
previous input stream.
   TERM OUTPUT(OUT) suspends the current output and switches it to the
previous output stream.

TYPE(T)

Usage: TYPE [element-pattern [element-pattern1..]]

prints out the values of elements which match element-pattern in the 
SAD MAIN input format.   Keywords which have zero values are omitted unless 
it is the default variable.   If non element-pattern is given, all elements 
are printed out.

UNTIL

Usage: REP [n] body UNTIL [expr1]

executes commands in body n times until expr1 gives nonzero.   The number n
can be any expression which gives a number.   If n is omitted, infinity is
assumed.   If expr1 is omitted, False(==0) is assumed.

USE

Usage: USE [[NO]EXPAND] beam-line

switches the beam line used in FFS to the beam line given by beam-line.
beam-line can be an BeamLine object or the name of a beam line defined
in MAIN. All information specific to the current beam line, such as matching
conditions is lost.   If the keyword EXPAND is given (default), the new 
beam line is expanded, i.e., the values of components are refreshed to the 
saved values.
   If a BeamLine object is used by USE or VISIT, the new beam line becomes a
new LINE in the MAIN level, with a name which is created automatically.

VARIABLES(VAR)

VARIABLES displays a list of current matching-variables and their present,
previous, saved, minimum, and maximum values together with the COUPLEd master
elements and their coefficients.
   When executed in the FFS function, it returns the result as a list.

   Usage:   FFS["VAR"]

returns a list of nvar elements, where nvar is the number of current 
matching-variables given by the FREE command.   Each element has the form

  {name, keyword, present, previous, saved, minimum, maximum,
   coupled-master-element, coupling-coefficient} ,

which corresponds to the output of the VARIABLES(VAR) command.

VARY

Usage: VARY keyword element-pattern

changes the default-keyword of the elements which match element-pattern to 
keyword.

VISIT

Usage: VISIT [[NO]EXPAND] beam-line

switches the beam line used in FFS to the beam line given by beam-line.
beam-line can be an BeamLine object or the name of a beam line defined
in MAIN. All information specific to the current beam line, such as matching
conditions are reserved, and the previous beam line is restored when BYE
command is issued.   If the keyword EXPAND is given (default), the new beam
line is expanded, i.e., the values of components are refreshed to the saved 
values.
   If a BeamLine object is used by USE or VISIT, the new beam line becomes a
new LINE in the MAIN level, with a name which is created automatically.

wildcards

   Many commands and functions accept the wildcards as a specification 
for the name of elements or components.
The valid wildcards are:

       *         matches any zero or more characters.
       %         matches one character.
       {..}      matches any character enclosed.
       {^..}     matches any character not enclosed.
       ..|..     alternative pattern.

x-y-coupling

The transformation matrix from the physical coordinate {x,px,y,py} to 
the x-y decoupled coordinate {X,Px,Y,Py} is written as

      R = {{mu I, J . Transpose[r] . J}, {r, mu I}}, 

with the submatrix r={{R1, R2},{R3, R4}}, where mu^2 + Det[r] = 1, 
I = {{1,0},{0,1}}, and J={{0, 1}, {-1, 0}}.

   Let T stand for the physical
transfer matrix from location 1 to location 2, then the transformation in
the decoupled coordinate is diagonalized as

      R_2 . T . Inverse[R_1] = {{T_X ,0}, {0, T_Y}} .

The Twiss parameters are defined for the matrices T_X and T_Y.
   If Det[r] >= 1, the above condition for mu is violated. In such a case, an
alternative matrix is used:

      R = {{J . Transpose[r'] . J, mu' I}, {mu'I, r'}}, 

where

      r' = {{R3, R4}, {R1, R2}}/Sqrt[Det[r]],

and mu'^2 + Det[r'] = 1.

Back to top