Previous topic

API Reference

Next topic


This Page


This module aims to provide the full functionality of the MAD-X library in a more convenient Python environment. For example, when you call the twiss method, you get numpy arrays containing the information from the table generated. Furthermore, we try to reduce the amount of commands needed by combining e.g. USE, SELECT, and TWISS into the twiss method itself, and define reasonable default patterns/columns etc. See, Madx example.

Module author: Yngve Inntjore Levinsen <>

Main module to interface with Mad-X library.

The class Madx uses a subprocess to execute MAD-X library calls remotely via a simple RPC protocol.

The remote backend is needed due to the fact that cpymad.libmadx is a low level binding to the MAD-X library which in turn uses global variables. This means that the cpymad.libmadx module has to be loaded within remote processes in order to deal with several isolated instances of MAD-X in parallel.

Furthermore, this can be used as a security enhancement: if dealing with unverified input, we can’t be sure that a faulty MAD-X function implementation will give access to a secure resource. This can be executing all library calls within a subprocess that does not inherit any handles.

More importantly: the MAD-X program crashes on the tinyest error. Boxing it in a subprocess will prevent the main process from crashing as well.

class cern.cpymad.madx.ChangeDirectory(path, _os=<module 'os' from '/usr/lib/python3.4/'>)[source]

Context manager for temporarily changing current working directory.

class cern.cpymad.madx.Madx(histfile=None, libmadx=None, logger=None)[source]

Python class which interfaces to Mad-X library


Get/set the name of the active sequence.

aperture(sequence=None, pattern=['full'], madrange='', columns=['name', 'l', 'anglex', 'y', 'z', 'theta'], offsets=None, fname=None, use=False)[source]


  • sequence (str) – name of sequence
  • fname (str) – name of file to store tfs table
  • pattern (list) – pattern to include in table
  • columns (list) – columns to include in table (may be a str)
  • use (bool) – Call use before aperture.
call(filename, chdir=False)[source]

CALL a file in the MAD-X interpretor.

  • filename (str) – file name with path
  • chdir (bool) – temporarily change directory in MAD-X process

Change the directory. Can be used as context manager.

Parameters:path (str) – new path name
Returns:a context manager that can change the directory back
Return type:ChangeDirectory

Perform a single MAD-X command.

  • cmd (str) – command name
  • **kwargs

    command parameters


Evaluates an expression and returns the result as double.

Parameters:cmd (string) – expression to evaluate.
Returns:numeric value of the expression
Return type:float

Get a handle to the active sequence.

Returns:a proxy object for the sequence
Return type:Sequence
Raises RuntimeError:
 if there is no active sequence

Get a handle to the specified sequence.

Parameters:name (str) – sequence name
Returns:a proxy object for the sequence
Return type:Sequence
Raises ValueError:
 if a sequence name is invalid

Return list of all sequences currently in memory.

Returns:list of all sequences names
Return type:list(str)

Return list of all sequences currently in memory.

Returns:list of sequence proxy objects
Return type:list(Sequence)

Get the specified table columns as numpy arrays.

  • table (str) – table name
  • columns (list or str (comma separated)) – column names

Show help about a command or list all MAD-X commands.

Parameters:cmd (str) – command name

Run any textual MAD-X input.

Parameters:text (str) – command text
match(sequence, constraints, vary, weight=None, method=('lmdif', {}), fname=None, twiss_init={}, **kwargs)[source]

Perform simple MATCH operation.

  • sequence (string) – name of sequence
  • constraints (list) – constraints to pose during matching
  • vary (list) – vary commands
  • weight (dict) – weights for matching parameters
select(flag, columns, pattern=[])[source]

Run SELECT command.

  • flag (str) – one of: twiss, makethin, error, seqedit
  • columns (list) – column names
  • pattern (list) – selected patterns
survey(sequence=None, pattern=['full'], columns=['name', 'l', 's', 'angle', 'x', 'y', 'z', 'theta'], madrange=None, fname=None, use=True)[source]


  • sequence (str) – name of sequence
  • fname (str) – name of file to store tfs table
  • pattern (list) – pattern to include in table
  • columns (list) – Columns to include in table
  • use (bool) – Call use before survey.
twiss(sequence=None, pattern=['full'], columns=['name', 's', 'betx', 'bety', 'x', 'y', 'dx', 'dy', 'px', 'py', 'mux', 'muyl', 'k1l', 'angle', 'k2l'], madrange=None, fname=None, twiss_init={}, use=True, **kwargs)[source]


  • sequence (str) – name of sequence
  • fname (str) – name of file to store tfs table
  • pattern (list) – pattern to include in table
  • columns (list) – columns to include in table, (may be a str)
  • twiss_init (dict) – dictionary of twiss initialization variables
  • use (bool) – Call use before aperture.
  • chrom (bool) – Also calculate chromatic functions (slower)
  • **kwargs

    further keyword arguments to TWISS (betx, bety, ..).

Note, that the kwargs overwrite any arguments in twiss_init.

class cern.cpymad.madx.MadxCommands(dispatch)[source]

Generic MAD-X command wrapper.

Raw python interface to issue MAD-X commands. Usage example:

>>> command = MadxCommands(libmadx.input)
>>> command('twiss', sequence='LEBT')
>>> command.title('A meaningful phrase')
Variables:__dispatch – callable that takes a MAD-X command string.
class cern.cpymad.madx.Sequence(name, libmadx, _check=True)[source]

MAD-X sequence representation.


Get the beam dictionary associated to the sequence.


Get list of all elements in the original sequence.

Returns:list of elements in the original (unexpanded) sequence
Return type:list(Element)

Get list of all elements in the expanded sequence.

Returns:list of elements in the expanded (unexpanded) sequence
Return type:list(Element)

NOTE: this may very well return an empty list, if the sequence has not been expanded (used) yet.


Get the name of the sequence.


Get the TWISS results from the last calculation.


Get the name of the table with the TWISS results.

class cern.cpymad.madx.Table(name, libmadx, _check=True)[source]

MAD-X table access class.


Get a lazy accessor for the table columns.


Get the table name.


Get the table summary.

class cern.cpymad.madx.TableColumns(table, libmadx)[source]

Lazy accessor for table column data.


Return a frozen table with the desired columns.

Parameters:columns (list) – column names or None for all columns.
Returns:column data
Return type:TfsTable
Raises ValueError:
 if the table name is invalid