dipas.madx.utils module¶
Utilities for interfacing the MADX program and parsing MADX generated output files.
-
dipas.madx.utils.
run_file
(scripts: Union[str, Sequence[str]], results: Union[Sequence[str], Dict[str, bool]] = None, *, variables: Dict[str, Any] = None, format: Dict[str, Any] = None, parameters: Dict[str, Any] = None, twiss: Dict[str, Any] = None, madx: str = None, wdir: Optional[str] = None) → Dict¶ Runs a single script or a bunch of dependent scripts, with optional configuration.
The first script specified in scripts is considered the entry point and is passed to the MADX executable. Other scripts should be invoked implicitly via
call, file = "...";
. If there is only a single script it can be used directly as the first argument.- Parameters
scripts (str or list of str) – A single script or a list of MADX script file names. The first item is used as the entry point. Actually the list can contain any file names, relative to the current working directory. These files will be copied to the new, temporary working directory where the script will be run (regardless of whether they are used or not). For example one can include error definitions that way, which are then loaded in the main script. Note that files within the main script which are referred to via
call, file = ...
orreadtable, file = ...
are auto-discovered and appended to the list of required scripts (if not already present).results (list or dict, optional) – See
run_script()
.variables (dict, optional) – Variables configuration for each of the scripts in scripts. See
run_script()
for more details.format (dict, optional) – Format values for each of the scripts in scripts. See
run_script()
for more details.parameters (dict, optional) – Parameter definitions for each of the scripts in scripts. See
run_script()
for more details.twiss (dict, optional) – Twiss command specification for each of the scripts. See
run_script()
for more details.madx (str, optional) – See
run_script()
.wdir (str, optional) – The working directory in which the scripts will be run. Note that any existing files with similar names as the ones in scripts will be overwritten. If not specified then a temporary working directory is created.
- Returns
output – Containing the stdout and stderr at keys “stdout” and “stderr” respectively as well as any output files specified in results, converted by
convert()
.- Return type
dict
- Raises
ValueError – If the MADX executable cannot be resolved either via madx or the MADX environment variable.
MADXError – If the MADX executable returns a non-zero exit code. The raised error has additional attributes script, which is the content of the script that caused the error, as well as stdout and stderr which contain the MADX output. The
__cause__
of that error is set to the original subprocess.CalledProcessError.
See also
convert()
Used for converting specified output files.
-
dipas.madx.utils.
run_script
(script: str, results: Union[Sequence[str], Dict[str, bool]] = None, *, variables: Dict[str, Any] = None, format: Dict[str, Any] = None, parameters: Dict[str, Dict[str, Any]] = None, twiss: Union[typing_extensions.Literal[True][True], Dict[str, Any]] = None, madx: str = None, wdir: Optional[str] = None) → Dict¶ Run the given MADX script through the MADX program.
- Parameters
script (str) – The MADX script to be run.
results (list or dict, optional) – File names of generated output files that should be returned. The content of these files will be automatically converted based on the chosen filename. For TFS-style files this does not include the header meta data (prefixed by “@”) by default. If the header meta data should be returned as well, a dict can be used, mapping file names to bool flags that indicate whether meta data for this file is requested or not. More generally one can also provide a dict per file name that represents the keyword arguments that will be passed to
convert()
for that particular file. One can also use a special syntax for requesting meta data or indicating a specific file type. The syntax for each file name is<file_name>+meta;<file_type>
where+meta
and;<file_type>
are optional. For exampleexample.tfs
would be parsed as a TFS file without parsing meta data. Usingexample.tfs+meta
also returns the meta data. Orexample.tfs;raw
would return the raw content of the file rather than parsing it. For more information about file types seeconvert()
. If the twiss argument is given, and a file name is specified, then this will automatically be added to the results list (similar fortwiss=True
).variables (dict, optional) – Used for replacing statements of the form
key = old;
withkey = value;
.format (dict, optional) – Used for filling in format specifiers of the form
%(key)s
.parameters (dict, optional) – Parameters of lattice elements. Keys should be element labels and values dicts that map attribute names to their values. These definitions will be inserted after the last sequence definition. For example
{"qh1": {"k1": 0.1}}
will be inserted asqh1->k1 = 0.1;
.twiss (True or dict, optional) – Parameters for the TWISS command. If this argument is given, then a TWISS command is appended at the end of the script. The dict keys should be parameter names, such as
tolerance
with corresponding values. The key"select"
, if present, should map to another dict that specifies the parameters for a preceding select statement. Theflag = twiss
parameter does not need to be specified as it will be added automatically. If thefile
parameter is specified, the file name does not need to be specified in results, it will be added automatically. If meta information of the resulting TWISS file is required, an additional'meta': True
entry in the twiss dict can be provided. If True then the TWISS command is run with MADX default parameters while saving to a file named “twiss”. The corresponding data is returned together with the meta data. Thus specifyingtwiss=True
is equivalent totwiss=dict(file='twiss', meta=True)
.madx (str, optional) – File name pointing to the MADX executable. If the MADX environment variable is set it takes precedence.
wdir (str, optional) – The working directory in which the script will be run. Note that a file named “main.madx” will be created in that directory, overwriting any existing file with that name. If not specified then a temporary working directory is created.
- Returns
output – Containing the stdout and stderr at keys “stdout” and “stderr” respectively as well as any output files specified in results, converted by
convert()
.- Return type
dict
- Raises
ValueError – If the MADX executable cannot be resolved either via madx or the MADX environment variable.
subprocess.CalledProcessError – If the MADX executable returns a non-zero exit code.
See also
convert()
Used for converting specified output files.
-
dipas.madx.utils.
run_orm
(script: str, kickers: Sequence[str], monitors: Sequence[str], *, kicks: Tuple[float, float] = (-0.001, 0.001), variables: Optional[Dict[str, Any]] = None, parameters: Dict[str, Dict[str, Any]] = None, twiss_args: Optional[Dict[str, Any]] = None, madx: str = None) → <MagicMock name='mock.DataFrame' id='139994650600000'>¶ Compute the Orbit Response Matrix (ORM) for the given sequence script, kickers and monitors.
- Parameters
script (str) – Either the file name of the script or the script itself. The script must contain the beam and the sequence definition.
kickers (list of str) – Kicker labels.
monitors (list of str) – Monitor labels.
kicks (2-tuple of float) – The kick strengths to be used for measuring the orbit response.
variables (dict) – See
run_script()
.parameters (dict) – See
run_script()
.twiss_args (dict) – Additional parameters for the TWISS command.
madx (str) – See
run_script()
.
- Returns
orm – Index == kickers, columns == monitors.
- Return type
pd.DataFrame
-
dipas.madx.utils.
convert
(f_name: str, f_type: Optional[typing_extensions.Literal['madx', 'raw', 'tfs', 'trackone'][madx, raw, tfs, trackone]] = None, meta: bool = False) → Union[<MagicMock name='mock.DataFrame' id='139994650600000'>, str, dipas.madx.parser.Script, Tuple[<MagicMock name='mock.DataFrame' id='139994650600000'>, Dict[str, str]]]¶ Convert MADX output file by automatically choosing the appropriate conversion method based on the file name.
- Parameters
f_name (str) – If ends with “one” then a
TRACK, ONETABLE = true
is assumed and a pd.DataFrame is returned. If suffix is one of {“.madx”, “.seq”} then a tuple according to madx.parse_file is returned. Otherwise a TFS file is assumed and converted to a pd.DataFrame. If this fails the raw string content is returned. Raw string content can also be enforced by using the suffix “.raw”; this supersedes the other cases.f_type (str) –
- Determines how the file should be loaded. The following types can be used:
”madx” – parses the file as a MADX script, using
parse_file()
.”raw” – loads the raw content of the file.
”tfs” – parses the file as a TFS file, using
convert_tfs()
.”trackone” – parses the file as a TRACKONE file, using
convert_trackone()
.
meta (bool) – Indicates whether TFS meta data (prefixed with “@”) should be returned in form of a dict. This is only possible for trackone and tfs tables.
- Returns
- Return type
The return value depends on the choice of the file name (see f_name).
-
dipas.madx.utils.
convert_tfs
(f_name: str, meta: bool = False) → Union[<MagicMock name='mock.DataFrame' id='139994650600000'>, Tuple[<MagicMock name='mock.DataFrame' id='139994650600000'>, Dict[str, str]]]¶ Convert table in TFS (Table File System) format to pandas data frame.
- Parameters
f_name (str) – File name pointing to the TFS file.
meta (bool, optional) – If True, return meta information prefixed by “@ ” in form of a dict.
- Returns
df – The corresponding data frame. If meta is True then a tuple containing the data frame and the meta data in form of a dict is returned.
- Return type
pd.DataFrame
- Raises
ValueError – If the given table is incomplete or if it’s not presented in TFS format.
-
dipas.madx.utils.
convert_trackone
(f_name: str, meta: bool = False) → Union[<MagicMock name='mock.DataFrame' id='139994650600000'>, Tuple[<MagicMock name='mock.DataFrame' id='139994650600000'>, Dict[str, str]]]¶ Convert “trackone” table (generated by
TRACK, onetable = true
) to pandas data frame.- Parameters
f_name (str) – File name pointing to the “trackone” file.
meta (bool, optional) – If True, return meta information prefixed by “@ ” in form of a dict.
- Returns
df – The corresponding data frame, augmented by two columns “PLACE” and “LABEL” indicating the observation places’ number and label respectively. The columns [LABEL, PLACE, NUMBER, TURN] are set as the data frame’s index. If meta is True then a tuple containing the data frame and the meta data in form of a dict is returned.
- Return type
pd.DataFrame
- Raises
ValueError – If the given table is incomplete or if it’s not presented in TFS format.