API Reference

The cpymadtools package is a collection of utilities to conveniently handle MAD-X simulations through the cpymad library.

Useful Constants

Specific constants to be used in cpymadtools functions, to help with consistency.

Betatron Coupling Utilities

Module with functions to perform MAD-X actions through a Madx object, that retate to betatron coupling in the machine.

cpymadtools.coupling.get_closest_tune_approach(madx: cpymad.madx.Madx, accelerator: Optional[str] = None, sequence: Optional[str] = None, varied_knobs: Optional[Sequence[str]] = None, telescopic_squeeze: bool = True, run3: bool = False, explicit_targets: Optional[Tuple[float, float]] = None, step: float = 1e-07, calls: int = 100, tolerance: float = 1e-21) float[source]

New in version 0.16.0.

Provided with an active Madx object, tries to match the tunes to their mid-fractional tunes, a.k.a tries to get them together. The difference between the final reached fractional tunes is the closest tune approach. This should not have any effect on the user’s simulation, as the varied knobs are restored to their previous values after performing the CTA. This uses match_tunes_and_chromaticities under the hood.

Note

This assumes the sequence has previously been matched to the user’s desired working point, as if not explicitely given, the appropriate targets will be determined from the MAD-X internal tables.

Important

This is hard-coded to use the CHROM flag when performing matching, since we expect to be in the presence of betatron coupling. In this case, attempting to match chromaticities at the same time as the tunes might cause LMDIF to fail, as the knobs become dependent. For this reason, only tune matching is performed here, and chromaticities are voluntarily ignored.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • accelerator (Optional[str]) -- name of the accelerator, used to determmine knobs if variables is not given. Automatic determination will only work for LHC and HLLHC.

  • sequence (str) -- name of the sequence you want to activate for the tune matching.

  • varied_knobs (Sequence[str]) -- the variables names to VARY in the MAD-X MATCH routine. An input could be ["kqf", "ksd", "kqf", "kqd"] as they are common names used for quadrupole and sextupole strengths (focusing / defocusing) in most examples.

  • telescopic_squeeze (bool) -- LHC specific. If set to True, uses the (HL)LHC knobs for Telescopic Squeeze configuration. Defaults to True since v0.9.0.

  • run3 (bool) -- if set to True, uses the LHC Run 3 *_op knobs. Defaults to False.

  • explicit_targets (Tuple[float, float]) -- if given, will be used as matching targets for (Qx, Qy). Otherwise, the target is determined as the middle of the current fractional tunes. Defaults to None.

  • step (float) -- step size to use when varying knobs.

  • calls (int) -- max number of varying calls to perform.

  • tolerance (float) -- tolerance for successfull matching.

Returns

The closest tune approach, in absolute value.

Example

>>> # Say we have set the LHC coupling knobs to 1e-3
>>> dqmin = get_closest_tune_approach(
...     madx,
...     "lhc",                    # will find the knobs automatically
...     sequence="lhcb1",
...     telescopic_squeeze=True,  # influences the knobs definition
...     run3=True,                # influences the knobs definition (LHC Run 3)
... )
0.001
cpymadtools.coupling.get_cminus_from_coupling_rdts(madx: cpymad.madx.Madx, patterns: Sequence[str] = [''], method: str = 'teapot', qx: Optional[float] = None, qy: Optional[float] = None, filtering: float = 0) float[source]

New in version 0.20.0.

Computes and returns the \(|C^{-}|\) from the machine’s coupling RDTs. The closest tune approach is computed thanks to functionality from optics_functions.coupling.

Hint

A quick estimate of the \(|C^{-}|\) is available in MAD-X as the dqmin variable in the SUMM table. However this estimate is not accurate in all situations, and is the norm of a complex vector which is not approriate for comparisons or for normalizations, which is the use-case of this functions.

Note

If using the “calaga”, “teapot”, “teapot_franchi” or “franchi” method, then the returned value will be a real number.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • patterns (Sequence[str]) -- the different patterns (such as MQX or BPM) of elements to use when computing the coupling RDTs. Defaults to [""] which will select and use all elements in the TWISS outputs.

  • method (str) -- the method to use for the calculation of the \(C^{-}\). Defaults to teapot, which is the default of closest_tune_approach.

  • qx (float) -- the horizontal tune. Defaults to None, in which case the value will be taken from the SUMM table.

  • qy (float) -- the vertical tune. Defaults to None, in which case the value will be taken from the SUMM table.

  • filtering (float) -- If non-zero value is given, applies outlier filtering of BPMs based on the abs. value of the coupling RTDs before computing the \(C^{-}\). The given value corresponds to the std. dev. \(\sigma\) outside of which to filter out a BPM. Defaults to 0, which means no filtering.

Returns

The calculated \(|C^{-}|\) value.

Examples

To compute the \(|C^{-}|\) taking in consideration all elements in the sequence:

>>> complex_cminus = get_cminus_from_coupling_rdts(madx)

To simulate the calculation from a measurement, with RDTs computed at BPMs only:

>>> complex_cminus = get_cminus_from_coupling_rdts(madx, patterns=["^BPM.*B[12]$"])
cpymadtools.coupling.get_coupling_rdts(madx: cpymad.madx.Madx, **kwargs) tfs.frame.TfsDataFrame[source]

New in version 0.20.0.

Computed the coupling Resonance Driving Tensors (RDTs) \(f_{1001}\) and \(f_{1010}\) at all elements in the currently active sequence from a TWISS call.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • **kwargs -- any keyword argument will be transmitted to the TWISS command in MAD-X. Note that CHROM is already provided as it is needed for the RDTs’ calculation.

Returns

A TfsDataFrame with columns of the TWISS table, and two complex columns for the F1001 and f1010 RDTs.

Example

>>> twiss_rdts = get_coupling_rdts(madx)
cpymadtools.coupling.match_no_coupling_through_ripkens(madx: cpymad.madx.Madx, sequence: Optional[str] = None, location: Optional[str] = None, vary_knobs: Optional[Sequence[str]] = None) None[source]

New in version 0.16.0.

Matching routine to get cross-term Ripken parameters \(\beta_{12}\) and \(\beta_{21}\) to be 0 at a given location.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • sequence (str) -- name of the sequence to activate for the matching.

  • location (str) -- the name of the element at which one wants the cross-term Ripkens to be 0.

  • vary_knobs (Sequence[str]) -- the variables names to VARY in the MAD-X routine.

Example

>>> match_no_coupling_through_ripkens(
...     madx, sequence="lhcb1", location="IP5", vary_knobs=["kqsx.3l5", "kqsx.3r5"]
... )

LHC-Specific Utilities

Module with functions to perform MAD-X actions through a Madx object, that are specific to LHC and HLLHC machines.

Important

The functions documented below are shown as coming from private modules (_coupling, _misc, _setup etc). They are still all accessible at the pyhdtoolkit.cpymadtools.lhc level, but any user is free to import and use them directly from the private modules if they wish to do so. In short, the two options below are both valid:

from cpymadtools.lhc import LHCSetup
# use this now
from cpymadtools.lhc._setup import LHCSetup
# use this now

Coupling Utilities

The functions below are betatron coupling utilities for the LHC.

cpymadtools.lhc._coupling.correct_lhc_global_coupling(madx: cpymad.madx.Madx, beam: int = 1, telescopic_squeeze: bool = True, calls: int = 100, tolerance: float = 1e-21) None[source]

New in version 0.20.0.

A littly tricky matching routine to perform a decent global coupling correction using the LHC coupling knobs.

Important

This routine makes use of some matching tricks and uses the SUMM table’s dqmin variable for the matching. It should be considered a helpful little trick, but it is not a perfect solution.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • beam (int) -- which beam you want to perform the matching for, should be 1 or 2. Defaults to 1.

  • telescopic_squeeze (bool) -- If set to True, uses the coupling knobs for Telescopic Squeeze configuration. Defaults to True.

  • calls (int) -- max number of varying calls to perform when matching. Defaults to 100.

  • tolerance (float) -- tolerance for successfull matching. Defaults to \(10^{-21}\).

Example

>>> correct_lhc_global_coupling(madx, sequence="lhcb1", telescopic_squeeze=True)
cpymadtools.lhc._coupling.get_lhc_bpms_twiss_and_rdts(madx: cpymad.madx.Madx) tfs.frame.TfsDataFrame[source]

New in version 0.19.0.

Runs a TWISS on the currently active sequence for all LHC BPMs. The coupling RDTs are also computed through a CMatrix approach via optics_functions.coupling.coupling_via_cmatrix.

Parameters

madx (cpymad.madx.Madx) -- an instanciated Madx object.

Returns

A TfsDataFrame of the TWISS table with basic default columns, as well as one new column for each of the coupling RDTs. The coupling RDTs are returned as complex numbers.

Example

>>> twiss_with_rdts = get_lhc_bpms_twiss_and_rdts(madx)

Elements Utilities

The functions below are utilities to install elements or markers in the LHC.

cpymadtools.lhc._elements.add_markers_around_lhc_ip(madx: cpymad.madx.Madx, sequence: str, ip: int, n_markers: int, interval: float) None[source]

New in version 1.0.0.

Adds some simple marker elements left and right of an IP point, to increase the granularity of optics functions returned from a TWISS call.

Warning

You will most likely need to have sliced the sequence before calling this function, as otherwise there is a risk on getting a negative drift depending on the affected IP. This would lead to the remote MAD-X process to crash.

Warning

After editing the sequence to add markers, the USE command will be run for the changes to apply. This means the caveats of USE apply, for instance the erasing of previously defined errors, orbits corrections etc.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • sequence (str) -- which sequence to use the routine on.

  • ip (int) -- The interaction point around which to add markers.

  • n_markers (int) -- how many markers to add on each side of the IP.

  • interval (float) -- the distance between markers, in [m]. Giving interval=0.05 will place a marker every 5cm (starting 5cm away from the IP on each side).

Example

>>> add_markers_around_lhc_ip(
...     madx, sequence=f"lhcb1", ip=1, n_markers=1000, interval=0.001
... )
cpymadtools.lhc._elements.install_ac_dipole_as_kicker(madx: cpymad.madx.Madx, deltaqx: float, deltaqy: float, sigma_x: float, sigma_y: float, beam: int = 1, start_turn: int = 100, ramp_turns: int = 2000, top_turns: int = 6600) None[source]

New in version 0.15.0.

Installs an AC dipole as a kicker element in (HL)LHC beam 1 or 2, for tracking. This function assumes that you have already defined lhcb1/lhcb2 sequence, made a beam for it (BEAM command or make_lhc_beams function), matched to your desired working point and made a TWISS call.

Important

In a real machine, the AC Dipole does impact the orbit as well as the betatron functions when turned on (Miyamoto et al. [MKJS08], part III). In MAD-X however, it cannot be modeled to do both at the same time. This routine introduces an AC Dipole as a kicker element so that its effect can be seen on particle trajectory in tracking. It does not affect TWISS functions.

One can find a full example use of the function for tracking in the AC Dipole Tracking example gallery.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • deltaqx (float) -- the deltaQx (horizontal tune excitation) used by the AC dipole.

  • deltaqy (float) -- the deltaQy (vertical tune excitation) used by the AC dipole.

  • sigma_x (float) -- the horizontal amplitude to drive the beam to, in bunch sigma.

  • sigma_y (float) -- the vertical amplitude to drive the beam to, in bunch sigma.

  • beam (int) -- the LHC beam to install the AC Dipole into, either 1 or 2. Defaults to 1.

  • start_turn (int) -- the turn at which to start ramping up the AC dipole. Defaults to 100.

  • ramp_turns (int) -- the number of turns to use for the ramp-up and the ramp-down of the AC dipole. This number is important in order to preserve the adiabaticity of the cycle. Defaults to 2000 as in the LHC.

  • top_turns (int) -- the number of turns to drive the beam for. Defaults to 6600 as in the LHC.

Example

>>> install_ac_dipole_as_kicker(
...     madx,
...     deltaqx=-0.01,  # driven horizontal tune to Qxd = 62.31 - 0.01 = 62.30
...     deltaqy=0.012,  # driven vertical tune to Qyd = 60.32 + 0.012 = 60.332
...     sigma_x=2,  # bunch amplitude kick in the horizontal plane
...     sigma_y=2,  # bunch amplitude kick in the vertical plane
...     beam=1,  # beam for which to install and kick
...     start_turn=100,  # when to turn on the AC Dipole
...     ramp_turns=2000,  # how many turns to ramp up/down the AC Dipole
...     top_turns=6600,  # how many turns to keep the AC Dipole at full kick
... )
cpymadtools.lhc._elements.install_ac_dipole_as_matrix(madx: cpymad.madx.Madx, deltaqx: float, deltaqy: float, beam: int = 1) None[source]

New in version 0.15.0.

Installs an AC dipole as a matrix element in (HL)LHC beam 1 or 2, to see its effect on TWISS functions This function assumes that you have already defined lhcb1/lhcb2 sequence, made a beam for it (BEAM command or make_lhc_beams function), matched to your desired working point and made a TWISS call.

This function’s use is very similar to that of install_ac_dipole_as_kicker.

Important

In a real machine, the AC Dipole does impact the orbit as well as the betatron functions when turned on (Miyamoto et al. [MKJS08], part III). In MAD-X however, it cannot be modeled to do both at the same time. This routine introduces an AC Dipole as a matrix element so that its effect can be seen on TWISS functions. It does not affect tracking.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • deltaqx (float) -- the deltaQx (horizontal tune excitation) used by the AC dipole.

  • deltaqy (float) -- the deltaQy (vertical tune excitation) used by the AC dipole.

  • beam (int) -- the LHC beam to install the AC Dipole into, either 1 or 2. Defaults to 1.

Example

>>> install_ac_dipole_as_matrix(madx, deltaqx=-0.01, deltaqy=0.012, beam=1)

Errors Utilities

The functions below are utilities to implement errors in elements of the LHC.

cpymadtools.lhc._errors.misalign_lhc_ir_quadrupoles(madx: cpymad.madx.Madx, ips: Sequence[int], beam: int, quadrupoles: Sequence[int], sides: Sequence[str] = ('r', 'l'), table: str = 'ir_quads_errors', **kwargs) None[source]

New in version 0.9.0.

Apply misalignment errors to IR quadrupoles on a given side of given IPs. In case of a sliced lattice, this will misalign all slices of each magnet together. According to the Equipment Codes Main System, those are Q1 to Q10 included, quads beyond are MQ or MQT which are considered arc elements.

One can find a full example use of the function for tracking in the LHC IR Errors example gallery.

Warning

This implementation is only valid for LHC IP IRs, which are 1, 2, 5 and 8. Other IRs have different layouts incompatible with this function.

Warning

One should avoid issuing different errors with several uses of this command as it is unclear to me how MAD-X chooses to handle this internally. Instead, it is advised to give all errors in the same command, which is guaranteed to work. See the last provided example below.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • ips (Sequence[int]) -- the interaction point(s) around which to apply errors.

  • beam (int) -- beam number to apply the errors to. Unlike triplet quadrupoles which are single aperture, Q4 to Q10 are not and will need this information.

  • quadrupoles (Sequence[int]) -- the number of the quadrupoles to apply errors to.

  • sides (Sequence[str]) -- sides of the IP to apply error on the triplets, either L or R or both. Case-insensitive. Defaults to both.

  • table (str) -- the name of the internal table that will save the assigned errors. Defaults to ‘ir_quads_errors’.

  • **kwargs -- Any keyword argument is given to the EALIGN command, including the error to apply (DX, DY, DPSI etc) as a string, like it would be given directly into MAD-X.

Examples

For systematic DX misalignment:

>>> misalign_lhc_ir_quadrupoles(
...     madx, ips=[1], quadrupoles=[1, 2, 3, 4, 5, 6], beam=1, sides="RL", dx="1E-5"
... )

For a tilt distribution centered on 1mrad:

>>> misalign_lhc_ir_quadrupoles(
...     madx, ips=[5],
...     quadrupoles=[7, 8, 9, 10],
...     beam=1,
...     sides="RL",
...     dpsi="1E-3 + 8E-4 * TGAUSS(2.5)",
... )

For several error types on the elements, here DY and DPSI:

>>> misalign_lhc_ir_quadrupoles(
...     madx,
...     ips=[1, 5],
...     quadrupoles=list(range(1, 11)),
...     beam=1,
...     sides="RL",
...     dy=1e-5,  # ok too as cpymad converts this to a string first
...     dpsi="1E-3 + 8E-4 * TGAUSS(2.5)"
... )
cpymadtools.lhc._errors.misalign_lhc_triplets(madx: cpymad.madx.Madx, ip: int, sides: Sequence[str] = ('r', 'l'), table: str = 'triplet_errors', **kwargs) None[source]

New in version 0.9.0.

Apply misalignment errors to IR triplet quadrupoles on a given side of a given IP. In case of a sliced lattice, this will misalign all slices of each magnet together. This is a convenience wrapper around the misalign_lhc_ir_quadrupoles function, see that function’s docstring for more information.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • ip (int) -- the interaction point around which to apply errors.

  • sides (Sequence[str]) -- sides of the IP to apply error on the triplets, either L or R or both. Case-insensitive. Defaults to both.

  • table (str) -- the name of the internal table that will save the assigned errors. Defaults to triplet_errors.

  • **kwargs -- Any keyword argument is given to the EALIGN command, including the error to apply (DX, DY, DPSI etc) as a string, like it would be given directly into MAD-X.

Examples

A random, gaussian truncated DX misalignment:

>>> misalign_lhc_triplets(madx, ip=1, sides="RL", dx="1E-5 * TGAUSS(2.5)")

A random, gaussian truncated DPSI misalignment:

>>> misalign_lhc_triplets(madx, ip=5, sides="RL", dpsi="0.001 * TGAUSS(2.5)")

Miscellaneous Utilities

The functions below are miscellaneous utilities for the LHC.

cpymadtools.lhc._misc.get_lhc_bpms_list(madx: cpymad.madx.Madx) List[str][source]

New in version 0.16.0.

Returns the list of monitoring BPMs for the current LHC sequence in use. The BPMs are queried through a regex in the result of a TWISS command.

Note

As this function calls the TWISS command and requires that TWISS can succeed on your sequence.

Parameters

madx (cpymad.madx.Madx) -- an instantiated cpymad.madx.Madx object.

Returns

The list of BPM names.

Example

>>> observation_bpms = get_lhc_bpms_list(madx)
cpymadtools.lhc._misc.get_lhc_tune_and_chroma_knobs(accelerator: str, beam: int = 1, telescopic_squeeze: bool = True, run3: bool = False) Tuple[str, str, str, str][source]

New in version 0.16.0.

Gets names of knobs needed to match tunes and chromaticities as a tuple of strings, for the LHC or HLLHC machines. Initial implementation credits go to Joschua Dilly.

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

  • beam (int) -- Beam to use, for the knob names. Defaults to 1.

  • telescopic_squeeze (bool) -- if set to True, returns the knobs for Telescopic Squeeze configuration. Defaults to True to reflect run III scenarios.

  • run3 (bool) -- if set to True, returns the Run 3 *_op knobs. Defaults to False.

Returns

A tuple of strings with knobs for (qx, qy, dqx, dqy).

Examples

>>> get_lhc_tune_and_chroma_knobs("LHC", beam=1, telescopic_squeeze=False)
('dQx.b1', 'dQy.b1', 'dQpx.b1', 'dQpy.b1')
>>> get_lhc_tune_and_chroma_knobs("LHC", beam=2, run3=True)
('dQx.b2_op', 'dQx.b2_op', 'dQpx.b2_op', 'dQpx.b2_op')
>>> get_lhc_tune_and_chroma_knobs("HLLHC", beam=2)
('kqtf.b2_sq', 'kqtd.b2_sq', 'ksf.b2_sq', 'ksd.b2_sq')
cpymadtools.lhc._misc.get_sizes_at_ip(madx: cpymad.madx.Madx, ip: int, geom_emit_x: Optional[float] = None, geom_emit_y: Optional[float] = None) Tuple[float, float][source]

New in version 1.0.0.

Get the Lebedev beam sizes (horizontal and vertical) at the provided LHC ip.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • ip (int) -- the IP to get the sizes at.

  • geom_emit_x (float) -- the horizontal geometrical emittance to use for the calculation. If not provided, will look for the values of the geometric_emit_x variable in MAD-X.

  • geom_emit_y (float) -- the vertical geometrical emittance to use for the calculation. If not provided, will look for the values of the geometric_emit_y variable in MAD-X.

Returns

A tuple of the horizontal and vertical beam sizes at the provided IP.

Example

>>> ip5_x, ip5_y = get_size_at_ip(madx, ip=5)
cpymadtools.lhc._misc.make_sixtrack_output(madx: cpymad.madx.Madx, energy: int) None[source]

New in version 0.15.0.

Prepare output for a SixTrack run. Initial implementation credits go to Joschua Dilly.

Parameters

Example

>>> make_sixtrack_output(madx, energy=6800)
cpymadtools.lhc._misc.reset_lhc_bump_flags(madx: cpymad.madx.Madx) None[source]

New in version 0.15.0.

Resets all LHC IP bump flags to 0.

Parameters

madx (cpymad.madx.Madx) -- an instanciated Madx object.

Example

>>> reset_lhc_bump_flags(madx)

Powering Utilities

The functions below are magnets or knobs powering utilities for the LHC.

cpymadtools.lhc._powering.apply_lhc_colinearity_knob(madx: cpymad.madx.Madx, colinearity_knob_value: float = 0, ir: Optional[int] = None) None[source]

New in version 0.15.0.

Applies the a trim of the LHC colinearity knob.

Note

If you don’t know what this is, you really should not be using this function.

Tip

The convention, which is also the one I implemented in LSA for the LHC, is that a positive value of the colinearity knob results in a powering increase of the MQSX right of the IP, and a powering decrease of the MQSX left of the IP.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • colinearity_knob_value (float) -- Units of the colinearity knob to apply. Defaults to 0 so users don’t mess up local IR coupling by mistake. This should be a positive integer, normally between 1 and 10.

  • ir (int) -- The Interaction Region to apply the knob to, should be one of [1, 2, 5, 8]. Classically 1 or 5.

Example

>>> apply_lhc_colinearity_knob(madx, colinearity_knob_value=5, ir=1)
cpymadtools.lhc._powering.apply_lhc_colinearity_knob_delta(madx: cpymad.madx.Madx, colinearity_knob_delta: float = 0, ir: Optional[int] = None) None[source]

New in version 0.21.0.

This is essentially the same as apply_lhc_colinearity_knob, but instead of a applying fixed powering value, it applies a delta to the (potentially) existing value.

Note

If you don’t know what this is, you really should not be using this function.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • colinearity_knob_delta (float) -- Units of the colinearity knob to vary the existing powerings with. Defaults to 0.

  • ir (int) -- The Interaction Region to apply the knob to, should be one of [1, 2, 5, 8]. Classically 1 or 5.

Example

>>> apply_lhc_colinearity_knob_delta(madx, colinearity_knob_delta=3.5, ir=1)
cpymadtools.lhc._powering.apply_lhc_coupling_knob(madx: cpymad.madx.Madx, coupling_knob: float = 0, beam: int = 1, telescopic_squeeze: bool = True) None[source]

New in version 0.15.0.

Applies a trim of the LHC coupling knob to reach the desired \(|C^{-}|\) value.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • coupling_knob (float) -- Desired value for the Cminus, typically a few units of 1E-3. Defaults to 0 so users don’t mess up coupling by mistake.

  • beam (int) -- beam to apply the knob to. Defaults to beam 1.

  • telescopic_squeeze (bool) -- if set to True, uses the knobs for Telescopic Squeeze configuration. Defaults to True since v0.9.0.

Example

>>> apply_lhc_coupling_knob(madx, coupling_knob=5e-4, beam=1)
cpymadtools.lhc._powering.apply_lhc_rigidity_waist_shift_knob(madx: cpymad.madx.Madx, rigidty_waist_shift_value: float = 0, ir: Optional[int] = None, side: str = 'left') None[source]

New in version 0.15.0.

Applies a trim of the LHC rigidity waist shift knob, moving the waist left or right of IP. The waist shift is achieved by moving all four betatron waists simltaneously: unbalancing the triplet powering knobs of the left and right-hand sides of the IP.

Note

If you don’t know what this is, you really should not be using this function.

Warning

Applying the shift will modify your tunes and is likely to flip them, making a subsequent matching impossible if your lattice has coupling. To avoid this, one should match to tunes split further apart before applying the waist shift knob, and then match to the desired working point. For instance for the LHC, matching to (62.27, 60.36) before applying and afterwards rematching to (62.31, 60.32) usually works well.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • rigidty_waist_shift_value (float) -- Units of the rigidity waist shift knob (positive values only).

  • ir (int) -- The Interaction Region to apply the knob to, should be one of [1, 2, 5, 8]. Classically 1 or 5.

  • side (str) -- Which side of the IP to move the waist to, determines a sign in the calculation. Defaults to left, which means \(s_{\mathrm{waist}} \lt s_{\mathrm{ip}}\) (and setting it to right would move the waist such that \(s_{\mathrm{waist}} \gt s_{\mathrm{ip}}\)).

Example

>>> # It is recommended to re-match tunes after this routine
>>> matching.match_tunes(madx, "lhc", "lhcb1", 62.27, 60.36)
>>> apply_lhc_rigidity_waist_shift_knob(madx, rigidty_waist_shift_value=1.5, ir=5)
>>> matching.match_tunes(madx, "lhc", "lhcb1", 62.31, 60.32)
cpymadtools.lhc._powering.carry_colinearity_knob_over(madx: cpymad.madx.Madx, ir: int, to_left: bool = True) None[source]

New in version 0.20.0.

Removes the powering setting on one side of the colinearty knob and applies it to the other side.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • ir (int) -- The Interaction Region around which to apply the change, should be one of [1, 2, 5, 8].

  • to_left (bool) -- If True, the magnet right of IP is de-powered of and its powering is transferred to the magnet left of IP. If False, then the opposite happens. Defaults to True.

Example

>>> carry_colinearity_knob_over(madx, ir=5, to_left=True)
cpymadtools.lhc._powering.deactivate_lhc_arc_sextupoles(madx: cpymad.madx.Madx, beam: int) None[source]

New in version 0.15.0.

Deactivates all arc sextupoles in the (HL)LHC.

Parameters

Example

>>> deactivate_lhc_arc_sextupoles(madx, beam=1)
cpymadtools.lhc._powering.power_landau_octupoles(madx: cpymad.madx.Madx, beam: int, mo_current: float, defective_arc: bool = False) None[source]

New in version 0.15.0.

Powers the Landau octupoles in the (HL)LHC.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • beam (int) -- beam to use.

  • mo_current (float) -- MO powering, in [A].

  • defective_arc -- If set to True, the KOD in Arc 56 are powered for less Imax.

Example

>>> power_landau_octupoles(madx, beam=1, mo_current=350, defect_arc=True)
cpymadtools.lhc._powering.switch_magnetic_errors(madx: cpymad.madx.Madx, **kwargs) None[source]

New in version 0.7.0.

Applies magnetic field orders. This will only work for LHC and HLLHC machines. Initial implementation credits go to Joschua Dilly.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • **kwargs -- The setting works through keyword arguments, and several specific kwargs are expected. default sets global default to this value (defaults to False). AB# sets the default for all of that order, the order being the # number. A# or B# sets the default for systematic and random of this id. A#s, B#r, etc. sets the specific value for this given order. In all kwargs, the order # should be in the range [1…15], where 1 == dipolar field.

Examples

Set random values for (alsmost) all of these orders:

>>> random_kwargs = {}
>>> for order in range(1, 16):
...     for ab in "AB":
...         random_kwargs[f"{ab}{order:d}"] = random.randint(0, 20)
>>> switch_magnetic_errors(madx, **random_kwargs)

Set a given value for B6 order magnetic errors:

>>> switch_magnetic_errors(madx, "B6"=1e-4)
cpymadtools.lhc._powering.vary_independent_ir_quadrupoles(madx: cpymad.madx.Madx, quad_numbers: Sequence[int], ip: int, sides: Sequence[str] = ('r', 'l'), beam: int = 1) None[source]

New in version 0.15.0.

Sends the VARY commands for the desired quadrupoles in the IR surrounding the provided ip. The independent quadrupoles for which this is implemented are Q4 to Q13 included. This is useful to setup some specific matching involving these elements.

Important

It is necessary to have defined a brho variable when creating your beams. If one has used make_lhc_beams to create the beams, this has already been done automatically.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • quad_numbers (Sequence[int]) -- quadrupoles to be varied, by number (aka position from IP).

  • ip (int) -- the IP around which to apply the instructions.

  • sides (Sequence[str]) -- the sides of IP to act on. Should be R for right and L for left, accepts these letters case-insensitively. Defaults to both sides of the IP.

  • beam (int) -- the beam for which to apply the instructions. Defaults to 1.

Example

>>> vary_independent_ir_quadrupoles(
...     madx, quad_numbers=[10, 11, 12, 13], ip=1, sides=("r", "l")
... )

Querying Utilities

The functions below are settings query utilities for the LHC.

cpymadtools.lhc._queries.get_current_orbit_setup(madx: cpymad.madx.Madx) Dict[str, float][source]

New in version 0.8.0.

Get the current values for the (HL)LHC orbit variables. Initial implementation credits go to Joschua Dilly.

Parameters

madx (cpymad.madx.Madx) -- an instanciated Madx object.

Returns

A dict of all orbit variables set, and their values as set in the MAD-X globals.

Example

>>> orbit_setup = get_current_orbit_setup(madx)
cpymadtools.lhc._queries.get_magnets_powering(madx: cpymad.madx.Madx, patterns: Sequence[str] = ['^mb\\.', '^mq\\.', '^ms\\.'], brho: Optional[Union[str, float]] = None, **kwargs) tfs.frame.TfsDataFrame[source]

New in version 0.17.0.

Gets the twiss table with additional defined columns for the given patterns.

Note

Here are below certain useful patterns for the LHC and their meaning:

  • ^mb\. \(\rightarrow\) main bends.

  • ^mq\. \(\rightarrow\) main quadrupoles.

  • ^ms\. \(\rightarrow\) main sextupoles.

  • ^mb[rswx] \(\rightarrow\) separation dipoles.

  • ^mq[mwxy] \(\rightarrow\) insertion quads.

  • ^mqt.1[23] \(\rightarrow\) short tuning quads (12 & 13).

  • ^mqtl \(\rightarrow\) long tuning quads.

  • ^mcbx \(\rightarrow\) crossing scheme magnets.

  • ^mcb[cy] \(\rightarrow\) crossing scheme magnets.

To make no selection, one can give patterns=[""] and this will give back the results for all elements. One can also give a specific magnet’s exact name to include it in the results.

Note

The TWISS flag will be fully cleared after running this function.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • patterns (Sequence[str]) -- a list of regex patterns to define which elements should be selected and included in the returned table. Defaults to selecting the main bends, quads and sextupoles. See the note admonition above for useful patterns to select specific LHC magnet families.

  • brho (Union[str, float]) -- optional, an explicit definition for the magnetic rigidity in \(Tm^{-1}\). If not given, it will be assumed that a brho quantity is defined in the MAD-X globals.

  • **kwargs -- any keyword argument will be passed to get_pattern_twiss and later on to the TWISS command executed in MAD-X.

Returns

A TfsDataFrame of the TWISS table, with the relevant newly defined columns and including the elements matching the regex patterns that were provided.

Example

>>> sextupoles_powering = get_magnets_powering(madx, patterns=[r"^ms\."])
cpymadtools.lhc._queries.query_arc_correctors_powering(madx: cpymad.madx.Madx) Dict[str, float][source]

New in version 0.15.0.

Queries for the arc corrector strengths and returns their values as a percentage of their max powering. This is a port of one of the corr_value.madx file’s macros

Parameters

madx (cpymad.madx.Madx) -- an instanciated Madx object with an active (HL)LHC sequence.

Returns

A dict with the percentage for each corrector.

Example

>>> arc_knobs = query_arc_correctors_powering(madx)
cpymadtools.lhc._queries.query_triplet_correctors_powering(madx: cpymad.madx.Madx) Dict[str, float][source]

New in version 0.15.0.

Queries for the triplet corrector strengths and returns their values as a percentage of their max powering. This is a port of one of the corr_value.madx file’s macros.

Parameters

madx (cpymad.madx.Madx) -- an instanciated Madx object with an active (HL)LHC sequence.

Returns

A dict with the percentage for each corrector.

Example

>>> triplet_knobs = query_triplet_correctors_powering(madx)
cpymadtools.lhc._routines.correct_lhc_global_coupling(madx: cpymad.madx.Madx, beam: int = 1, telescopic_squeeze: bool = True, calls: int = 100, tolerance: float = 1e-21) None[source]

New in version 0.20.0.

A littly tricky matching routine to perform a decent global coupling correction using the LHC coupling knobs.

Important

This routine makes use of some matching tricks and uses the SUMM table’s dqmin variable for the matching. It should be considered a helpful little trick, but it is not a perfect solution.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • beam (int) -- which beam you want to perform the matching for, should be 1 or 2. Defaults to 1.

  • telescopic_squeeze (bool) -- If set to True, uses the coupling knobs for Telescopic Squeeze configuration. Defaults to True.

  • calls (int) -- max number of varying calls to perform when matching. Defaults to 100.

  • tolerance (float) -- tolerance for successfull matching. Defaults to \(10^{-21}\).

Example

>>> correct_lhc_global_coupling(madx, sequence="lhcb1", telescopic_squeeze=True)
cpymadtools.lhc._routines.correct_lhc_orbit(madx: cpymad.madx.Madx, sequence: str, orbit_tolerance: float = 1e-14, iterations: int = 3, mode: str = 'micado', **kwargs) None[source]

New in version 0.9.0.

Routine for orbit correction using MCB.* elements in the LHC. This uses the CORRECT command in MAD-X behind the scenes, refer to the MAD-X manual for usage information.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • sequence (str) -- which sequence to use the routine on.

  • orbit_tolerance (float) -- the tolerance for the correction. Defaults to 1e-14.

  • iterations (int) -- the number of iterations of the correction to perform. Defaults to 3.

  • mode (str) -- the method to use for the correction. Defaults to micado as in the CORRECT command.

  • **kwargs -- Any keyword argument that can be given to the MAD-X CORRECT command, such as mode, ncorr, etc.

Example

>>> correct_lhc_orbit(madx, sequence="lhcb1", plane="y")
cpymadtools.lhc._routines.do_kmodulation(madx: cpymad.madx.Madx, ir: int = 1, side: str = 'right', steps: int = 100, stepsize: float = 3e-08, **kwargs) tfs.frame.TfsDataFrame[source]

New in version 0.20.0.

Simulates a K-Modulation measurement by varying the powering of Q1 left or right of the IP, and returning the tune variations resulting from this modulation.

Note

At the end of the simulation, the powering of the quadrupole is reset to the value it had at the time of function call.

Tip

From these, one can then calculate the \(\beta\)-functions at the Q1 and then at the IP, plus the possible waist shift, according to Carlier and Tomás [CT17].

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • ir (int) -- the IR in which to perform the modulation. Defaults to 1.

  • side (str) -- which side of the IP to use the Q1 to perform the modulation. Should be either right or left, case-insensitive. Defaults to right.

  • steps (int) -- the number of steps to perform in the modulations, aka the number of “measurements”. Defaults to 100.

  • stepsize (float) -- the increment in powering for Q1, in direct values of the powering variable used in MAD-X. Defaults to 3e-8.

  • **kwargs -- Any additional keyword arguments to pass to down to the MAD-X TWISS command, such as chrom, ripken or centre.

Returns

A TfsDataFrame containing the tune values at each powering step.

Example

>>> tune_results = do_kmodulation(madx, ir=1, side="right", steps=100, stepsize=3e-8)

Setup Utilities

The functions below are setup utilities for the LHC, to easily get simulations ready.

class cpymadtools.lhc._setup.LHCSetup(run: int = 3, opticsfile: Optional[str] = None, beam: int = 1, use_b4: bool = False, energy: float = 6800, slicefactor: Optional[int] = None, **kwargs)[source]

New in version 1.0.0.

This is a context manager to prepare an LHC Run 2 or Run 3 setup: calling sequences and opticsfile, re-cycling as is done in the OMC model creator, making beams, potentially slicing, etc. For details on the achieved setups, look at the prepare_lhc_run2 or prepare_lhc_run3 functions.

Important

For the Run 3 setup, it is assumed that the acc-models-lhc repo is available in the root space.

Note

Matching is not performed by this setup and should be taken care of by the user, but the working point should be set by the definitions in the opticsfile.

Note

If you intend to do tracking for beam 2, remember that the lhcb4 sequence needs to be called. This is handled by giving the use_b4 argument as True to the constructor.

Parameters
  • run (int) -- which run to set up for, should be 2 or 3. Defaults to run 3.

  • opticsfile (str) -- name of the opticsfile to be used. For a Run 2 setup, should be the string path to the file. For a Run 3 setup, can be the string path to the file or only the opticsfile name itself, which would be looked for at the acc-models-lhc/operation/optics/ path. Defaults to None, which will raise an error.

  • beam (int) -- which beam to set up for. Defaults to beam 1.

  • use_b4 (bool) -- if True, the lhcb4 sequence file will be used. This is the beam 2 sequence but for tracking purposes. Defaults to False.

  • energy (float) -- beam energy to set up for, in GeV. Defaults to 6800, to match the default of run 3.

  • slicefactor (int) -- if provided, the sequence will be sliced and “made thin”. Defaults to None, which leads to an unsliced sequence.

  • **kwargs -- if echo or warn are found in the keyword arguments they will be transmitted as options to MAD-X. Any other keyword argument is transmitted to the Madx creation call.

Returns

An instanciated context manager Madx object with the required configuration.

Raises

Examples

Get a Run 2 setup for beam 2:

>>> with LHCSetup(run=2, opticsfile="2018/PROTON/opticsfile.22", beam=2) as madx:
...    # do some stuff

Get a Run 3 setup for beam 1, with a sliced sequence and muted output:

>>> with LHCSetup(run=3, opticsfile="R2022a_A30cmC30cmA10mL200cm.madx", slicefactor=4, stdout=False) as madx:
...    # do some stuff
cpymadtools.lhc._setup.lhc_orbit_variables() Tuple[List[str], Dict[str, str]][source]

New in version 0.8.0.

Get the variable names used for orbit setup in the (HL)LHC. Initial implementation credits go to Joschua Dilly.

Returns

A tuple with a list of all orbit variables, and a dict of additional variables, that in the default configurations have the same value as another variable.

Example

>>> variables, specials = lhc_orbit_variables()
cpymadtools.lhc._setup.make_lhc_beams(madx: cpymad.madx.Madx, energy: float = 7000, emittance_x: float = 3.75e-06, emittance_y: float = 3.75e-06, b4: bool = False, **kwargs) None[source]

New in version 0.15.0.

Defines beams with default configuratons for LHCB1 and LHCB2 sequences.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • energy (float) -- beam energy, in [GeV]. Defaults to 6500.

  • emittance_x (float) -- horizontal emittance in [m]. Will be used to calculate geometric emittance which is then fed to the BEAM command.

  • emittance_y (float) -- vertical emittance in [m]. Will be used to calculate geometric emittance which is then fed to the BEAM command.

  • b4 (bool) -- if True, will consider one is using lhb4 to do tracking on beam 2, and will properly set the bv flag to 1. Defaults to False.

  • **kwargs -- Any keyword argument that can be given to the MAD-X BEAM command.

Examples

>>> make_lhc_beams(madx, energy=6800, emittance_x=2.5e-6, emittance_y=3e-6)

Setting up in a way compatible for tracking of beam 2 (needs to call lhcb4 and set bv to 1):

>>> make_lhc_beams(madx, energy=6800, emittance_x=2.5e-6, emittance_y=3e-6, b4=True)
cpymadtools.lhc._setup.make_lhc_thin(madx: cpymad.madx.Madx, sequence: str, slicefactor: int = 1, **kwargs) None[source]

New in version 0.15.0.

Executes the MAKETHIN command for the LHC sequence as previously done in MAD-X macros. This will use the teapot style and will enforce makedipedge.

One can find an exemple use of this function in the AC Dipole Tracking and Free Tracking example galleries.

Parameters
  • madx (cpymad.madx.Madx) -- an instantiated Madx object.

  • sequence (str) -- the sequence to use for the MAKETHIN command.

  • slicefactor (int) -- the slice factor to apply in MAKETHIN, which is a factor applied to default values for different elements, as did the old macro. Defaults to 1.

  • **kwargs -- any keyword argument will be transmitted to the MAD-X MAKETHN command, namely style (will default to teapot) and the makedipedge flag (will default to True).

Example

>>> make_lhc_thin(madx, sequence="lhcb1", slicefactor=4)
cpymadtools.lhc._setup.prepare_lhc_run2(opticsfile: str, beam: int = 1, use_b4: bool = False, energy: float = 6500, slicefactor: Optional[int] = None, **kwargs) cpymad.madx.Madx[source]

New in version 1.0.0.

Returns a prepared default LHC setup for the given opticsfile, for a Run 2 setup. Both beams are made with a default Run 2 configuration, and the lhcb sequence for the given beam is re-cycled from MSIA.EXIT.B{beam} as in the OMC model_creator, and then USE-d. Specific variable settings can be given as keyword arguments.

Important

As this is a Run 2 setup, it is assumed that files are organised in the typical setup as found on AFS. The sequence file will be looked for as a relative location from the optics file: it is assumed that next to the sequence file is a PROTON or ION folder with the opticsfiles.

Note

Matching is not performed by this function and should be taken care of by the user, but the working point should be set by the definitions in the opticsfile. Beware that passing specific variables as keyword arguments might change that working point.

Parameters
  • opticsfile (str) -- name of the optics file to be used. Can be the string path to the file or only the opticsfile name itself, which would be looked for at the acc-models-lhc/operation/optics/ path.

  • beam (int) -- which beam to set up for. Defaults to beam 1.

  • use_b4 (bool) -- if True, the lhcb4 sequence file will be used. This is the beam 2 sequence but for tracking purposes. Defaults to False.

  • energy (float) -- beam energy to set up for, in GeV. Defaults to 6500.

  • slicefactor (int) -- if provided, the sequence will be sliced and made thin. Defaults to None, which leads to an unsliced sequence.

  • **kwargs -- if echo or warn are found in the keyword arguments they will be transmitted as options to MAD-X (by default they are given as False). Any other keyword argument is transmitted to the Madx creation call.

Returns

An instanciated Madx object with the required configuration.

Example

>>> madx = prepare_lhc_run2(
...     "/afs/cern.ch/eng/lhc/optics/runII/2018/PROTON/opticsfile.22", beam=2, stdout=True
... )
cpymadtools.lhc._setup.prepare_lhc_run3(opticsfile: str, beam: int = 1, use_b4: bool = False, energy: float = 6800, slicefactor: Optional[int] = None, **kwargs) cpymad.madx.Madx[source]

New in version 1.0.0.

Returns a prepared default LHC setup for the given opticsfile, for a Run 3 setup. Both beams are made with a default Run 3 configuration, and the provided sequence is re-cycled from MSIA.EXIT.[B12] as in the OMC model_creator, then USE-d. Specific variable settings can be given as keyword arguments.

Important

As this is a Run 3 setup, it is assumed that the acc-models-lhc repo is available in the root space,``. which is needed by the different files in acc-models-lhc.

Note

Matching is not performed by this function and should be taken care of by the user, but the working point should be set by the variable definitions in the opticsfile.

Parameters
  • opticsfile (str) -- name of the optics file to be used. Can be the string path to the file or only the opticsfile name itself, which would be looked for at the acc-models-lhc/operation/optics/ path.

  • beam (int) -- which beam to set up for. Defaults to beam 1.

  • use_b4 (bool) -- if True, the lhcb4 sequence file will be used. This is the beam 2 sequence but for tracking purposes. Defaults to False.

  • energy (float) -- beam energy to set up for, in GeV. Defaults to 6800.

  • slicefactor (int) -- if provided, the sequence will be sliced and made thin. Defaults to None, which leads to an unsliced sequence.

  • **kwargs -- if echo or warn are found in the keyword arguments they will be transmitted as options to MAD-X. Any other keyword argument is transmitted to the Madx creation call.

Returns

An instanciated Madx object with the required configuration.

Example

>>> madx = prepare_lhc_run3(
...     "R2022a_A30cmC30cmA10mL200cm.madx", slicefactor=4, stdout=True
... )
cpymadtools.lhc._setup.re_cycle_sequence(madx: cpymad.madx.Madx, sequence: str = 'lhcb1', start: str = 'IP3') None[source]

New in version 0.15.0.

Re-cycles the provided sequence from a different starting point, given as start.

One can find an exemple use of this function in the AC Dipole Tracking and Free Tracking example galleries.

Parameters
  • madx (cpymad.madx.Madx) -- an instantiated Madx object.

  • sequence (str) -- the sequence to re-cycle.

  • start (str) -- element to start the new cycle from.

Example

>>> re_cycle_sequence(madx, sequence="lhcb1", start="MSIA.EXIT.B1")
cpymadtools.lhc._setup.setup_lhc_orbit(madx: cpymad.madx.Madx, scheme: str = 'flat', **kwargs) Dict[str, float][source]

New in version 0.8.0.

Automated orbit setup for (HL)LHC runs, for some default schemes. It is assumed that at least sequence and optics files have been called. Initial implementation credits go to Joschua Dilly.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • scheme (str) -- the default scheme to apply, as defined in the LHC_CROSSING_SCHEMES constant. Accepted values are keys of LHC_CROSSING_SCHEMES. Defaults to flat (every orbit variable to 0).

  • **kwargs -- Any standard crossing scheme variables (on_x1, phi_IR1, etc). Values given here override the values in the default scheme configurations.

Returns

A dict of all orbit variables set, and their values as set in the MAD-X globals.

Example

>>> orbit_setup = setup_lhc_orbit(madx, scheme="lhc_top")

Twiss Utilities

The functions below are twiss utilities for the LHC insertion regions.

cpymadtools.lhc._twiss.get_ips_twiss(madx: cpymad.madx.Madx, columns: Sequence[str] = ['name', 's', 'x', 'y', 'l', 'px', 'py', 'betx', 'bety', 'alfx', 'alfy', 'dx', 'dy', 'mux', 'muy', 'r11', 'r12', 'r21', 'r22', 'beta11', 'beta12', 'beta21', 'beta22'], **kwargs) tfs.frame.TfsDataFrame[source]

New in version 0.9.0.

Quickly get the TWISS table for certain variables at IP locations only. The SUMM table will be included as the TfsDataFrame’s header dictionary.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • columns (Sequence[str]) -- the variables to be returned, as columns in the DataFrame.

  • **kwargs -- Any keyword argument that can be given to the MAD-X TWISS command, such as chrom, ripken, centre; or starting coordinates with betx, bety etc.

Returns

A TfsDataFrame of the TWISS table’s sub-selection.

Example

>>> ips_df = get_ips_twiss(madx, chrom=True, ripken=True)
cpymadtools.lhc._twiss.get_ir_twiss(madx: cpymad.madx.Madx, ir: int, columns: Sequence[str] = ['name', 's', 'x', 'y', 'l', 'px', 'py', 'betx', 'bety', 'alfx', 'alfy', 'dx', 'dy', 'mux', 'muy', 'r11', 'r12', 'r21', 'r22', 'beta11', 'beta12', 'beta21', 'beta22'], **kwargs) tfs.frame.TfsDataFrame[source]

New in version 0.9.0.

Quickly get the TWISS table for certain variables for one Interaction Region, meaning at the IP and Q1 to Q3 both left and right of the IP. The SUMM table will be included as the TfsDataFrame’s header dictionary.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • ir (int) -- which interaction region to get the TWISS for.

  • columns (Sequence[str]) -- the variables to be returned, as columns in the DataFrame.

  • **kwargs -- Any keyword argument that can be given to the MAD-X TWISS command, such as chrom, ripken, centre; or starting coordinates with betx, bety etc.

Returns

A TfsDataFrame of the TWISS table’s sub-selection.

Example

>>> ir_df = get_ir_twiss(madx, chrom=True, ripken=True)

Matching Routines

Module with functions to perform MAD-X matchings through a Madx object.

cpymadtools.matching.match_chromaticities(madx: cpymad.madx.Madx, accelerator: Optional[str] = None, sequence: Optional[str] = None, dq1_target: Optional[float] = None, dq2_target: Optional[float] = None, varied_knobs: Optional[Sequence[str]] = None, telescopic_squeeze: bool = True, run3: bool = False, step: float = 1e-07, calls: int = 100, tolerance: float = 1e-21)[source]

New in version 0.17.0.

Provided with an active Madx object, will run relevant commands to match chromaticities to the desired target values.

Note

This is a wrapper around the match_tunes_and_chromaticities function. Refer to its documentation for usage details.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • accelerator (Optional[str]) -- name of the accelerator, used to determmine knobs if variables is not given. Automatic determination will only work for LHC and HLLHC. Defaults to None, in which case the knobs must be provided explicitly through varied_knobs.

  • sequence (str) -- name of the sequence you want to perform the matching for. Defaults to None, in which case the currently active sequence will be used for the matching.

  • dq1_target (float) -- horizontal chromaticity to match to. Defaults to None, in which case it will not be a target and will be excluded from the matching.

  • dq2_target (float) -- vertical chromaticity to match to. Defaults to None, in which case it will not be a target and will be excluded from the matching.

  • varied_knobs (Sequence[str]) -- the variables names to VARY in the MAD-X MATCH routine. An example input could be ["kqf", "ksd", "kqf", "kqd"] as they are common names used for quadrupole and sextupole strengths (focusing / defocusing) in most examples.

  • telescopic_squeeze (bool) -- LHC specific. If set to True, uses the (HL)LHC knobs for Telescopic Squeeze configuration. Defaults to True since v0.9.0.

  • run3 (bool) -- if set to True, uses the LHC Run 3 *_op knobs. Defaults to False.

  • step (float) -- step size to use when varying knobs.

  • calls (int) -- max number of varying calls to perform. Defaults to 100.

  • tolerance (float) -- tolerance for successfull matching. Defaults to \(10^{-21}\).

Examples

Matching a dummy lattice (not LHC or HLLHC):

>>> matching.match_chromaticities(
...     madx,
...     None,              # this is not LHC or HLLHC
...     sequence="CAS3",
...     dq1_target=100,
...     dq2_target=100,
...     varied_knobs=["ksf", "ksd"],  # only chroma knobs
... )

Note that since the accelerator and sequence arguments default to None, they can be omitted. In this case the sequence currently in use will be used for the matching, and varied_knobs must be provided.

>>> matching.match_tunes_and_chromaticities(
...     madx,
...     dq1_target=100,
...     dq2_target=100,
...     varied_knobs=["ksf", "ksd"],  # only chroma knobs
... )

Matching the LHC lattice:

>>> matching.match_chromaticities(
...     madx,
...     "lhc",                    # will find the knobs automatically
...     sequence="lhcb1",
...     dq1_target=2.0,
...     dq2_target=2.0,
... )
cpymadtools.matching.match_tunes(madx: cpymad.madx.Madx, accelerator: Optional[str] = None, sequence: Optional[str] = None, q1_target: Optional[float] = None, q2_target: Optional[float] = None, varied_knobs: Optional[Sequence[str]] = None, telescopic_squeeze: bool = True, run3: bool = False, step: float = 1e-07, calls: int = 100, tolerance: float = 1e-21)[source]

New in version 0.17.0.

Provided with an active Madx object, will run relevant commands to match tunes to the desired target values.

Note

This is a wrapper around the match_tunes_and_chromaticities function. Refer to its documentation for usage details.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • accelerator (Optional[str]) -- name of the accelerator, used to determmine knobs if variables is not given. Automatic determination will only work for LHC and HLLHC. Defaults to None, in which case the knobs must be provided explicitly through varied_knobs.

  • sequence (str) -- name of the sequence you want to perform the matching for. Defaults to None, in which case the currently active sequence will be used for the matching.

  • q1_target (float) -- horizontal tune to match to. Defaults to None, in which case it will not be a target and will be excluded from the matching.

  • q2_target (float) -- vertical tune to match to. Defaults to None, in which case it will not be a target and will be excluded from the matching.

  • varied_knobs (Sequence[str]) -- the variables names to VARY in the MAD-X MATCH routine. An example input could be ["kqf", "ksd", "kqf", "kqd"] as they are common names used for quadrupole and sextupole strengths (focusing / defocusing) in most examples.

  • telescopic_squeeze (bool) -- LHC specific. If set to True, uses the (HL)LHC knobs for Telescopic Squeeze configuration. Defaults to True since v0.9.0.

  • run3 (bool) -- if set to True, uses the LHC Run 3 *_op knobs. Defaults to False.

  • step (float) -- step size to use when varying knobs.

  • calls (int) -- max number of varying calls to perform. Defaults to 100.

  • tolerance (float) -- tolerance for successfull matching. Defaults to \(10^{-21}\).

Examples

Matching a dummy lattice (not LHC or HLLHC):

>>> matching.match_tunes(
...     madx,
...     None,              # this is not LHC or HLLHC
...     sequence="CAS3",
...     q1_target=6.335,
...     q2_target=6.29,
...     varied_knobs=["kqf", "kqd"],  # only tune knobs
... )

Note that since the accelerator and sequence arguments default to None, they can be omitted. In this case the sequence currently in use will be used for the matching, and varied_knobs must be provided.

>>> matching.match_tunes_and_chromaticities(
...     madx,
...     q1_target=6.335,
...     q2_target=6.29,
...     varied_knobs=["kqf", "kqd"],  # only tune knobs
... )

Matching the LHC lattice:

>>> matching.match_tunes(
...     madx,
...     "lhc",                    # will find the knobs automatically
...     sequence="lhcb1",
...     q1_target=62.31,
...     q2_target=60.32,
... )
cpymadtools.matching.match_tunes_and_chromaticities(madx: cpymad.madx.Madx, accelerator: Optional[str] = None, sequence: Optional[str] = None, q1_target: Optional[float] = None, q2_target: Optional[float] = None, dq1_target: Optional[float] = None, dq2_target: Optional[float] = None, varied_knobs: Optional[Sequence[str]] = None, telescopic_squeeze: bool = True, run3: bool = False, step: float = 1e-07, calls: int = 100, tolerance: float = 1e-21) None[source]

New in version 0.8.0.

Provided with an active Madx object, will run relevant commands to match tunes and/or chromaticities. As target values are given, the function expects knob names to be provided, which are then used and varied by MAD-X to match the targets. This is a convenient wrapper around the MATCH command. For usage details, see the MAD-X manual.

One can find example use of this function in the lattice plotting, rigid waist shift or phase space example galleries.

Important

If target tune values only are provided, then tune matching is performed with the provided knobs. If target chromaticity values only are provided, then chromaticity matching is performed with the provided knobs. If targets for both types are provided, then both are matched in a single call with the provided knobs.

Note

If the user wishes to perform different matching calls for each, then it is recommended to call this function as many times as necessary, with the appropriate targets.

For instance, in some cases and machines some prefer to do a tune matching followed by a chromaticity matching, then followed by a combined matching. In this case the function should be called three times, once with tune targets and knobs, another time with chromaticity targets and knobs, then a final time with all of the above. For this, simple wrappers are provided: the match_tunes() and match_chromaticities() functions.

Hint

When acting of either the LHC or HLLHC machines, the accelerator name can be provided and the vary knobs will be automatically set accordingly to the provided targets. Note that only the relevant knobs are set, so if tune targets only are provided, then tune knobs only will be used, and not chromaticity knobs. If explicit knobs are provided, these will always be used. On other machines the knobs should be provided explicitly, always.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • accelerator (Optional[str]) -- name of the accelerator, used to determmine knobs if variables is not given. Automatic determination will only work for LHC and HLLHC. Defaults to None, in which case the knobs must be provided explicitly through varied_knobs.

  • sequence (str) -- name of the sequence you want to perform the matching for. Defaults to None, in which case the currently active sequence will be used for the matching.

  • q1_target (float) -- horizontal tune to match to. Defaults to None, in which case it will not be a target and will be excluded from the matching.

  • q2_target (float) -- vertical tune to match to. Defaults to None, in which case it will not be a target and will be excluded from the matching.

  • dq1_target (float) -- horizontal chromaticity to match to. Defaults to None, in which case it will not be a target and will be excluded from the matching.

  • dq2_target (float) -- vertical chromaticity to match to. Defaults to None, in which case it will not be a target and will be excluded from the matching.

  • varied_knobs (Sequence[str]) -- the variables names to VARY in the MAD-X MATCH routine. An example input could be ["kqf", "ksd", "kqf", "kqd"] as they are common names used for quadrupole and sextupole strengths (focusing / defocusing) in most examples.

  • telescopic_squeeze (bool) -- LHC specific. If set to True, uses the (HL)LHC knobs for Telescopic Squeeze configuration. Defaults to True since v0.9.0.

  • run3 (bool) -- if set to True, uses the LHC Run 3 *_op knobs. Defaults to False.

  • step (float) -- step size to use when varying knobs.

  • calls (int) -- max number of varying calls to perform. Defaults to 100.

  • tolerance (float) -- tolerance for successfull matching. Defaults to \(10^{-21}\).

Examples

Matching a dummy lattice (not LHC or HLLHC):

>>> matching.match_tunes_and_chromaticities(
...     madx,
...     None,              # this is not LHC or HLLHC
...     sequence="CAS3",
...     q1_target=6.335,
...     q2_target=6.29,
...     dq1_target=100,
...     dq2_target=100,
...     varied_knobs=["kqf", "kqd", "ksf", "ksd"],
... )

Note that since the accelerator and sequence arguments default to None, they can be omitted. In this case the sequence currently in use will be used for the matching, and varied_knobs must be provided.

>>> matching.match_tunes_and_chromaticities(
...     madx,
...     q1_target=6.335,
...     q2_target=6.29,
...     dq1_target=100,
...     dq2_target=100,
...     varied_knobs=["kqf", "kqd", "ksf", "ksd"],
... )

Matching the lhcb1 sequence of the LHC lattice:

>>> matching.match_tunes_and_chromaticities(
...     madx,
...     "lhc",                    # will find the knobs automatically
...     sequence="lhcb1",
...     q1_target=62.31,
...     q2_target=60.32,
...     dq1_target=2.0,
...     dq2_target=2.0,
...     run3=True,  # influences the knobs definition
... )

PTC Routines

Module with functions to manipulate MAD-X PTC functionality through a Madx object.

cpymadtools.ptc.get_amplitude_detuning(madx: cpymad.madx.Madx, order: int = 2, file: Optional[Union[pathlib.Path, str]] = None, fringe: bool = False, **kwargs) tfs.frame.TfsDataFrame[source]

New in version 0.7.0.

Calculates amplitude detuning coefficients via PTC_NORMAL, with sensible defaults set for other relevant PTC commands used in the process. The result table is returned as a TfsDataFrame, the headers of which are the contents of the internal SUMM table. This is a heavily refactored version of an initial implementation by Joschua Dilly.

Important

The PTC_CREATE_LAYOUT command is issued with model=3 (SixTrack model), method=4 (integration order), nst=3 (number of integration steps, aka body slices for elements) and exact=True (use exact Hamiltonian, not an approximated one).

The PTC_NORMAL command is explicitely given icase=6 to enforce 6D calculations (see the MAD-X manual for details), no=5 (map order for derivative evaluation of Twiss parameters), closedorbit=True (triggers closed orbit calculation) and normal=True (activate calculation of the Normal Form).

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • order (int) -- maximum derivative order coefficient (only 0, 1 or 2 implemented in PTC). Defaults to 2.

  • file (Union[Path, str]) -- path to output file. Defaults to None.

  • fringe (bool) -- boolean flag to include fringe field effects in the calculation. Defaults to False.

  • **kwargs -- any keyword argument is transmitted to the PTC_NORMAL command. See above which arguments are already set for PTC_NORMAL to avoid trying to override them.

Returns

A TfsDataframe with the calculated coefficients.

Example

>>> ampdet_coeffs = get_amplitude_detuning(madx, order=2, closedorbit=True)
cpymadtools.ptc.get_rdts(madx: cpymad.madx.Madx, order: int = 4, file: Optional[Union[pathlib.Path, str]] = None, fringe: bool = False, **kwargs) tfs.frame.TfsDataFrame[source]

New in version 0.7.0.

Calculate the resonance driving terms up to order via PTC_TWISS, with sensible defaults set for other relevant PTC commands. The result table is returned as a TfsDataFrame, the headers of which are the contents of the internal SUMM table. This is a heavily refactored version of an initial implementation by Joschua Dilly.

Important

The PTC_CREATE_LAYOUT command is issued with model=3 (SixTrack model), method=4 (integration order), nst=3 (number of integration steps, aka body slices for elements) and exact=True (use exact Hamiltonian, not an approximated one).

The PTC_NORMAL command is explicitely given icase=6 to enforce 6D calculations (see the MAD-X manual for details), trackrdts=True (for this function to fullfill its purpose) and normal=True to trigger saving the normal form analysis results in a table called NONLIN which will then be available through the provided Madx instance.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • order (int) -- map order for derivative evaluation of Twiss parameters. Defaults to 4.

  • file (Union[Path, str]) -- path to output file. Default to None.

  • fringe (bool) -- boolean flag to include fringe field effects in the calculation. Defaults to False.

  • **kwargs -- any keyword argument is transmitted to the PTC_TWISS command. See above which arguments are already set for PTC_TWISS to avoid trying to override them.

Returns

A TfsDataframe with the calculated RDTs.

Example

>>> rdts_df = get_rdts(madx, order=3, fringe=True)
cpymadtools.ptc.ptc_track_particle(madx: cpymad.madx.Madx, initial_coordinates: Tuple[float, float, float, float, float, float], nturns: int, sequence: Optional[str] = None, observation_points: Optional[Sequence[str]] = None, onetable: bool = False, fringe: bool = False, **kwargs) Dict[str, pandas.core.frame.DataFrame][source]

New in version 0.12.0.

Tracks a single particle for nturns through PTC_TRACK, based on its initial coordinates. The use of this function is similar to that of track_single_particle.

Important

The PTC_CREATE_LAYOUT command is issued with model=3 (SixTrack model), method=4 (integration order), nst=3 (number of integration steps, aka body slices for elements) and exact=True (use exact Hamiltonian, not an approximated one).

The PTC_TRACK command is explicitely given ELEMENT_BY_ELEMENT=True to force element by element tracking mode.

Warning

If the sequence argument is given a string value, the USE command will be ran on the provided sequence name. This means the caveats of USE apply, for instance the erasing of previously defined errors, orbits corrections etc. In this case a warning will be logged but the function will proceed. If None is given (by default) then the sequence already in use will be the one tracking is performed on.

Parameters
  • madx (cpymad.madx.Madx) -- an instantiated cpymad.madx.Madx object.

  • initial_coordinates (Tuple[float, float, float, float, float, float]) -- a tuple with the X, PX, Y, PY, T, PT starting coordinates of the particle to track. Defaults to all 0 if None given.

  • nturns (int) -- the number of turns to track for.

  • sequence (Optional[str]) -- the sequence to use for tracking. If no value is provided, it is assumed that a sequence is already defined and in use, and this one will be picked up by MAD-X. Beware of the dangers of giving a sequence that will be used by MAD-X, see the warning below for more information.

  • observation_points (Sequence[str]) -- sequence of all element names at which to OBSERVE during the tracking.

  • onetable (bool) -- flag to combine all observation points data into a single table. Defaults to False.

  • fringe (bool) -- boolean flag to include fringe field effects in the calculation. Defaults to False.

  • **kwargs --

    Any keyword argument is transmitted to the PTC_TRACK command such as the CLOSED_ORBIT flag to activate closed orbit calculation before tracking. Refer to the MAD-X manual for options.

Returns

A dict with a copy of the track table’s dataframe for each defined observation point, with as columns the coordinates x, px, y, py, t, pt, s and e (energy). The keys of the dictionary are simply named observation_point_1, observation_point_2 etc. The first observation point always corresponds to the start of machine, the others correspond to the ones manually defined, in the order they are defined in.

If the user has set onetable to True, only one entry is in the dictionary under the key trackone and it has the combined table as a pandas DataFrame for value.

Example

>>> tracks_dict = ptc_track_particle(
...     madx, nturns=1023, initial_coordinates=(2e-4, 0, 1e-4, 0, 0, 0)
... )
cpymadtools.ptc.ptc_twiss(madx: cpymad.madx.Madx, order: int = 4, file: Optional[Union[pathlib.Path, str]] = None, fringe: bool = False, table: str = 'ptc_twiss', **kwargs) tfs.frame.TfsDataFrame[source]

New in version 0.12.0.

Calculates the TWISS parameters according to the Willeke and Ripken [WR89] formalism via PTC_TWISS, with sensible defaults set for other relevant PTC commands. The result table is returned as a TfsDataFrame, the headers of which are the contents of the internal SUMM table.

This is very similar to the get_rdts function as both use PTC_TWISS internally, however this function does not track RDTs which makes the calculations significantly faster.

Important

The PTC_CREATE_LAYOUT command is issued with model=3 (SixTrack model), method=4 (integration order), nst=3 (number of integration steps, aka body slices for elements) and exact=True (use exact Hamiltonian, not an approximated one).

The PTC_TWISS command is explicitely given icase=6 to enforce 6D calculations (see the MAD-X manual for details), normal=True to trigger saving the normal form analysis results in a table called NONLIN which will then be available through the provided Madx instance.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • order (int) -- map order for derivative evaluation of TWISS parameters. Defaults to 4.

  • file (Union[Path, str]) -- path to output file. Default to None.

  • fringe (bool) -- boolean flag to include fringe field effects in the calculation. Defaults to False.

  • table (str) -- the name of the internal table in which to save the results. Defaults to ptc_twiss.

  • **kwargs -- Any keyword argument is transmitted to the PTC_TWISS command. See above which arguments are already set for PTC_TWISS to avoid trying to override them.

Returns

A TfsDataframe with the calculated TWISS parameters.

Example

>>> twiss_ptc_df = ptc_twiss(madx, order=3)

Tracking Routines

Module with functions to manipulate MAD-X TRACK functionality through a Madx object.

cpymadtools.track.track_single_particle(madx: cpymad.madx.Madx, initial_coordinates: Tuple[float, float, float, float, float, float], nturns: int, sequence: Optional[str] = None, observation_points: Optional[Sequence[str]] = None, **kwargs) Dict[str, pandas.core.frame.DataFrame][source]

New in version 0.8.0.

Tracks a single particle for nturns, based on its initial coordinates. For an example of the use of this function, have a look at the phase space or tracking example galleries.

Parameters
  • madx (cpymad.madx.Madx) -- an instantiated Madx object.

  • initial_coordinates (Tuple[float, float, float, float, float, float]) -- a tuple with the X, PX, Y, PY, T, PT starting coordinates of the particle to track. Defaults to all 0 if None given.

  • nturns (int) -- the number of turns to track for.

  • sequence (Optional[str]) -- the sequence to use for tracking. If no value is provided, it is assumed that a sequence is already defined and in use, and this one will be picked up by MAD-X. Beware of the dangers of giving a sequence that will be used by MAD-X, see the warning below for more information.

  • observation_points (Sequence[str]) -- sequence of all element names at which to OBSERVE during the tracking.

  • **kwargs -- Any keyword argument will be given to the TRACK command like it would be given directly into MAD-X, for instance ONETABLE etc. Refer to the MAD-X manual for options.

Warning

If the sequence argument is given a string value, the USE command will be ran on the provided sequence name. This means the caveats of USE apply, for instance the erasing of previously defined errors, orbits corrections etc. In this case a warning will be logged but the function will proceed. If None is given (by default) then the sequence already in use will be the one tracking is performed on.

Returns

A dict with a copy of the track table’s dataframe for each defined observation point, with as columns the coordinates x, px, y, py, t, pt, s and e (energy). The keys of the dictionary are simply named observation_point_1, observation_point_2 etc. The first observation point always corresponds to the start of machine, the others correspond to the ones manually defined, in the order they are defined in.

If the user has set onetable to True, only one entry is in the dictionary under the key trackone and it has the combined table as a pandas DataFrame for value.

Example

>>> tracks_dict = track_single_particle(
...     madx, nturns=1023, initial_coordinates=(2e-4, 0, 1e-4, 0, 0, 0)
... )

Tune Utilities

Module with functions to manipulate MAD-X functionality around the tune through a Madx object.

cpymadtools.tune.get_footprint_lines(dynap_dframe: tfs.frame.TfsDataFrame) Tuple[numpy.ndarray, numpy.ndarray][source]

New in version 0.12.0.

Provided with the TfsDataFrame returned by make_footprint_table, determines the various (Qx, Qy) points needed to plot the footprint data with lines representing the different amplitudes and angles from starting particles, and returns these in immediately plottable numpy.ndarray objects.

Warning

This function is some dark magic stuff I have taken out of very dusty drawers, and I cannot explain exactly how it works. I also do not know who wrote this initially. Results are not guaranteed to be correct and should be checked with a quick plot.

Parameters

dynap_dframe (tfs.frame.TfsDataFrame) -- the dynap data frame returned by make_footprint_table.

Returns

The Qx and Qy data points to plot directly, both as ndarray objects.

Example

>>> dynap_tfs = make_footprint_table(madx)
>>> qxs, qys = get_footprint_lines(dynap_tfs)
>>> plt.plot(qxs, qys, "o--", label="Tune Footprint from DYNAP Table")
cpymadtools.tune.get_footprint_patches(dynap_dframe: tfs.frame.TfsDataFrame) matplotlib.collections.PatchCollection[source]

New in version 0.12.0.

Provided with the TfsDataFrame returned by make_footprint_table, computes the polygon patches needed to plot the footprint data, with lines representing the different amplitudes and angles from starting particles, and returns the PatchCollection with the computed polygons. Initial implementation credits go to Konstantinos Paraschou.

Note

The polygons will have blue edges, except the ones corresponding to the last starting angle particles (in red) and the last starting amplitude particles (in green).

Warning

The internal construction of polygons can be tricky, and you might need to change the ANGLE or AMPLITUDE values in dynap_dframe headers.

Parameters

dynap_dframe (tfs.frame.TfsDataFrame) -- the dynap data frame returned by make_footprint_table.

Returns

The PatchCollection with the created polygons.

Example

>>> fig, axis = plt.subplots()
>>> dynap_tfs = make_footprint_table(madx)
>>> footprint_polygons = get_footprint_patches(dynap_tfs)
>>> axis.add_collection(footprint_polygons)
cpymadtools.tune.make_footprint_table(madx: cpymad.madx.Madx, sigma: float = 5, dense: bool = False, file: Optional[str] = None, cleanup: bool = True, **kwargs) tfs.frame.TfsDataFrame[source]

New in version 0.9.0.

Instantiates an ensemble of particles up to the desired bunch \(\sigma\) amplitude to be tracked for the DYNAP command, letting MAD-X infer their tunes. Particules are instantiated for different angle variables for each amplitude, creating an ensemble able to represent the tune footprint.

Warning

Since the DYNAP command makes use of tracking, your sequence needs to be sliced before calling this function.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • sigma (float) -- the maximum amplitude of the tracked particles, in bunch \(\sigma\). Defaults to 5.

  • dense (bool) -- if set to True, an increased number of particles will be tracked. Defaults to False.

  • file (str) -- If given, the dynaptune table will be exported as a TFS file with the provided name.

  • cleanup (bool) -- If True, the fort.69 and lyapunov.data files are cleared before returning the dynaptune table. Defaults to True.

  • **kwargs -- any keyword argument will be transmitted to the DYNAP command in MAD-X.

Returns

The resulting dynaptune table, as a TfsDataFrame.

Example

>>> dynap_dframe = make_footprint_table(madx)

TWISS Routines

Module with functions to manipulate MAD-X TWISS functionality through a Madx object.

cpymadtools.twiss.get_pattern_twiss(madx: cpymad.madx.Madx, columns: Optional[Sequence[str]] = None, patterns: Sequence[str] = [''], **kwargs) tfs.frame.TfsDataFrame[source]

New in version 0.8.0.

Extracts the TWISS table for desired variables from the provided Madx object, and for certain elements matching the provided patterns. The table is returned as a TfsDataFrame. Additionally, the SUMM table is also returned as the headers of the returned DataFrame.

Note

The TWISS flag will be fully cleared after running this function.

Warning

Although the patterns parameter should accept a regex, MAD-X does not implement actual regexes. Please refer to the MAD-X manual, section Regular Expressions for details on what is implemented in MAD-X itself.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • columns (Sequence[str]) -- the variables to be returned, as columns in the TfsDataFrame. Defaults to None, which will return all available columns.

  • patterns (Sequence[str]) -- the different element patterns (such as MQX or BPM) to be applied to the TWISS command, which will determine the rows in the returned TfsDataFrame. Defaults to [""] which will select all elements.

  • **kwargs -- Any keyword argument that can be given to the MAD-X TWISS command, such as chrom, ripken, centre; or starting coordinates with betx, bety etc.

Returns

A TfsDataFrame with the selected columns for all elements matching the provided patterns, and the internal SUMM table as header dict.

Examples

To get LHC IP points:

>>> ips_df = get_pattern_twiss(madx=madx, patterns=["IP"])

To get (HL)LHC IR1 triplets:

>>> triplets_df = get_pattern_twiss(
...     madx=madx,
...     patterns=[
...         r"MQXA.[12345][RL]1",  # Q1 and Q3 LHC
...         r"MQXB.[AB][12345][RL]1",  # Q2A and Q2B LHC
...         r"MQXF[AB].[AB][12345][RL]1",  # Q1 to Q3 A and B HL-LHC
...     ],
... )
cpymadtools.twiss.get_twiss_tfs(madx: cpymad.madx.Madx, **kwargs) tfs.frame.TfsDataFrame[source]

New in version 0.8.3.

Returns a TfsDataFrame from the Madx instance’s TWISS table, typically in the way we’re used to getting it from MAD-X outputting the TWISS (uppercase names, colnames, SUMM table in headers). This will call the TWISS command first before returning the dframe to you.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • **kwargs -- Any keyword argument that can be given to the MAD-X TWISS command, such as chrom, ripken, centre; or starting coordinates with betx, bety etc. Keyword Args:

Returns

A TfsDataFrame of the TWISS table.

Example

>>> twiss_df = get_twiss_tfs(madx, chrom=True, ripken=True)

Miscellaneous Utilities

Module with utility functions to do mundane operations with Madx objects.

cpymadtools.utils.export_madx_table(madx: cpymad.madx.Madx, table_name: str, file_name: Union[pathlib.Path, str], pattern: Optional[str] = None, headers_table: str = 'SUMM', **kwargs) None[source]

New in version 0.17.0.

Exports an internal table from the MAD-X process into a TfsDataFrame on disk.

Important

Tables can only be correctly read back in MAD-X (through READTABLE) if the written file has a NAME and a TYPE entries in its headers.

If these entries are not provided (see below for their usage), then they will be given default values so the TFS file can be read by MAD-X.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • table_name (str) -- the name of the internal table to retrieve.

  • file_name (str) -- the name of the file to export to.

  • pattern (str) -- if given, will be used as a regular expression to filter the extracted table, by passing it as the regex parameter of pandas.DataFrame.filter.

  • headers_table (str) -- the name of the internal table to use for headers. Defaults to SUMM.

  • **kwargs -- any keyword arguments will be passed to write_tfs.

Example

>>> madx.command.twiss()
>>> export_madx_table(madx, table_name="TWISS", file_name="twiss.tfs")
cpymadtools.utils.get_table_tfs(madx: cpymad.madx.Madx, table_name: str, headers_table: str = 'SUMM') tfs.frame.TfsDataFrame[source]

New in version 0.11.0.

Turns an internal table from the MAD-X process into a TfsDataFrame.

Parameters
  • madx (cpymad.madx.Madx) -- an instanciated Madx object.

  • table_name (str) -- the name of the internal table to retrieve.

  • headers_table (str) -- the name of the internal table to use for headers. Defaults to SUMM.

Returns

A TfsDataFrame object with the table_name data, and the desired headers_table (usually SUMM) as headers.

Examples

>>> twiss_tfs = get_table_tfs(madx, table_name="TWISS")