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: cpymad.madx.Madx, /, accelerator: str = None, sequence: str = None, varied_knobs: Sequence[str] = None, telescopic_squeeze: bool = True, run3: bool = False, explicit_targets: 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.

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

  • 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)
)
# returns 0.001
pyhdtoolkit.cpymadtools.coupling.get_cminus_from_coupling_rdts(madx: cpymad.madx.Madx, /, patterns: Sequence[str] = [''], method: str = 'teapot', qx: float = None, qy: 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. 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) -- 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]$"])
pyhdtoolkit.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 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 -- any keyword argument will be transmitted to the TWISS command in MAD-X.

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)
pyhdtoolkit.cpymadtools.coupling.match_no_coupling_through_ripkens(madx: cpymad.madx.Madx, /, sequence: str = None, location: str = None, vary_knobs: 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. Positional only.

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

  • 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)
pyhdtoolkit.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. Positional only.

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.

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

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

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.

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

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.

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

pyhdtoolkit.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. 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 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)"
)
pyhdtoolkit.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. Positional only.

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

pyhdtoolkit.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)
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]

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)
# 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: cpymad.madx.Madx, /, ip: int, geom_emit_x: float = None, geom_emit_y: 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. Positional only.

  • 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)
pyhdtoolkit.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)
pyhdtoolkit.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. 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: cpymad.madx.Madx, /, colinearity_knob_value: float = 0, ir: 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. 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: cpymad.madx.Madx, /, colinearity_knob_delta: float = 0, ir: 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. Positional only.

  • 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)
pyhdtoolkit.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. 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 knobs for Telescopic Squeeze configuration. Defaults to True 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: cpymad.madx.Madx, /, rigidty_waist_shift_value: float = 0, ir: 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. Positional only.

  • 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)
pyhdtoolkit.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. 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: 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)
pyhdtoolkit.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. Positional only.

  • 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)
pyhdtoolkit.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. 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: 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. 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]) -- 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.

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

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)
pyhdtoolkit.cpymadtools.lhc._queries.get_magnets_powering(madx: cpymad.madx.Madx, /, patterns: Sequence[str] = ['^mb\\.', '^mq\\.', '^ms\\.'], brho: 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. 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 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\."])
pyhdtoolkit.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)
pyhdtoolkit.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)

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

  • 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)
pyhdtoolkit.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. 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: 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. Positional only.

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

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()
pyhdtoolkit.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. Positional only.

  • 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)
pyhdtoolkit.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)
pyhdtoolkit.cpymadtools.lhc._setup.prepare_lhc_run2(opticsfile: str, beam: int = 1, use_b4: bool = False, energy: float = 6500, slicefactor: 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) -- 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) -- 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
)
pyhdtoolkit.cpymadtools.lhc._setup.prepare_lhc_run3(opticsfile: str, beam: int = 1, use_b4: bool = False, energy: float = 6800, slicefactor: 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
)
pyhdtoolkit.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")
pyhdtoolkit.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. 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

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

  • 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)
pyhdtoolkit.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. Positional only.

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

pyhdtoolkit.cpymadtools.matching.match_chromaticities(madx: cpymad.madx.Madx, /, accelerator: str = None, sequence: Optional[str] = None, dq1_target: float = None, dq2_target: float = None, varied_knobs: 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. Positional only.

  • 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,
)
pyhdtoolkit.cpymadtools.matching.match_tunes(madx: cpymad.madx.Madx, /, accelerator: str = None, sequence: Optional[str] = None, q1_target: float = None, q2_target: float = None, varied_knobs: 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. Positional only.

  • 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,
)
pyhdtoolkit.cpymadtools.matching.match_tunes_and_chromaticities(madx: cpymad.madx.Madx, /, accelerator: str = None, sequence: Optional[str] = None, q1_target: float = None, q2_target: float = None, dq1_target: float = None, dq2_target: float = None, varied_knobs: 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. Positional only.

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

Parameters

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

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

New 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

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: cpymad.madx.Madx, /, order: int = 2, file: 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 default values used for the PTC_CREATE_LAYOUT command are 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). These can be provided as keyword arguments to override them.

The PTC_NORMAL command is explicitely given icase=6 by default 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. Positional only.

  • 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 -- Some parameters for the PTC universe creation can be given as keyword arguments. They are model, method, nst and exact. The icase, no, closed_orbit and normal kwargs can be given for the PTC_NORMAL command. Their default values are listed higher up in this docstring. Any remaining keyword argument is transmitted to the PTC_NORMAL command.

Returns

A TfsDataframe with the calculated coefficients.

Example

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: cpymad.madx.Madx, /, order: int = 4, file: 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 default values used for the PTC_CREATE_LAYOUT command are 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). These can be provided as keyword arguments to override them.

The PTC_TWISS command is given icase=6 by default to enforce 6D calculations (see the MAD-X manual for details), 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.

These default values can be changed through keyword arguments.

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

  • 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 -- Some parameters for the PTC universe creation can be given as keyword arguments. They are model, method, nst and exact. The icase and normal ones can be given for the PTC_TWISS command. Their default values are listed higher up in this docstring. Any remaining keyword argument is transmitted to the PTC_TWISS command.

Returns

A TfsDataFrame with the calculated RDTs.

Example

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: cpymad.madx.Madx, /, initial_coordinates: Tuple[float, float, float, float, float, float], nturns: int, sequence: Optional[str] = None, observation_points: 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 default values used for the PTC_CREATE_LAYOUT command are 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). These can be provided as keyword arguments to override them.

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

These default values can be changed through keyword arguments.

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

    Some parameters for the PTC universe creation can be given as keyword arguments. They are model, method, nst, exact and element_by_element for the PTC_TRACK command. Their default values are listed higher up in this docstring. Any remaining 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 DataFrame for value.

Example

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: cpymad.madx.Madx, /, order: int = 4, file: 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 default values used for the PTC_CREATE_LAYOUT command are 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). These can be provided as keyword arguments to override them.

The PTC_TWISS command is given icase=6 by default to enforce 6D calculations (see the MAD-X manual for details), 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.

These default values can be changed through keyword arguments.

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

  • 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 -- Some parameters for the PTC universe creation can be given as keyword arguments. They are model, method, nst and exact. The icase and normal ones can be given for the PTC_TWISS command. Their default values are listed higher up in this docstring. Any remaining keyword argument is transmitted to the PTC_TWISS command.

Returns

A TfsDataFrame with the calculated TWISS parameters.

Example

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: cpymad.madx.Madx, /, initial_coordinates: Tuple[float, float, float, float, float, float], nturns: int, sequence: Optional[str] = None, observation_points: 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.

pyhdtoolkit.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")
pyhdtoolkit.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)
pyhdtoolkit.cpymadtools.tune.make_footprint_table(madx: cpymad.madx.Madx, /, sigma: float = 5, dense: bool = False, file: 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. 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) -- 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.

pyhdtoolkit.cpymadtools.twiss.get_pattern_twiss(madx: cpymad.madx.Madx, /, columns: 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. Positional only.

  • 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
    ],
)
pyhdtoolkit.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. Positional only.

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

pyhdtoolkit.cpymadtools.utils.export_madx_table(madx: cpymad.madx.Madx, /, table_name: str, file_name: Union[pathlib.Path, str], pattern: 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 (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. Positional only.

  • 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")
pyhdtoolkit.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. 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 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")