Modules

General

Some helper functions for cpymad, that would be complicated macros in MAD-X.

cpymad_lhc.general.add_expression(madx: Madx, name: str, expression: str)[source]

Add an expression to a variable that might already be a deferred expression.

Parameters:
  • madx (Madx) -- Madx instance to incorporate the variable in

  • name (str) -- Name of the variable

  • expression (str) -- Expression to assign

cpymad_lhc.general.amplitude_detuning_ptc(madx: Madx, ampdet: int = 2, chroma: Optional[int] = None, file: Optional[Path] = None) TfsDataFrame[source]

Calculate amplitude detuning via PTC_NORMAL

Parameters:
  • madx -- Madx instance

  • ampdet -- Maximum derivative order for amplitude detuning (only 0, 1 or 2 implemented). Default 2

  • chroma -- Maximum derivative order for chromaticity. Default 2

  • file -- Path to output file. Default None

Returns:

TfsDataframe with results

cpymad_lhc.general.auto_dtype(df)[source]

Set DataFrame dtypes automatically.

cpymad_lhc.general.closest_tune_approach(madx: Madx, accel: str, sequence: str, qx: float, qy: float, dqx: float, dqy: float, step: float = 1e-07, tolerance: float = 1e-21, calls: float = 100, knobs_suffix: str = '')[source]

Tries to match the tunes to their mid-fractional tunes. The difference between this mid-tune and the actual matched tune is the closest tune approach.

cpymad_lhc.general.deactivate_arc_sextupoles(madx: Madx, beam: int)[source]

Deactivates all arc sextupoles.

Parameters:
  • madx -- Madx instance

  • beam -- beam to use

cpymad_lhc.general.dynamic_aperture_tracking(madx: Madx, sigmas: Sequence[int], n_angles: int, turns: int = 1024, min_delta: float = 0.05, outputdir: Optional[Path] = None)[source]

Perform MAD-X tracking via the DYNAP module.

Parameters:
  • madx -- Madx instance

  • n_sigma (int) -- Number of sigmas in amplitude for particle distribution

  • n_angles (int) -- number of angles for particle distribution

  • turns (int) -- number of turns to track. Default 1024

  • min_delta (float) -- minimum amplitude/angle to use, avoids using 0 and 1 values. Default 0.05

  • outputdir (Path) -- Path to write the output files. Default None

cpymad_lhc.general.fractional_tune(tune)[source]

Returns the fractional tune.

cpymad_lhc.general.get_coupling_knobs(accel: str, beam: int, suffix: str = '') Tuple[str, str][source]

Get names of knobs to change coupling as tuple of strings.

Parameters:
  • accel -- Accelerator either ‘LHC’ or ‘HLLHC’

  • beam -- Beam to use, for the (LHC) knob names

  • suffix (str) -- suffix to add to the knobs, e.g. _sq

Returns:

Tuple of strings like (real_knob, imaginary_knob)

cpymad_lhc.general.get_k_strings(start: int = 0, stop: int = 8, orientation: str = 'both')[source]

Return all K-column names for a given range.

Parameters:
  • start -- lowest order to include. Default 0.

  • stop -- highest order + 1 to include (same as in range()). Default 8.

  • orientation -- ‘S’ for skew, ‘’ for normal, ‘both’ for both

cpymad_lhc.general.get_kqs_for_coupling_correction(beam: int) List[str][source]

Returns a list of elements for the respective beam as used for coupling correction.

Parameters:

beam -- Beam to use

Returns:

List of KQS-names.

cpymad_lhc.general.get_lhc_sequence_filename_and_bv(beam: int, accel: str = 'lhc')[source]

Return the default sequence filename, the sequence name and the bv-flag for the given beam.

Parameters:
  • beam (int) -- beam to use.

  • accel (str) -- accelerator name (‘lhc’ or ‘hllhc’).

cpymad_lhc.general.get_tfs(table: Table, index: Optional[Sequence] = None, columns: Optional[Sequence] = None, index_regex: Optional[str] = None, columns_regex: Optional[str] = None, only_selected: bool = False, remove_element_numbering: bool = True) TfsDataFrame[source]

Returns the filtered content of the given table as TfsDataFrame.

Parameters:
  • table -- madx table to convert to dataframe

  • index -- indices to be included in dataframe (need ot be present in table)

  • columns -- columns to be included in dataframe (need to be present in table)

  • index_regex -- regex-selection to be applied onto (selected) indices

  • columns_regex -- regex-selection to be applied onto (selected) columns

  • only_selected -- returns only selected rows and columns. Overridden by either index for rows or columns for columns (i.e. the given index or columns will be returned). If the selection is empty ALL rows and columns will be returned, as it can not be decided if the selection is empty from a clear, or from over-exclusive selection.

  • remove_element_numbering -- Removes the :# from the element names (present in column NAME in twiss/error tables)

Returns:

TfsDataFrame with selected indices and columns from table and summary as header, if available.

cpymad_lhc.general.get_tune_and_chroma_knob_values(madx: Madx, accel: str, beam: int, suffix: str = '') dict[source]

Saves the current tune and dispersion knob values into list.

Parameters:
  • madx -- Madx instance

  • accel -- Accelerator we are using ‘LHC’ or ‘HLLHC’ see get_tune_and_dispersion_knobs()

  • beam -- beam we are using

  • suffix (str) -- suffix to add to the knobs, e.g. _sq

Returns:

Dict of qx, qy, dqx and dqy knob values.

cpymad_lhc.general.get_tune_and_chroma_knobs(accel: str, beam: int, suffix: str = '') Tuple[str, str, str, str][source]

Get names of knobs to change tune and chromaticity as tuple of strings.

Parameters:
  • accel -- Accelerator either ‘LHC’ (dQ[xy], dQp[xy] knobs) or ‘HLLHC’ (kqt[fd], ks[fd] knobs)

  • beam -- Beam to use, for the knob names

  • suffix (str) -- suffix to add to the knobs, e.g. _sq

Returns:

Tuple of strings like (qx, qy, dqx, dqy)

cpymad_lhc.general.lhc_arc_names(beam: int) List[str][source]

Names of all arcs for given beam.

cpymad_lhc.general.lhc_arcs() List[str][source]

Strings of all LHC arcs.

cpymad_lhc.general.match_tune(madx: Madx, accel: str, sequence: str, qx: float, qy: float, dqx: Optional[float] = None, dqy: Optional[float] = None, step: float = 1e-07, tolerance: float = 1e-21, calls: int = 100, knobs_suffix: str = '')[source]

Simple tune (and chromaticity) matching. If both are given it matches first tune and dispersion independently and then together.

Parameters:
  • madx -- Madx instance

  • accel -- Accelerator we are using ‘LHC’ or ‘HLLHC’

  • sequence -- Sequence to use

  • qx -- tune to match in x

  • qy -- tune to match in y

  • dqx -- chromaticity to match in x

  • dqy -- chromaticity to match in y

  • step -- step size to vary knob

  • tolerance -- tolerance for successfull matching

  • calls -- number of varying calls

  • knobs_suffix -- suffix to use with the knobs, e.g.`_sq`

cpymad_lhc.general.power_landau_octupoles(madx: Madx, mo_current: float, beam: int, defective_arc: bool = False)[source]

Power the landau octupoles.

Parameters:
  • madx -- Madx instance

  • mo_current -- MO powering in ampere

  • beam -- beam to use

  • defective_arc -- If true the KOD in Arc 56 are powered for less Imax

cpymad_lhc.general.rdts_ptc(madx: Madx, order: int = 4, file: Optional[Path] = None) TfsDataFrame[source]

Calculate the RDTs via PTC_TWISS.

Parameters:
  • madx -- Madx instance

  • order -- Maximum order of the RDTs. Default 4

  • file -- Path to rdt output file. Default None

Returns:

TfsDataframe with results

cpymad_lhc.general.sixtrack_output(madx, energy, outputdir: Optional[Path] = None)[source]

Prepare output for sixtrack run.

cpymad_lhc.general.switch_magnetic_errors(madx: Madx, **kwargs)[source]

Which magnetic field orders to apply.

Parameters:

madx -- Madx instance

Keyword Arguments:
  • default -- sets global default to this (default of default is False).

  • AB# -- sets the default for all of that order.

  • B# (A# or) -- sets the default for systematic and random of this id.

  • etc. (A#s, B#r) -- sets the specific value.

with # in [1, 15], where 1 == dipolar field.

cpymad_lhc.general.temp_disable_errors(madx: Madx, *args)[source]

Disable all global variable args and restore their value afterwards.

Corrector Limits

Checks whether the assigned strengths do not exceed a given maxima. If it does exceed it, depending on limit_to_max either an error is thrown or the strength is redefined to the maximum (while its sign is retained). All values are energy independent.

The python script was adapted from errors/corr_limit.madx or errors/corr_value_limit.madx (depending on HL-LHC version)

cpymad_lhc.corrector_limits.check_corrector_limits(madx: Madx, accel: str, beam: int, limit_to_max: bool = False)[source]

Wrapper to run the limit checks.

Parameters:
  • madx (Madx) -- MAD-X instance

  • accel (str) -- Accelerator to check.

  • beam (int) -- Beam to check

  • limit_to_max (bool) -- If True set the value to the max if above limit. If False will raise ValueError after finding too high values. Default: False.

Coupling Correction

Creates a coupling knob from current optics. Perform coupling correction. The functionality is based on the FineTuneCoupling scripts.

cpymad_lhc.coupling_correction.correct_coupling(madx: Madx, accel: str, sequence: str, knobs_suffix: str = '', **kwargs)[source]
Wrapper for coupling correction to use the default knob-names if not

otherwise given.

Parameters:
  • madx -- Madx instance

  • accel -- Accelerator we are using ‘LHC’ or ‘HLLHC’

  • sequence -- Sequence to use

  • knobs_suffix -- Use suffix with knobs ( e.g. _sq)

Keyword Arguments:

correct_coupling_with_knobs (Other arguments of) --

cpymad_lhc.coupling_correction.correct_coupling_with_knobs(madx: Madx, sequence: str, tune_knobs: List[str], chroma_knobs: List[str], coupling_knobs: List[str], qx: float, qy: float, dqx: float, dqy: float, iterations: int = 2, tolerance: float = 1e-07, simplex: bool = False, pre_estimation: bool = True, match_tunes: bool = True)[source]

Corrects coupling via the given knobs.

If there is no coupling, the tunes should be able to be matched to the same factional tunes (mid-tunes). If there is a remaining tune split, this is the closest tune approach (cta) and indicates the presence of coupling.

The algorithm is as follows: First the coupling knob settings are estimated by a one-step newton optimization (if pre_estimate is set). Then the tune-knobs and the coupling knobs are used alternatingly to match the tunes together. This is iterated according to the desired iteration parameter. Before and after this correction the cta is checked.

Remark: The first twiss call in the first _analytical_minimization call is unneccessary as the nothing has changed between this one and the one in _cta_check. Could be somehow checked for speed optimization.

Parameters:
  • madx -- Madx instance

  • tune_knobs -- names of elements/knobs to vary for tune matching

  • chroma_knobs -- names of elements/knobs to vary for chroma matching:

  • coupling_knobs -- names of elements/knobs to vary for coupling matching:

  • sequence -- Sequence to use

  • qx -- tune to match in x

  • qy -- tune to match in y

  • dqx -- chromaticity to match in x

  • dqy -- chromaticity to match in y

  • tolerance -- (final) tolerance for successfull matching

  • iterations -- number of iterations in empirical matching

  • simplex -- use simplex method in empirical matching

  • pre_estimation -- use analytical method to estimate coupling-knob settings. This will only work if the given coupling knobs correspond to the imaginary and real part of F1001.

  • match_tunes -- If true, also performs a tune and chroma match at the end, otherwise, the original tune-knob values are recovered.

cpymad_lhc.coupling_correction.match(madx: Madx, sequence: str, knobs: Sequence[str], step: float = 1e-07, tolerance: float = 1e-21, calls: float = 100, chrom=False, simplex=False, **kwargs)[source]

Match the knobs to the settings in kwargs.

Parameters:
  • madx -- Madx instance

  • sequence -- Sequence to use

  • knobs -- Sequence of variables to match

  • chrom -- use the chrom flag in match

  • step -- step size to vary knob

  • calls -- number of varying calls

  • tolerance -- (final) tolerance for successfull matching

Keyword Arguments:
  • at, (Arguments for the MAD-X global command to be matched) --

  • etc. (e.g. q1=, dqy=) --

Coupling Knob

Creates a coupling knob from current optics. Not implemented yet. TODO!

cpymad_lhc.coupling_knob.calculate_coupling_coefficients_per_sector(df: TfsDataFrame, deactivate_sectors: Sequence[str] = ('12', '45', '56', '81')) TfsDataFrame[source]

Calculate the coupling knob coefficients as in corr_MB_ats_v4. This is basically Eq. (59) in https://cds.cern.ch/record/522049/files/lhc-project-report-501.pdf , with cosine for the real part and sine for the imaginary part. What is happening here is, that we are building a matrix for the equation-system M * [MQS12,…, MQS81] = -[RE, IM] where RE and IM are the real and imaginary parts of the coupling coefficients, and therefore the knobs we want to create. MQS12 - MQS81 is the total powering of the MQS per arc, which we steer with the knob. All MQS in a single arc are assumed to be powered equally. After building the matrix, we “solve” the equation system via pseudo-inverese M+ and get therefore the definition of the coupling knob. [MQS12,…, MQS81] = - M+ * [RE, IM] HINT: The MINN function in corr_MB_ats_v4 is simply the calculation the pseudo-inverse: M+ = M’ (M * M’)^-1 (’ = transpose, ^-1 = inverse) including the minus on the rhs of the equation. .. todo:

- Get beta and phases from the beamline directly (instead of the TFS dataframe)
- Make the number of MQS more flexible, could maybe be parsed from the beamline
- Why is there an absolute value in Eq. (59) but not in the code? (see also https://cds.cern.ch/record/2778887/files/CERN-ACC-NOTE-2021-0022.pdf)
- Add a2 correction to the KQS definition (as in corr_MB_ats_v4)
- Include the actual fractional tune split of the current machine (see also https://cds.cern.ch/record/2778887/files/CERN-ACC-NOTE-2021-0022.pdf)
- Calculate also the contribution to f_1010 and try to set to zero
- Does this still work when slicing the MQS?
Parameters:
  • df (tfs.TfsDataFrame) -- Dataframe containing the optics of the machine.

  • deactivate_sectors (Sequence[str], optional) -- Deactivate these sectors, i.e. don’t use their MQS. Defaults to (‘12’, ‘45’, ‘56’, ‘81’), the ATS sectors.

cpymad_lhc.coupling_knob.create_coupling_knobs(madx: Madx, beam: int, accel: str, optics: Optional[Union[Path, TfsDataFrame]] = None)[source]

Create coupling knobs in the beam-line. WARNING: This function will not take a2 errors into account! Normally, the a2 errors are also corrected with the MQS, but in this function the MQS powering is fully controlled by the coupling knobs. See also the todo’s in xmask.lhc.knob_manipulations.calculate_coupling_coefficients_per_sector() :param madx: Madx instance to incorporate the knobs in :type madx: Madx :param beam: Beam number. :type beam: int :param optics: Path or TfsDataFrame of the twiss containing the optics to be used.

If not given, a twiss will be computed. Defaults to None.

cpymad_lhc.coupling_knob.get_attribute_response(madx: Madx, sequence: str, variables: Sequence[str], attribute: str) DataFrame[source]

Creates the linear response matrix of the given variables for the desired attributed.

IR Orbit

Functions to setup and check the orbit in the IRs.

The values in the on_ knobs (see CROSSING_SCHEMES and get_orbit_variables()) refer to the settings in mm and urad in Beam 1 (i.e. not only the Beam 1 reference frame but Beam 1 itself). Beam 2 or Beam 4 are then configured accordingly. To check the twiss if everything is set correctly, the following symmetry/sign relations should hold true:

Beam 1 and Beam 2 share coordinate system. Crossing angles - opposite sign Crossing offsets (same plane) - same sign Separation - opposite sign

Beam 1 and Beam 4 have x-axis inverted. Y Crossing Angles - same sign Y Crossing offsets - same sign (i.e. same side) X Separation - same sign (i.e. opposite sides)

X Crossing Angles - opposite sign X Crossing offsets - opposite sign (i.e. same sides) Y Separation - opposite sign (i.e. opposite sides)

cpymad_lhc.ir_orbit.check_crabbing(madx: Madx, auto_set: bool = False)[source]

Check that the crabbing is not larger than the crossing angle.

Parameters:
  • madx -- Madx instance

  • auto_set -- instead of throwing an error, set the crabbing to the xing.

cpymad_lhc.ir_orbit.get_current_orbit_scheme(madx: Madx, accel: str, year: int = 2018)[source]

Get the current values for the orbit variales.

Parameters:
  • madx -- Madx instance

  • accel (str) -- ‘lhc’ or ‘hllhc’

  • year (int) -- year of the models/optics (for ‘lhc’)

Returns:

Dictionary of all orbit variables and their value/definition.

cpymad_lhc.ir_orbit.get_orbit_variables(accel: str, year: int = 2018)[source]

Get the variable names used for orbit setup. :param accel: ‘lhc’ or ‘hllhc’ :type accel: str :param year: year of the models/optics (for ‘lhc’) :type year: int

Returns:

list of all orbit variables, apart form those in 1
1: dictionary of additional variables, that in the

default configurations have the same value as another variable

Return type:

tuple of 0

cpymad_lhc.ir_orbit.log_orbit(madx: Madx, accel: str, year: int = 2018, twiss: Optional[TfsDataFrame] = None, ip: Optional[Union[Iterable[int], int]] = None)[source]

Get the orbit from madx-instance and twiss-dataframe and log the configuration per IP.

cpymad_lhc.ir_orbit.log_orbit_from_madx(madx: Madx, accel: str, year: int = 2018, ip: Optional[Union[Iterable[int], int]] = None, variables: Optional[Iterable[str]] = None)[source]

Log current orbit scheme sorted by IP.

cpymad_lhc.ir_orbit.log_orbit_from_twiss(twiss: TfsDataFrame, ip: Optional[Union[Iterable[int], int]] = None)[source]

Log orbit from twiss-dataframe.

cpymad_lhc.ir_orbit.orbit_setup(madx: Madx, accel: str, year: int = 2018, **kwargs)[source]

Automated orbit setup for some default schemes. Please check if these are still valid.

Parameters:
  • madx -- Madx instance

  • accel (str) -- ‘lhc’ or ‘hllhc’

  • year (int) -- year of the models/optics (for ‘lhc’)

Keyword Arguments:
  • scheme -- default orbit scheme to apply. Choices: ‘flat’, ‘inj’, ‘top’, None Default: ‘flat’ (all values 0)

  • other -- All standard crossing scheme variables. Values given here override the values in the scheme, which in turn override the ones already set. If the value of a variable is None, the variable is not used (i.e. the value in the madx.globals is kept).

Returns:

dictionary with current settings of the scheme.

Logging

Logging tools with cpymad perks.

class cpymad_lhc.logging.MaxFilter(level)[source]

To get messages only up to a certain level

filter(log_record)[source]

Determine if the specified record is to be logged.

Is the specified record to be logged? Returns 0 for no, nonzero for yes. If deemed appropriate, the record may be modified in-place.

class cpymad_lhc.logging.StreamToLogger(logger, log_level=20)[source]

File-like stream object that redirects writes to a logger instance.

cpymad_lhc.logging.cpymad_logging_setup(command_log: Path = PosixPath('madx_commands.log'), full_log: Path = PosixPath('full_output.log'), output_log: Optional[Path] = None, colors: bool = True, level=20, clear_handlers: bool = True)[source]

Create all necessary logging. Adds stream handlers to root logger including cpymad loggers for output and commands. Takes also care of file handlers if specified.

Args

output_log: Path to write madx-output to (None to deactivate) command_log: Path to write madx-commands to (None to deactivate) full_log: Path to write full logging output to (None to deactivate) colors: Bool whether ascii-colors should be used level: Minimum stdout logging level. Madx commands and output are always logged clear_loggers: Clears all handlers of the loggers first.

Returns

dict with StreamToLoggers ‘stdout’ and ‘command_log’. Can be used as Madx(**cpymad_logging_setup())