Cpymadtools

The cpymadtools subpackage 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.

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

Added 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.

Parameters:
  • madx (cpymad.madx.Madx) -- An instanciated Madx object. Positional only.

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

  • sequence (str, optional) -- Name of the sequence to activate for the tune matching.

  • varied_knobs (Sequence[str], optional) -- 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], optional) -- 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. Defaults to 1e-7.

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

  • tolerance (float) -- Tolerance for successfull matching. Defaults to 1e-21.

Returns:

float -- 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)
)
# returns 0.001
pyhdtoolkit.cpymadtools.coupling.get_cminus_from_coupling_rdts(madx: Madx, /, patterns: Sequence[str] = [''], method: str = 'teapot', qx: float | None = None, qy: float | None = None, filtering: float = 0) float[source]

Added in version 0.20.0.

Computes and returns the \(|C^{-}|\) from the machine’s coupling RDTs. The cminus 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, empirically 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, the returned value will be a real number.

Parameters:
  • madx (cpymad.madx.Madx) -- An instanciated Madx object. Positional only.

  • 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, optional) -- The horizontal tune. If this parameters is not provided then the value will be taken from the SUMM table.

  • qy (float, optional) -- The vertical tune. If this parameters is not provided then the value will be taken from the SUMM table.

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

Returns:

float -- 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]$"])
pyhdtoolkit.cpymadtools.coupling.get_coupling_rdts(madx: Madx, /, **kwargs) TfsDataFrame[source]

Added in version 0.20.0.

Computed the coupling Resonance Driving Terms (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. Positional only.

  • **kwargs -- All keyword arguments are passed to the TWISS command in MAD-X.

Returns:

TfsDataFrame -- 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)
pyhdtoolkit.cpymadtools.coupling.match_no_coupling_through_ripkens(madx: Madx, /, sequence: str | None = None, location: str | None = None, vary_knobs: Sequence[str] | None = None) None[source]

Added 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. Positional only.

  • sequence (str, optional) -- Name of the sequence to activate for the matching. If not provided the currently active sequence will be used.

  • location (str, optional) -- The name of the element at which to match the cross-term Ripkens to be 0. If not provided, the start of the sequence will be used. Please refer to the Table Access Functions section in the MAD-X documentation for more information on the location string format.

  • vary_knobs (Sequence[str], optional) -- 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 the LHC and HLLHC machines.

Important

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

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

Coupling Utilities

The functions below are betatron coupling utilities for the LHC.

pyhdtoolkit.cpymadtools.lhc._coupling.get_lhc_bpms_twiss_and_rdts(madx: Madx, /) TfsDataFrame[source]

Added 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 a call to optics_functions.coupling.coupling_via_cmatrix.

Parameters:

madx (cpymad.madx.Madx) -- An instanciated Madx object. Positional only.

Returns:

TfsDataFrame -- A TfsDataFrame of the TWISS table with basic default columns, as well as one new complex-valued column for each of the coupling RDTs.

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 in MAD-X.

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

Added in version 1.0.0.

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

Warning

It is most likely needed 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 called for the changes to apply. This means the caveats of USE apply, for instance the erasing of previously defined errors, orbits corrections etc.

Therefore, it is recommended to install the errors and save them with the ESAVE or ETABLE command, call this function, then re-implement the errors with the SETERR command.

Parameters:
  • madx (cpymad.madx.Madx) -- An instanciated Madx object. Positional only.

  • 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
)
pyhdtoolkit.cpymadtools.lhc._elements.install_ac_dipole_as_kicker(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]

Added in version 0.15.0.

Installs an AC dipole as a kicker element in (HL)LHC beam 1 or 2, for tracking. This function makes the assumption that the lhcb1 / lhcb2 sequence is already defined, sliced, with an associated beam (BEAM command or make_lhc_beams function), is matched to the desired working point and a TWISS call has been made.

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.

Note

The sequence should be sliced before calling this function, as the AC Dipole is installed at the location of MKQA.6L4.B[12]. This is a minor inconvenience as the sequence should be sliced in order to perform tracking anyway.

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

Warning

Installing the AC Dipole modifies the sequence, and the USE command will be called again at the end of this function. This will remove any errors that were installed in the sequence.

As the errors impact the optics functions which are used during the installation of the AC Dipole, it would not be correct to implement them only after installing the element.

Therefore, it is recommended to install the errors and save them with the ESAVE or ETABLE command, call this function, then re-implement the errors with the SETERR command.

Parameters:
  • madx (cpymad.madx.Madx) -- An instanciated Madx object. Positional only.

  • deltaqx (float) -- The deltaQx (horizontal tune excitation) used by the AC dipole. This is added on top of the current matched tune.

  • deltaqy (float) -- The deltaQy (vertical tune excitation) used by the AC dipole. This is added on top of the current matched tune.

  • 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 during the tracking. 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 at full amplitude of the exciting oscillations. 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
)
pyhdtoolkit.cpymadtools.lhc._elements.install_ac_dipole_as_matrix(madx: Madx, /, deltaqx: float, deltaqy: float, beam: int = 1) None[source]

Added 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 makes the assumption that the lhcb1 / lhcb2 sequence is already defined, sliced, with an associated beam (BEAM command or make_lhc_beams function), is matched to the desired working point and a TWISS call has been made.

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.

Warning

Installing the AC Dipole modifies the sequence, and the USE command will be called again at the end of this function. This will remove any errors that were installed in the sequence.

As the errors impact the optics functions which are used during the installation of the AC Dipole, it would not be correct to implement them only after installing the element.

Therefore, it is recommended to install the errors and save them with the ESAVE or ETABLE command, call this function, then re-implement the errors with the SETERR command.

Parameters:
  • madx (cpymad.madx.Madx) -- An instanciated Madx object. Positional only.

  • deltaqx (float) -- The deltaQx (horizontal tune excitation) used by the AC dipole. This is added on top of the current matched tune.

  • deltaqy (float) -- The deltaQy (vertical tune excitation) used by the AC dipole. This is added on top of the current matched tune.

  • 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.

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

Added 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. 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. Positional only.

  • 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 for which to apply error on the triplets, either L, 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)",
)
pyhdtoolkit.cpymadtools.lhc._errors.misalign_lhc_triplets(madx: Madx, /, ip: int, sides: Sequence[str] = ('r', 'l'), table: str = 'triplet_errors', **kwargs) None[source]

Added 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. Positional only.

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

  • sides (Sequence[str]) -- Sides of the IP for which to apply error on the triplets, either L, 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.

pyhdtoolkit.cpymadtools.lhc._misc.get_lhc_bpms_list(madx: Madx, /) list[str][source]

Added 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 it requires that TWISS can succeed on your sequence.

Parameters:

madx (cpymad.madx.Madx) -- An instanciated Madx object. Positional only.

Returns:

list[str] -- The list of BPM names.

Example

observation_bpms = get_lhc_bpms_list(madx)
pyhdtoolkit.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]

Added 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) -- The accelerator to get knobs for, either LHC or HLLHC. Case insensitive.

  • beam (int) -- The beam to get knobs for. Defaults to 1.

  • telescopic_squeeze (bool) -- If set to True, uses the (HL)LHC knobs for Telescopic Squeeze configuration. Defaults to True to reflect Run 3 scenarios.

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

Returns:

tuple[str, str, str, str] -- A tuple of strings with knobs for (qx, qy, dqx, dqy).

Examples

get_lhc_tune_and_chroma_knobs("LHC", beam=1, telescopic_squeeze=False)
# gives ('dQx.b1', 'dQy.b1', 'dQpx.b1', 'dQpy.b1')
get_lhc_tune_and_chroma_knobs("LHC", beam=2, run3=True)
# gives ('dQx.b2_op', 'dQx.b2_op', 'dQpx.b2_op', 'dQpx.b2_op')
get_lhc_tune_and_chroma_knobs("HLLHC", beam=2)
# gives ('kqtf.b2_sq', 'kqtd.b2_sq', 'ksf.b2_sq', 'ksd.b2_sq')
pyhdtoolkit.cpymadtools.lhc._misc.get_sizes_at_ip(madx: Madx, /, ip: int, gemitt_x: float | None = None, gemitt_y: float | None = None) tuple[float, float][source]

Added 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. Positional only.

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

  • gemitt_x (float, optional) -- The horizontal geometrical emittance to use for the calculation. If not provided, the value of the geometric_emit_x variable in MAD-X will be used.

  • gemitt_y (float, optional) -- The vertical geometrical emittance to use for the calculation. If not provided, the value of the geometric_emit_y variable in MAD-X will be used.

Returns:

tuple[float, float] -- 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)
pyhdtoolkit.cpymadtools.lhc._misc.make_sixtrack_output(madx: Madx, /, energy: int) None[source]

Added 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)
pyhdtoolkit.cpymadtools.lhc._misc.reset_lhc_bump_flags(madx: Madx, /) None[source]

Added in version 0.15.0.

Resets all LHC IP bump flags to 0.

Parameters:

madx (cpymad.madx.Madx) -- An instanciated Madx object. Positional only.

Example

reset_lhc_bump_flags(madx)

Powering Utilities

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

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

Added in version 0.15.0.

Applies the a trim of the LHC colinearity knob.

Warning

If you don’t know what this is, then you most likely 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. Positional only.

  • 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)
pyhdtoolkit.cpymadtools.lhc._powering.apply_lhc_colinearity_knob_delta(madx: Madx, /, colinearity_knob_delta: float = 0, ir: int | None = None) None[source]

Added 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.

Warning

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

Parameters:
  • madx (cpymad.madx.Madx) -- An instanciated Madx object. Positional only.

  • colinearity_knob_value (float) -- Units of the colinearity knob to vary the existing knob with. 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_delta(madx, colinearity_knob_delta=3.5, ir=1)
pyhdtoolkit.cpymadtools.lhc._powering.apply_lhc_coupling_knob(madx: Madx, /, coupling_knob: float = 0, beam: int = 1, telescopic_squeeze: bool = True) None[source]

Added in version 0.15.0.

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

Parameters:
  • madx (cpymad.madx.Madx) -- An instanciated Madx object. Positional only.

  • 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 (HL)LHC knobs for Telescopic Squeeze configuration. Defaults to True to reflect Run 3 scenarios since v0.9.0.

Example

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

Added 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.

Warning

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

Important

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 quite well.

Parameters:
  • madx (cpymad.madx.Madx) -- An instanciated Madx object. Positional only.

  • rigidty_waist_shift_value (float) -- Units of the rigidity waist shift knob (positive values only). Defaults to 0 so users don’t mess up the IR setup by mistake.

  • 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. This parameter determines a sign in the calculation. Defaults to left, which means that \(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)
pyhdtoolkit.cpymadtools.lhc._powering.carry_colinearity_knob_over(madx: Madx, /, ir: int, to_left: bool = True) None[source]

Added 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. Positional only.

  • 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)
pyhdtoolkit.cpymadtools.lhc._powering.deactivate_lhc_arc_sextupoles(madx: Madx, /, beam: int) None[source]

Added in version 0.15.0.

Deactivates all arc sextupoles in the (HL)LHC.

Parameters:

Example

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

Added in version 0.15.0.

Powers the Landau octupoles in the (HL)LHC.

Parameters:
  • madx (cpymad.madx.Madx) -- An instanciated Madx object. Positional only.

  • beam (int) -- The beam to use.

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

  • defective_arc (bool) -- If set to True, the KOD in Arc 56 are powered for less Imax. Defaults to False.

Example

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

Added 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. Positional only.

  • **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 only:

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

Added 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 the make_lhc_beams function to create the beams, this has already been done automatically.

Parameters:
  • madx (cpymad.madx.Madx) -- An instanciated Madx object. Positional only.

  • 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]) -- Sides of the IP for which to apply error on the triplets, either L, R or both, case insensitive. Defaults to both.

  • 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.

pyhdtoolkit.cpymadtools.lhc._queries.get_current_orbit_setup(madx: Madx, /) dict[str, float][source]

Added 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. Positional only.

Returns:

dict[str, float] -- 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)
pyhdtoolkit.cpymadtools.lhc._queries.get_magnets_powering(madx: Madx, /, patterns: Sequence[str] = ['^mb\\.', '^mq\\.', '^ms\\.'], brho: str | float | None = None, **kwargs) TfsDataFrame[source]

Added in version 0.17.0.

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

Hint

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. Positional only.

  • 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 hint 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 and this one will be used.

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

Returns:

TfsDataFrame -- 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\."])
pyhdtoolkit.cpymadtools.lhc._queries.query_arc_correctors_powering(madx: Madx, /) dict[str, float][source]

Added 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 macros from the corr_value.madx file in the old toolkit.

Parameters:

madx (cpymad.madx.Madx) -- An instanciated Madx object. Positional only.

Returns:

dict[str, float] -- A dict with the percentage for each corrector.

Example

arc_knobs = query_arc_correctors_powering(madx)
pyhdtoolkit.cpymadtools.lhc._queries.query_triplet_correctors_powering(madx: Madx, /) dict[str, float][source]

Added 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 macros from the corr_value.madx file in the old toolkit.

Parameters:

madx (cpymad.madx.Madx) -- An instanciated Madx object. Positional only.

Returns:

dict[str, float] -- A dict with the percentage for each corrector.

Example

triplet_knobs = query_triplet_correctors_powering(madx)

Routine Utilities

The functions below are routines mimicking manipulations that would be done in the LHC.

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

Added 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. Positional only.

  • beam (int) -- The beam to perform the matching for. Should be either 1 or 2. Defaults to 1.

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

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

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

Example

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

Added 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. Positional only.

  • 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")
pyhdtoolkit.cpymadtools.lhc._routines.do_kmodulation(madx: Madx, /, ir: int = 1, side: str = 'right', steps: int = 100, stepsize: float = 3e-08, **kwargs) tfs.TfsDataFrame[source]

Added 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.

Hint

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. Positional only.

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

  • side (str) -- Side of the IP on which 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 modulation, 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:

tfs.TfsDataFrame -- 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 pyhdtoolkit.cpymadtools.lhc._setup.LHCSetup(run: int = 3, opticsfile: str | None = None, beam: int = 1, use_b4: bool = False, energy: float = 6800, slicefactor: int | None = None, **kwargs)[source]

Added in version 1.0.0.

context manager to prepare an LHC Run 2 or Run 3 setup: calling sequence 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 function and should be taken care of by the user, but the working point should be set by the definitions in the opticsfile.

Note

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) -- The name of the optics file 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) -- The 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) -- The beam energy to set up for, in [GeV]. Defaults to 6800, to match the default of Run 3.

  • slicefactor (int, optional) -- 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 these two are given as False). Any other keyword argument is transmitted to the Madx creation call.

Returns:

cpymad.madx.Madx -- 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:
    pass  # 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:
    pass  # do some stuff
pyhdtoolkit.cpymadtools.lhc._setup.lhc_orbit_variables() tuple[list[str], dict[str, str]][source]

Added 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:

tuple[list[str], dict[str, str]] -- 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()
pyhdtoolkit.cpymadtools.lhc._setup.make_lhc_beams(madx: Madx, /, energy: float = 7000, nemitt_x: float = 2.5e-06, nemitt_y: float = 2.5e-06, b4: bool = False, **kwargs) None[source]

Added in version 0.15.0.

Defines beams with default configuratons for LHCB1 and LHCB2 sequences.

Parameters:
  • madx (cpymad.madx.Madx) -- An instanciated Madx object. Positional only.

  • energy (float) -- Beam energy, in [GeV]. Defaults to 7000.

  • nemitt_x (float) -- Normalized horizontal emittance in [m]. Will be used to calculate geometric emittance which is then fed to the BEAM command. Defaults to the Run 3 value of 2.5e-6m.

  • nemitt_y (float) -- Normalized vertical emittance in [m]. Will be used to calculate geometric emittance which is then fed to the BEAM command. Defaults to the Run 3 value of 2.5e-6m.

  • 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 other keyword argument is given to the MAD-X BEAM command.

Examples

make_lhc_beams(madx, energy=6800, nemitt_x=2.75e-6, nemitt_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, nemitt_x=3e-6, nemitt_y=3e-6, b4=True)
pyhdtoolkit.cpymadtools.lhc._setup.make_lhc_thin(madx: Madx, /, sequence: str, slicefactor: int = 1, **kwargs) None[source]

Added 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 example use of this function in the AC Dipole Tracking and Free Tracking example galleries.

Parameters:
  • madx (cpymad.madx.Madx) -- An instanciated Madx object. Positional only.

  • 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)
pyhdtoolkit.cpymadtools.lhc._setup.prepare_lhc_run2(opticsfile: str, beam: int = 1, use_b4: bool = False, energy: float = 6500, slicefactor: int | None = None, **kwargs) Madx[source]

Added 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.

Parameters:
  • opticsfile (str) -- The relative string path or a Path object to the opticsfile location. This will be used to determine the location of the sequence file, see the admonition above.

  • beam (int) -- The 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) -- The beam energy to set up for, in [GeV]. Defaults to 6500.

  • slicefactor (int, optional) -- 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 these two are given as False). Any other keyword argument is transmitted to the Madx creation call.

Returns:

cpymad.madx.Madx -- 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,
)
pyhdtoolkit.cpymadtools.lhc._setup.prepare_lhc_run3(opticsfile: str, beam: int = 1, use_b4: bool = False, energy: float = 6800, slicefactor: int | None = None, **kwargs) Madx[source]

Added 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 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 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 the acc-models-lhc repo itself.

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.

Parameters:
  • opticsfile (str) -- The 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) -- The 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) -- The beam energy to set up for, in [GeV]. Defaults to 6800.

  • slicefactor (int, optional) -- 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 these two are given as False). Any other keyword argument is transmitted to the Madx creation call.

Returns:

cpymad.madx.Madx -- An instanciated Madx object with the required configuration.

Example

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

Added 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 instanciated Madx object. Positional only.

  • sequence (str) -- The sequence to re-cycle. Defaults to “lhcb1”.

  • start (str) -- The element to start the new cycle from. Defaults to “IP3”.

Example

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

Added 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. Positional only.

  • 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:

dict[str, float] -- 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.

pyhdtoolkit.cpymadtools.lhc._twiss.get_ips_twiss(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) TfsDataFrame[source]

Added 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. Positional only.

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

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

Returns:

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

Example

ips_df = get_ips_twiss(madx, chrom=True, ripken=True)
pyhdtoolkit.cpymadtools.lhc._twiss.get_ir_twiss(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) TfsDataFrame[source]

Added 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. Positional only.

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

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

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

Returns:

TfsDataFrame -- 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.

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

Added 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 (str, optional) -- Name of the accelerator, used to determmine knobs if variables is not given. Automatic determination will only work for the LHC and HLLHC (accepted case insensitively). Defaults to None, in which case the knobs must be provided explicitly through varied_knobs.

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

  • dq1_target (float, optional) -- 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, optional) -- 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], optional) -- 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. This parameter is optional if the accelerator is provided as LHC or HLLHC, but must be provided otherwise. Defaults to None.

  • 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) -- LHC specific. If set to True, uses the LHC Run 3 *_op knobs. Defaults to False.

  • step (float) -- Step size to use when varying knobs. Defaults to \(10^{-7}\).

  • 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 parameters 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 lhcb1 sequence of the LHC lattice and letting the function determine the knobs automatically:

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

Added 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 (str, optional) -- Name of the accelerator, used to determmine knobs if variables is not given. Automatic determination will only work for the LHC and HLLHC (accepted case insensitively). Defaults to None, in which case the knobs must be provided explicitly through varied_knobs.

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

  • q1_target (float, optional) -- 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, optional) -- 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], optional) -- 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. This parameter is optional if the accelerator is provided as LHC or HLLHC, but must be provided otherwise. Defaults to None.

  • 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) -- LHC specific. If set to True, uses the LHC Run 3 *_op knobs. Defaults to False.

  • step (float) -- Step size to use when varying knobs. Defaults to \(10^{-7}\).

  • 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 parameters 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 lhcb1 sequence of the LHC lattice and letting the function determine the knobs automatically:

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

Added 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 in the MAD-X process. For usage details, see the MAD-X manual.

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

Important

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

Note

If one 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, or simply the wrappers provided in this module.

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 one could call this function three times, or use each wrapper once (first tunes, then chromaticities, then this function). Refer to the match_tunes() and match_chromaticities() functions.

Hint

When acting on 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, based on the machine’s default knobs. Note that in this case only the relevant knobs are set, so if tune targets only are provided, then tune knobs only will be used, and vice versa. If explicit knobs are provided, these will always take precedence. On any other machine the knobs should be provided explicitly, always.

Parameters:
  • madx (cpymad.madx.Madx) -- An instanciated Madx object.

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

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

  • q1_target (float, optional) -- 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, optional) -- 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, optional) -- 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, optional) -- 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], optional) -- 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. This parameter is optional if the accelerator is provided as LHC or HLLHC, but must be provided otherwise. Defaults to None.

  • 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) -- LHC specific. If set to True, uses the LHC Run 3 *_op knobs. Defaults to False.

  • step (float) -- Step size to use when varying knobs. Defaults to \(10^{-7}\).

  • 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 parameters 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 and letting the function determine the knobs automatically:

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
)

Beam Parameters

Module with functions to fetch or compute different beam and machine parameters through a Madx object.

pyhdtoolkit.cpymadtools.parameters.query_beam_attributes(madx: Madx, /) MADXBeam[source]

Added in version 0.12.0.

Returns all BEAM attributes from the MAD-X process based on the currently defined beam. If no beam has been defined at function call, then MAD-X will return all the default values. See the MAD-X manual for details.

Parameters:

madx (cpymad.madx.Madx) -- An instanciated Madx object. Positional only.

Returns:

MADXBeam -- A validated MADXBeam object.

Example

beam_parameters = query_beam_attributes(madx)

PTC Routines

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

pyhdtoolkit.cpymadtools.ptc.get_amplitude_detuning(madx: Madx, /, order: int = 2, file: Path | str | None = None, fringe: bool = False, **kwargs) tfs.TfsDataFrame[source]

Added 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 default values used for the PTC_CREATE_LAYOUT command are: model=3 (SixTrack model), method=4 (integration order), nst=3 (number of integration steps, a.k.a body slices for elements) and exact=True (use an exact Hamiltonian, not an approximated one). These can be provided as keyword arguments to override them.

The PTC_NORMAL command is explicitely given icase=6 by default in order to enforce 6D calculations (see the MAD-X manual for details), no=5 (map order for derivative evaluation of Twiss parameters), normal=True (activate calculation of the Normal Form) and closedorbit=True (triggers closed orbit calculation). These can also be provided as keyword arguments to override them.

Parameters:
  • madx (cpymad.madx.Madx) -- An instanciated Madx object. Positional only.

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

  • file (Path | str, optional) -- Path to output file. Defaults to None, which will skip writing the resulting table to disk.

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

  • **kwargs -- Some parameters for the PTC universe creation can be given as keyword arguments. They are model, method, nst and exact (case sensitive). Similarly icase, no, closed_orbit and normal can be given (case sensitively) for the PTC_NORMAL command. Any remaining keyword argument is transmitted to the PTC_NORMAL command as given.

Returns:

tfs.TfsDataFrame -- A TfsDataFrame with the calculated RDTs, and the SUMM table as headers.

Examples

ampdet_coeffs = get_amplitude_detuning(madx, order=2, closedorbit=True)

One can also specify parameters for the PTC universe and the PTC_NORMAL command:

tracks_dict = get_amplitude_detuning(
    madx, order=3, model=3, exact=True, icase=5, no=6
)
pyhdtoolkit.cpymadtools.ptc.get_rdts(madx: Madx, /, order: int = 4, file: Path | str | None = None, fringe: bool = False, **kwargs) tfs.TfsDataFrame[source]

Added 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 default values used for the PTC_CREATE_LAYOUT command are: model=3 (SixTrack model), method=4 (integration order), nst=3 (number of integration steps, a.k.a body slices for elements) and exact=True (use an exact Hamiltonian, not an approximated one). These can be provided as keyword arguments to override them.

The PTC_TWISS command is explicitely given icase=6 by default in order to enforce 6D calculations (see the MAD-X manual for details), and normal=True to activate calculation of the Normal Form. The normal form analysis result will be stored in an internal table named NONLIN which will then be available through the provided Madx instance. These can also be provided as keyword arguments to override them.

Parameters:
  • madx (cpymad.madx.Madx) -- An instanciated Madx object. Positional only.

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

  • file (Path | str, optional) -- Path to output file. Defaults to None, which will skip writing the resulting table to disk.

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

  • **kwargs -- Some parameters for the PTC universe creation can be given as keyword arguments. They are model, method, nst and exact (case sensitive). Similarly icase and normal can be given (case sensitively) for the PTC_TWISS command. Any remaining keyword argument is transmitted to the PTC_TWISS command as given.

Returns:

tfs.TfsDataFrame -- A TfsDataFrame with the calculated RDTs, and the SUMM table as headers.

Examples

rdts_df = get_rdts(madx, order=3, fringe=True)

One can also specify parameters for the PTC universe and the PTC_TWISS command:

tracks_dict = get_rdts(
    madx, order=3, model=3, method=6, nst=3, exact=True, icase=5
)
pyhdtoolkit.cpymadtools.ptc.ptc_track_particle(madx: Madx, /, initial_coordinates: tuple[float, float, float, float, float, float], nturns: int, sequence: str | None = None, observation_points: Sequence[str] | None = None, onetable: bool = False, fringe: bool = False, **kwargs) dict[str, pd.DataFrame][source]

Added 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 default values used for the PTC_CREATE_LAYOUT command are: model=3 (SixTrack model), method=4 (integration order), nst=3 (number of integration steps, a.k.a body slices for elements) and exact=True (use an exact Hamiltonian, not an approximated one). These can be provided as keyword arguments to override them.

The PTC_TRACK command is explicitely given ELEMENT_BY_ELEMENT=True by default to force element by element tracking mode. This can also be provided as keyword argument to override it.

Warning

If the sequence parameter 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 with.

Parameters:
  • madx (cpymad.madx.Madx) -- An instanciated Madx object. Positional only.

  • 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 (str, optional) -- 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 use-d by MAD-X, see the warning above for more information.

  • observation_points (Sequence[str], optional) -- A sequence of 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 --

    Some parameters for the PTC universe creation can be given as keyword arguments. They are model, method, nst and exact (case sensitive). Similarly element_by_element can be given (case sensitively) for the PTC_TRACK command. Any remaining keyword argument is transmitted to the PTC_TRACK command, such as the closed_orbit flag to activate closed orbit calculation before any tracking. Refer to the MAD-X manual for options.

Returns:

dict[str, pd.DataFrame] -- 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 at function call, in the order they are given.

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

Examples

tracks_dict = ptc_track_particle(
    madx, nturns=1023, initial_coordinates=(2e-4, 0, 1e-4, 0, 0, 0)
)

One can also specify parameters for the PTC universe:

tracks_dict = ptc_track_particle(
    madx,
    nturns=10,
    initial_coordinates=(2e-4, 0, 1e-4, 0, 0, 0),
    model=3,
    method=6,
    nst=3,
    exact=True,
)
pyhdtoolkit.cpymadtools.ptc.ptc_twiss(madx: Madx, /, order: int = 4, file: Path | str | None = None, fringe: bool = False, table: str = 'ptc_twiss', **kwargs) tfs.TfsDataFrame[source]

Added 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 default values used for the PTC_CREATE_LAYOUT command are: model=3 (SixTrack model), method=4 (integration order), nst=3 (number of integration steps, a.k.a body slices for elements) and exact=True (use an exact Hamiltonian, not an approximated one). These can be provided as keyword arguments to override them.

The PTC_TWISS command is explicitely given icase=6 by default in order to enforce 6D calculations (see the MAD-X manual for details), and normal=True to activate calculation of the Normal Form. The normal form analysis result will be stored in an internal table named NONLIN which will then be available through the provided Madx instance. These can also be provided as keyword arguments to override them.

Parameters:
  • madx (cpymad.madx.Madx) -- An instanciated Madx object. Positional only.

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

  • file (Path | str, optional) -- Path to output file. Defaults to None, which will skip writing the resulting table to disk.

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

  • **kwargs -- Some parameters for the PTC universe creation can be given as keyword arguments. They are model, method, nst and exact (case sensitive). Similarly icase and normal can be given (case sensitively) for the PTC_TWISS command. Any remaining keyword argument is transmitted to the PTC_TWISS command as given.

Returns:

tfs.TfsDataFrame -- A TfsDataFrame with the calculated TWISS parameters, and the SUMM table as headers.

Examples

twiss_ptc_df = ptc_twiss(madx, order=3)

One can also specify parameters for the PTC universe and the PTC_TWISS command:

tracks_dict = ptc_twiss(
    madx, order=3, model=3, method=6, nst=3, exact=True, icase=5
)

Tracking Routines

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

pyhdtoolkit.cpymadtools.track.track_single_particle(madx: Madx, /, initial_coordinates: tuple[float, float, float, float, float, float], nturns: int, sequence: str | None = None, observation_points: Sequence[str] | None = None, **kwargs) dict[str, pd.DataFrame][source]

Added in version 0.8.0.

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

Warning

If the sequence parameter 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 with.

Parameters:
  • madx (cpymad.madx.Madx) -- An instantiated Madx object. Positional only.

  • 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 (str, optional) -- 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 use-d by MAD-X, see the warning above for more information.

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

  • **kwargs --

    Any keyword argument will be given to the TRACK command, for instance ONETABLE etc. Refer to the MAD-X manual for options.

Returns:

dict[str, pd.DataFrame] -- 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 at function call, in the order they are given.

If the user has set onetable=True, only one entry is in the dictionary under the key trackone and it has the combined table as a 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.

pyhdtoolkit.cpymadtools.tune.get_footprint_lines(dynap_dframe: TfsDataFrame) tuple[ndarray, ndarray][source]

Added in version 0.12.0.

Provided with the TfsDataFrame as is returned by the make_footprint_table function, 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 most of it works under the hood. I also do not know who wrote this initially. Results are not guaranteed to be correct and should always be checked with a quick plot.

Parameters:

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

Returns:

tuple[np.ndarray, np.ndarray] -- The \(Q_x\) and \(Q_y\) data points to plot directly, 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")
pyhdtoolkit.cpymadtools.tune.get_footprint_patches(dynap_dframe: TfsDataFrame) PatchCollection[source]

Added in version 0.12.0.

Provided with the TfsDataFrame as is returned by the make_footprint_table function, computes the polygon patches needed to plot the tune 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 one might need to change the ANGLE or AMPLITUDE values in dynap_dframe headers.

Parameters:

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

Returns:

matplotlib.collections.PatchCollection -- 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)
pyhdtoolkit.cpymadtools.tune.make_footprint_table(madx: Madx, /, sigma: float = 5, dense: bool = False, file: str | None = None, cleanup: bool = True, **kwargs) tfs.TfsDataFrame[source]

Added 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. Positional only.

  • 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, optional) -- 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:

tfs.TfsDataFrame -- The resulting DYNAPTUNE table, as a TfsDataFrame.

Example

dynap_dframe = make_footprint_table(madx, dense=True)

TWISS Routines

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

pyhdtoolkit.cpymadtools.twiss.get_pattern_twiss(madx: Madx, /, columns: Sequence[str] | None = None, patterns: Sequence[str] = (), **kwargs) tfs.TfsDataFrame[source]

Added in version 0.8.0.

Extracts the TWISS table for desired variables from the provided Madx object, for elements matching the provided patterns. The table is returned as a TfsDataFrame, the headers of which are the contents of the internal SUMM table.

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. Positional only.

  • columns (Sequence[str], optional) -- 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 an empty sequence, 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 values for betx, bety etc.

Returns:

tfs.TfsDataFrame -- A TfsDataFrame with the selected columns for all elements matching the provided patterns, and the internal SUMM table as headers.

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
    ],
)
pyhdtoolkit.cpymadtools.twiss.get_twiss_tfs(madx: Madx, /, **kwargs) tfs.TfsDataFrame[source]

Added 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. Positional only.

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

Returns:

tfs.TfsDataFrame -- A TfsDataFrame of the TWISS table, with the internal SUMM table as headers.

Example

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

Miscellaneous Utilities

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

pyhdtoolkit.cpymadtools.utils.export_madx_table(madx: Madx, /, table_name: str, file_name: Path | str, pattern: str | None = None, headers_table: str = 'SUMM', **kwargs) None[source]

Added 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 present (see below for their usage), then they will be given default values so the TFS file can be read back by MAD-X.

Parameters:
  • madx (cpymad.madx.Madx) -- An instanciated Madx object. Positional only.

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

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

  • pattern (str | None, optional) -- 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 using the SUMM table.

  • **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")
pyhdtoolkit.cpymadtools.utils.get_table_tfs(madx: Madx, /, table_name: str, headers_table: str = 'SUMM') tfs.TfsDataFrame[source]

Added 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. Positional only.

  • 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 using the SUMM table.

Returns:

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

Example

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