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
Madxobject, 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 usesmatch_tunes_and_chromaticitiesunder 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-Xinternal tables.- Parameters:
madx (
cpymad.madx.Madx) -- An instanciatedMadxobject. Positional only.accelerator (
str, optional) -- Name of the accelerator, used to determmine knobs if variables is not given. Automatic determination will only work forLHCandHLLHC.sequence (
str, optional) -- Name of the sequence to activate for the tune matching.varied_knobs (
Sequence[str], optional) -- The variables names toVARYin theMAD-XMATCHroutine. 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) --LHCspecific. If set toTrue, uses the(HL)LHCknobs for Telescopic Squeeze configuration. Defaults toTruesincev0.9.0.run3 (
bool) -- If set toTrue, uses theLHCRun 3*_opknobs. Defaults toFalse.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 toNone.step (
float) -- Step size to use when varying knobs. Defaults to1e-7.calls (
int) -- Max number of varying calls to perform. Defaults to100.tolerance (
float) -- Tolerance for successfull matching. Defaults to1e-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-Xas thedqminvariable in theSUMMtable. 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_franchiorfranchimethod, the returned value will be a real number.- Parameters:
madx (
cpymad.madx.Madx) -- An instanciatedMadxobject. Positional only.patterns (
Sequence[str]) -- The different patterns (such asMQXorBPM) of elements to use when computing the coupling RDTs. Defaults to[""]which will select and use all elements in theTWISSoutputs.method (
str) -- The method to use for the calculation of the \(C^{-}\). Defaults toteapot, which is the default ofclosest_tune_approach.qx (
float, optional) -- The horizontal tune. If this parameters is not provided then the value will be taken from theSUMMtable.qy (
float, optional) -- The vertical tune. If this parameters is not provided then the value will be taken from theSUMMtable.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 to0, 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
TWISScall.- Parameters:
madx (
cpymad.madx.Madx) -- An instanciatedMadxobject. Positional only.**kwargs -- All keyword arguments are passed to the
TWISScommand inMAD-X.
- Returns:
TfsDataFrame-- ATfsDataFramewith columns of theTWISStable, and two complex columns for theF1001andf1010RDTs.
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 instanciatedMadxobject. 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 theTable Access Functionssection in theMAD-Xdocumentation for more information on the location string format.vary_knobs (
Sequence[str], optional) -- The variables names toVARYin theMAD-Xroutine.
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
TWISSon the currently active sequence for allLHCBPMs. The coupling RDTs are also computed through a CMatrix approach via a call tooptics_functions.coupling.coupling_via_cmatrix.- Parameters:
madx (
cpymad.madx.Madx) -- An instanciatedMadxobject. Positional only.- Returns:
TfsDataFrame-- ATfsDataFrameof theTWISStable 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
TWISScall.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-Xprocess to crash.Warning
After editing the sequence to add markers, the
USEcommand will be called for the changes to apply. This means the caveats ofUSEapply, for instance the erasing of previously defined errors, orbits corrections etc.Therefore, it is recommended to install the errors and save them with the
ESAVEorETABLEcommand, call this function, then re-implement the errors with theSETERRcommand.- Parameters:
madx (
cpymad.madx.Madx) -- An instanciatedMadxobject. 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]. Givinginterval=0.05will 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/lhcb2sequence is already defined, sliced, with an associated beam (BEAMcommand ormake_lhc_beamsfunction), is matched to the desired working point and aTWISScall 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-Xhowever, 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 affectTWISSfunctions.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
USEcommand 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
ESAVEorETABLEcommand, call this function, then re-implement the errors with theSETERRcommand.- Parameters:
madx (
cpymad.madx.Madx) -- An instanciatedMadxobject. 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/lhcb2sequence is already defined, sliced, with an associated beam (BEAMcommand ormake_lhc_beamsfunction), is matched to the desired working point and aTWISScall 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-Xhowever, 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 onTWISSfunctions. It does not affect tracking.Warning
Installing the AC Dipole modifies the sequence, and the
USEcommand 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
ESAVEorETABLEcommand, call this function, then re-implement the errors with theSETERRcommand.- Parameters:
madx (
cpymad.madx.Madx) -- An instanciatedMadxobject. 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
MQorMQTwhich 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-Xchooses 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 instanciatedMadxobject. 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
EALIGNcommand, including the error to apply (DX,DY,DPSIetc) as a string, like it would be given directly intoMAD-X.
Examples
For systematic
DXmisalignment: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
DYandDPSI:
- 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_quadrupolesfunction, see that function’s docstring for more information.- Parameters:
madx (
cpymad.madx.Madx) -- An instanciatedMadxobject. 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
EALIGNcommand, including the error to apply (DX,DY,DPSIetc) as a string, like it would be given directly intoMAD-X.
Examples
A random, gaussian truncated
DXmisalignment:misalign_lhc_triplets(madx, ip=1, sides="RL", dx="1E-5 * TGAUSS(2.5)")
A random, gaussian truncated
DPSImisalignment: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
TWISScommand.Note
As this function calls the
TWISScommand it requires thatTWISScan succeed on your sequence.- Parameters:
madx (
cpymad.madx.Madx) -- An instanciatedMadxobject. Positional only.- Returns:
list[str]-- Thelistof 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, eitherLHCorHLLHC. Case insensitive.beam (
int) -- The beam to get knobs for. Defaults to 1.telescopic_squeeze (
bool) -- If set toTrue, uses the(HL)LHCknobs for Telescopic Squeeze configuration. Defaults toTrueto reflect Run 3 scenarios.run3 (
bool) -- If set toTrue, uses the Run 3*_opknobs. Defaults toFalse.
- Returns:
tuple[str,str,str,str]-- Atupleof 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 instanciatedMadxobject. 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 thegeometric_emit_xvariable inMAD-Xwill be used.gemitt_y (
float, optional) -- The vertical geometrical emittance to use for the calculation. If not provided, the value of thegeometric_emit_yvariable inMAD-Xwill 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
SixTrackrun. Initial implementation credits go to Joschua Dilly.- Parameters:
madx (
cpymad.madx.Madx) -- An instanciatedMadxobject. Positional only.energy (
float) -- The beam energy, in [GeV].
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 instanciatedMadxobject. 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
LSAfor theLHC, is that a positive value of the colinearity knob results in a powering increase of theMQSXright of the IP, and a powering decrease of theMQSXleft of the IP.- Parameters:
madx (
cpymad.madx.Madx) -- An instanciatedMadxobject. 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 instanciatedMadxobject. 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 instanciatedMadxobject. Positional only.coupling_knob (
float) -- Desired value for the Cminus, typically a few units of1E-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 toTrue, uses the(HL)LHCknobs for Telescopic Squeeze configuration. Defaults toTrueto reflect Run 3 scenarios sincev0.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 instanciatedMadxobject. 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 toleft, which means that \(s_{\mathrm{waist}} \lt s_{\mathrm{ip}}\) (and setting it torightwould 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 instanciatedMadxobject. Positional only.ir (
int) -- The Interaction Region around which to apply the change, should be one of [1, 2, 5, 8].to_left (
bool) -- IfTrue, the magnet right of IP is de-powered of and its powering is transferred to the magnet left of IP. IfFalse, then the opposite happens. Defaults toTrue.
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:
madx (
cpymad.madx.Madx) -- An instanciatedMadxobject. Positional only.beam (
int) -- The beam to use.
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:
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
LHCandHLLHCmachines. Initial implementation credits go to Joschua Dilly.- Parameters:
madx (
cpymad.madx.Madx) -- An instanciatedMadxobject. Positional only.**kwargs -- The setting works through keyword arguments, and several specific kwargs are expected.
defaultsets global default to this value (defaults toFalse).AB#sets the default for all of that order, the order being the#number.A#orB#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
B6order 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
VARYcommands 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
brhovariable when creating your beams. If one has used themake_lhc_beamsfunction to create the beams, this has already been done automatically.- Parameters:
madx (
cpymad.madx.Madx) -- An instanciatedMadxobject. 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 instanciatedMadxobject. Positional only.- Returns:
dict[str,float]-- Adictof all orbit variables set, and their values as set in theMAD-Xglobals.
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
LHCand 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
TWISSflag will be fully cleared after running this function.- Parameters:
madx (
cpymad.madx.Madx) -- An instanciatedMadxobject. 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 specificLHCmagnet families.brho (
Union[str,float], optional) -- An explicit definition for the magnetic rigidity in \(Tm^{-1}\). If not given, it will be assumed that abrhoquantity is defined in theMAD-Xglobals and this one will be used.**kwargs -- Any keyword argument will be passed to
get_pattern_twissand later on to theTWISScommand executed inMAD-X.
- Returns:
TfsDataFrame-- ATfsDataFrameof theTWISStable, 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 instanciatedMadxobject. Positional only.- Returns:
dict[str,float]-- Adictwith 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 instanciatedMadxobject. Positional only.- Returns:
dict[str,float]-- Adictwith 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
LHCcoupling knobs.Important
This routine makes use of some matching tricks and uses the
SUMMtable’sdqminvariable for the matching. It should be considered a helpful little trick, but it is not a perfect solution.- Parameters:
madx (
cpymad.madx.Madx) -- An instanciatedMadxobject. 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 toTrue, uses the(HL)LHCknobs for Telescopic Squeeze configuration. Defaults toTrue.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 theCORRECTcommand inMAD-Xbehind the scenes, refer to the MAD-X manual for usage information.- Parameters:
madx (
cpymad.madx.Madx) -- An instanciatedMadxobject. 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 tomicadoas in theCORRECTcommand.**kwargs -- Any keyword argument that can be given to the
MAD-XCORRECTcommand, such asmode,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 instanciatedMadxobject. 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 eitherrightorleft, case insensitive. Defaults toright.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 inMAD-X. Defaults to 3e-8.**kwargs -- Any additional keyword arguments to pass to down to the
MAD-XTWISScommand, such aschrom,ripkenorcentre.
- Returns:
tfs.TfsDataFrame-- ATfsDataFramecontaining 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
OMCmodel creator, making beams, potentially slicing, etc. For details on the achieved setups, look at theprepare_lhc_run2orprepare_lhc_run3functions.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
lhcb4sequence needs to be called. This is handled by giving theuse_b4argument asTrueto 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 toNone, which will raise an error.beam (
int) -- The beam to set up for. Defaults to beam 1.use_b4 (
bool) -- IfTrue, the lhcb4 sequence file will be used. This is the beam 2 sequence but for tracking purposes. Defaults toFalse.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 toNone, which leads to an unsliced sequence.**kwargs -- If
echoorwarnare found in the keyword arguments they will be transmitted as options toMAD-X(by default these two are given asFalse). Any other keyword argument is transmitted to theMadxcreation call.
- Returns:
cpymad.madx.Madx-- An instanciated context managerMadxobject with the required configuration.- Raises:
NotImplementedError -- If the run argument is not 2 or 3.
AssertionError -- If the opticsfile argument is not provided.
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]]-- Atuplewith alistof all orbit variables, and adictof 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
LHCB1andLHCB2sequences.- Parameters:
madx (
cpymad.madx.Madx) -- An instanciatedMadxobject. 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 theBEAMcommand. 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 theBEAMcommand. Defaults to the Run 3 value of 2.5e-6m.b4 (
bool) -- IfTrue, will consider one is usinglhb4to do tracking on beam 2, and will properly set thebvflag to 1. Defaults toFalse.**kwargs -- Any other keyword argument is given to the
MAD-XBEAMcommand.
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
lhcb4and setbvto 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
MAKETHINcommand for the LHC sequence as previously done inMAD-Xmacros. This will use theteapotstyle and will enforcemakedipedge.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 instanciatedMadxobject. Positional only.sequence (
str) -- The sequence to use for theMAKETHINcommand.slicefactor (
int) -- The slice factor to apply inMAKETHIN, 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-XMAKETHNcommand, namelystyle(will default toteapot) and themakedipedgeflag (will default toTrue).
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
LHCsetup for the given opticsfile, for a Run 2 setup. Both beams are made with a default Run 2 configuration, and thelhcbsequence for the given beam is re-cycled fromMSIA.EXIT.B{beam}as in theOMCmodel_creator, and thenUSE-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 aPathobject 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) -- IfTrue, the lhcb4 sequence file will be used. This is the beam 2 sequence but for tracking purposes. Defaults toFalse.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 toNone, which leads to an unsliced sequence.**kwargs -- If
echoorwarnare found in the keyword arguments they will be transmitted as options toMAD-X(by default these two are given asFalse). Any other keyword argument is transmitted to theMadxcreation call.
- Returns:
cpymad.madx.Madx-- An instanciatedMadxobject 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
LHCsetup for the given opticsfile, for a Run 3 setup. Both beams are made with a default Run 3 configuration, and thelhcbsequence for the given beam is re-cycled fromMSIA.EXIT.B{beam}as in theOMCmodel_creator, and thenUSE-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-lhcrepo is available in the root space, which is needed by the different files in theacc-models-lhcrepo 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) -- IfTrue, the lhcb4 sequence file will be used. This is the beam 2 sequence but for tracking purposes. Defaults toFalse.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 toNone, which leads to an unsliced sequence.**kwargs -- If
echoorwarnare found in the keyword arguments they will be transmitted as options toMAD-X(by default these two are given asFalse). Any other keyword argument is transmitted to theMadxcreation call.
- Returns:
cpymad.madx.Madx-- An instanciatedMadxobject 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 instanciatedMadxobject. 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 instanciatedMadxobject. Positional only.scheme (
str) -- The default scheme to apply, as defined in theLHC_CROSSING_SCHEMESconstant. Accepted values are keys ofLHC_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]-- Adictof all orbit variables set, and their values as set in theMAD-Xglobals.
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
TWISStable for certain variables at IP locations only. TheSUMMtable will be included as theTfsDataFrame’s header dictionary.- Parameters:
madx (
cpymad.madx.Madx) -- an instanciatedMadxobject. Positional only.columns (
Sequence[str]) -- The variables to be returned, as columns in the DataFrame. Defaults to theDEFAULT_TWISS_COLUMNSconstant.**kwargs -- Any keyword argument that can be given to the
MAD-XTWISScommand, such aschrom,ripken,centre; or starting coordinates for optics functions such asbetx,betyetc.
- Returns:
TfsDataFrame-- ATfsDataFrameof theTWISStable’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
TWISStable for certain variables for one Interaction Region, meaning at the IP and Q1 to Q3 both left and right of the IP. TheSUMMtable will be included as theTfsDataFrame’s header dictionary.- Parameters:
madx (
cpymad.madx.Madx) -- an instanciatedMadxobject. 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 theDEFAULT_TWISS_COLUMNSconstant.**kwargs -- Any keyword argument that can be given to the
MAD-XTWISScommand, such aschrom,ripken,centre; or starting coordinates for optics functions such asbetx,betyetc.
- Returns:
TfsDataFrame-- ATfsDataFrameof theTWISStable’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
Madxobject, will run relevant commands to match chromaticities to the desired target values.Note
This is a wrapper around the
match_tunes_and_chromaticitiesfunction. Refer to its documentation for usage details.- Parameters:
madx (
cpymad.madx.Madx) -- An instanciatedMadxobject.accelerator (
str, optional) -- Name of the accelerator, used to determmine knobs if variables is not given. Automatic determination will only work for theLHCandHLLHC(accepted case insensitively). Defaults toNone, in which case the knobs must be provided explicitly throughvaried_knobs.sequence (
str, optional) -- Name of the sequence to perform the matching for. Defaults toNone, in which case the currently active sequence will be used for the matching.dq1_target (
float, optional) -- Horizontal chromaticity to match to. Defaults toNone, 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 toNone, in which case it will not be a target and will be excluded from the matching.varied_knobs (
Sequence[str], optional) -- The variables names toVARYin theMAD-XMATCHroutine. 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 asLHCorHLLHC, but must be provided otherwise. Defaults toNone.telescopic_squeeze (
bool) --LHCspecific. If set toTrue, uses the(HL)LHCknobs for Telescopic Squeeze configuration. Defaults toTruesincev0.9.0.run3 (
bool) --LHCspecific. If set toTrue, uses theLHCRun 3*_opknobs. Defaults toFalse.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
LHCorHLLHC):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
acceleratorandsequenceparameters default toNone, they can be omitted. In this case the sequence currently in use will be used for the matching, andvaried_knobsmust be provided:matching.match_tunes_and_chromaticities( madx, dq1_target=100, dq2_target=100, varied_knobs=["ksf", "ksd"], # only chroma knobs )
Matching the
lhcb1sequence of theLHClattice 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
Madxobject, will run relevant commands to match tunes to the desired target values.Note
This is a wrapper around the
match_tunes_and_chromaticitiesfunction. Refer to its documentation for usage details.- Parameters:
madx (
cpymad.madx.Madx) -- An instanciatedMadxobject.accelerator (
str, optional) -- Name of the accelerator, used to determmine knobs if variables is not given. Automatic determination will only work for theLHCandHLLHC(accepted case insensitively). Defaults toNone, in which case the knobs must be provided explicitly throughvaried_knobs.sequence (
str, optional) -- Name of the sequence to perform the matching for. Defaults toNone, in which case the currently active sequence will be used for the matching.q1_target (
float, optional) -- Horizontal tune to match to. Defaults toNone, 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 toNone, in which case it will not be a target and will be excluded from the matching.varied_knobs (
Sequence[str], optional) -- The variables names toVARYin theMAD-XMATCHroutine. 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 asLHCorHLLHC, but must be provided otherwise. Defaults toNone.telescopic_squeeze (
bool) --LHCspecific. If set toTrue, uses the(HL)LHCknobs for Telescopic Squeeze configuration. Defaults toTruesincev0.9.0.run3 (
bool) --LHCspecific. If set toTrue, uses theLHCRun 3*_opknobs. Defaults toFalse.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
LHCorHLLHC):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
acceleratorandsequenceparameters default toNone, they can be omitted. In this case the sequence currently in use will be used for the matching, andvaried_knobsmust 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
lhcb1sequence of theLHClattice 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
Madxobject, 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 byMAD-Xto match the targets. This is a convenient wrapper around theMATCHcommand in theMAD-Xprocess. 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()andmatch_chromaticities()functions.Hint
When acting on either the
LHCorHLLHCmachines, 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 instanciatedMadxobject.accelerator (
str, optional) -- Name of the accelerator, used to determmine knobs if variables is not given. Automatic determination will only work for theLHCandHLLHC(accepted case insensitively). Defaults toNone, in which case the knobs must be provided explicitly throughvaried_knobs.sequence (
str, optional) -- Name of the sequence to perform the matching for. Defaults toNone, in which case the currently active sequence will be used for the matching.q1_target (
float, optional) -- Horizontal tune to match to. Defaults toNone, 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 toNone, 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 toNone, 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 toNone, in which case it will not be a target and will be excluded from the matching.varied_knobs (
Sequence[str], optional) -- The variables names toVARYin theMAD-XMATCHroutine. 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 asLHCorHLLHC, but must be provided otherwise. Defaults toNone.telescopic_squeeze (
bool) --LHCspecific. If set toTrue, uses the(HL)LHCknobs for Telescopic Squeeze configuration. Defaults toTruesincev0.9.0.run3 (
bool) --LHCspecific. If set toTrue, uses theLHCRun 3*_opknobs. Defaults toFalse.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
LHCorHLLHC):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
acceleratorandsequenceparameters default toNone, they can be omitted. In this case the sequence currently in use will be used for the matching, andvaried_knobsmust 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
lhcb1sequence of theLHClattice 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
BEAMattributes from theMAD-Xprocess based on the currently defined beam. If no beam has been defined at function call, thenMAD-Xwill return all the default values. See the MAD-X manual for details.- Parameters:
madx (
cpymad.madx.Madx) -- An instanciatedMadxobject. Positional only.- Returns:
MADXBeam-- A validatedMADXBeamobject.
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 relevantPTCcommands used in the process. The result table is returned as aTfsDataFrame, the headers of which are the contents of the internalSUMMtable. This is a heavily refactored version of an initial implementation by Joschua Dilly.Important
The default values used for the
PTC_CREATE_LAYOUTcommand are:model=3(SixTrackmodel),method=4(integration order),nst=3(number of integration steps, a.k.a body slices for elements) andexact=True(use an exact Hamiltonian, not an approximated one). These can be provided as keyword arguments to override them.The
PTC_NORMALcommand is explicitely givenicase=6by 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) andclosedorbit=True(triggers closed orbit calculation). These can also be provided as keyword arguments to override them.- Parameters:
madx (
cpymad.madx.Madx) -- An instanciatedMadxobject. Positional only.order (
int) -- Maximum derivative order coefficient (remember that only 0, 1 or 2 are implemented inPTC). Defaults to 2.file (
Path | str, optional) -- Path to output file. Defaults toNone, which will skip writing the resulting table to disk.fringe (
bool) -- Boolean flag to include fringe field effects in the calculation. Defaults toFalse.**kwargs -- Some parameters for the
PTCuniverse creation can be given as keyword arguments. They aremodel,method,nstandexact(case sensitive). Similarlyicase,no,closed_orbitandnormalcan be given (case sensitively) for thePTC_NORMALcommand. Any remaining keyword argument is transmitted to thePTC_NORMALcommand as given.
- Returns:
tfs.TfsDataFrame-- ATfsDataFramewith the calculated RDTs, and theSUMMtable as headers.
Examples
ampdet_coeffs = get_amplitude_detuning(madx, order=2, closedorbit=True)
One can also specify parameters for the
PTCuniverse and thePTC_NORMALcommand: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 relevantPTCcommands. The result table is returned as aTfsDataFrame, the headers of which are the contents of the internalSUMMtable. This is a heavily refactored version of an initial implementation by Joschua Dilly.Important
The default values used for the
PTC_CREATE_LAYOUTcommand are:model=3(SixTrackmodel),method=4(integration order),nst=3(number of integration steps, a.k.a body slices for elements) andexact=True(use an exact Hamiltonian, not an approximated one). These can be provided as keyword arguments to override them.The
PTC_TWISScommand is explicitely givenicase=6by default in order to enforce 6D calculations (see the MAD-X manual for details), andnormal=Trueto activate calculation of the Normal Form. The normal form analysis result will be stored in an internal table namedNONLINwhich will then be available through the providedMadxinstance. These can also be provided as keyword arguments to override them.- Parameters:
madx (
cpymad.madx.Madx) -- An instanciatedMadxobject. Positional only.order (
int) -- Maximum derivative order coefficient (remember that only 0, 1 or 2 are implemented inPTC). Defaults to 2.file (
Path | str, optional) -- Path to output file. Defaults toNone, which will skip writing the resulting table to disk.fringe (
bool) -- Boolean flag to include fringe field effects in the calculation. Defaults toFalse.**kwargs -- Some parameters for the
PTCuniverse creation can be given as keyword arguments. They aremodel,method,nstandexact(case sensitive). Similarlyicaseandnormalcan be given (case sensitively) for thePTC_TWISScommand. Any remaining keyword argument is transmitted to thePTC_TWISScommand as given.
- Returns:
tfs.TfsDataFrame-- ATfsDataFramewith the calculated RDTs, and theSUMMtable as headers.
Examples
rdts_df = get_rdts(madx, order=3, fringe=True)
One can also specify parameters for the
PTCuniverse and thePTC_TWISScommand: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 oftrack_single_particle.Important
The default values used for the
PTC_CREATE_LAYOUTcommand are:model=3(SixTrackmodel),method=4(integration order),nst=3(number of integration steps, a.k.a body slices for elements) andexact=True(use an exact Hamiltonian, not an approximated one). These can be provided as keyword arguments to override them.The
PTC_TRACKcommand is explicitely givenELEMENT_BY_ELEMENT=Trueby 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
USEcommand will be ran on the provided sequence name. This means the caveats ofUSEapply, for instance the erasing of previously defined errors, orbits corrections etc. In this case a warning will be logged but the function will proceed. IfNoneis given (by default) then the sequence already in use will be the one tracking is performed with.- Parameters:
madx (
cpymad.madx.Madx) -- An instanciatedMadxobject. Positional only.initial_coordinates (
tuple[float,float,float,float,float,float]) -- A tuple with theX, PX, Y, PY, T, PTstarting coordinates of the particle to track. Defaults to all 0 ifNonegiven.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 byMAD-X. Beware of the dangers of giving a sequence that will beuse-d byMAD-X, see the warning above for more information.observation_points (
Sequence[str], optional) -- A sequence of element names at which toOBSERVEduring the tracking.onetable (
bool) -- Flag to combine all observation points data into a single table. Defaults toFalse.fringe (
bool) -- Boolean flag to include fringe field effects in the calculation. Defaults toFalse.**kwargs --
Some parameters for the
PTCuniverse creation can be given as keyword arguments. They aremodel,method,nstandexact(case sensitive). Similarlyelement_by_elementcan be given (case sensitively) for thePTC_TRACKcommand. Any remaining keyword argument is transmitted to thePTC_TRACKcommand, such as theclosed_orbitflag to activate closed orbit calculation before any tracking. Refer to the MAD-X manual for options.
- Returns:
dict[str,pd.DataFrame]-- Adictwith a copy of the track table’s dataframe for each defined observation point, with as columns the coordinatesx, px, y, py, t, pt, s and e(energy). The keys of the dictionary are simply namedobservation_point_1,observation_point_2etc. 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 keytrackoneand it has the combined table as aDataFramefor 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
PTCuniverse: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
TWISSparameters according to the Willeke and Ripken [WR89] formalism viaPTC_TWISS, with sensible defaults set for other relevantPTCcommands. The result table is returned as aTfsDataFrame, the headers of which are the contents of the internalSUMMtable.This is very similar to the
get_rdtsfunction as both usePTC_TWISSinternally, however this function does not track RDTs which makes the calculations significantly faster.Important
The default values used for the
PTC_CREATE_LAYOUTcommand are:model=3(SixTrackmodel),method=4(integration order),nst=3(number of integration steps, a.k.a body slices for elements) andexact=True(use an exact Hamiltonian, not an approximated one). These can be provided as keyword arguments to override them.The
PTC_TWISScommand is explicitely givenicase=6by default in order to enforce 6D calculations (see the MAD-X manual for details), andnormal=Trueto activate calculation of the Normal Form. The normal form analysis result will be stored in an internal table namedNONLINwhich will then be available through the providedMadxinstance. These can also be provided as keyword arguments to override them.- Parameters:
madx (
cpymad.madx.Madx) -- An instanciatedMadxobject. Positional only.order (
int) -- Maximum derivative order coefficient (remember that only 0, 1 or 2 are implemented inPTC). Defaults to 2.file (
Path | str, optional) -- Path to output file. Defaults toNone, which will skip writing the resulting table to disk.fringe (
bool) -- Boolean flag to include fringe field effects in the calculation. Defaults toFalse.**kwargs -- Some parameters for the
PTCuniverse creation can be given as keyword arguments. They aremodel,method,nstandexact(case sensitive). Similarlyicaseandnormalcan be given (case sensitively) for thePTC_TWISScommand. Any remaining keyword argument is transmitted to thePTC_TWISScommand as given.
- Returns:
tfs.TfsDataFrame-- ATfsDataFramewith the calculatedTWISSparameters, and theSUMMtable as headers.
Examples
twiss_ptc_df = ptc_twiss(madx, order=3)
One can also specify parameters for the
PTCuniverse and thePTC_TWISScommand: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
TRACKcommand, 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
USEcommand will be ran on the provided sequence name. This means the caveats ofUSEapply, for instance the erasing of previously defined errors, orbits corrections etc. In this case a warning will be logged but the function will proceed. IfNoneis given (by default) then the sequence already in use will be the one tracking is performed with.- Parameters:
madx (
cpymad.madx.Madx) -- An instantiatedMadxobject. Positional only.initial_coordinates (
tuple[float,float,float,float,float,float]) -- A tuple with theX, PX, Y, PY, T, PTstarting coordinates of the particle to track. Defaults to all 0 ifNonegiven.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 byMAD-X. Beware of the dangers of giving a sequence that will beuse-d byMAD-X, see the warning above for more information.observation_points (
Sequence[str], optional) -- A sequence of element names at which toOBSERVEduring the tracking.**kwargs --
Any keyword argument will be given to the
TRACKcommand, for instanceONETABLEetc. Refer to the MAD-X manual for options.
- Returns:
dict[str,pd.DataFrame]-- Adictwith a copy of the track table’s dataframe for each defined observation point, with as columns the coordinatesx, px, y, py, t, pt, s and e(energy). The keys of the dictionary are simply namedobservation_point_1,observation_point_2etc. 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 keytrackoneand it has the combined table as aDataFramefor 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
TfsDataFrameas is returned by themake_footprint_tablefunction, 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 plottablenumpy.ndarrayobjects.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 bymake_footprint_table.- Returns:
tuple[np.ndarray,np.ndarray]-- The \(Q_x\) and \(Q_y\) data points to plot directly, asndarrayobjects.
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
TfsDataFrameas is returned by themake_footprint_tablefunction, computes the polygon patches needed to plot the tune footprint data, with lines representing the different amplitudes and angles from starting particles, and returns thePatchCollectionwith 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
ANGLEorAMPLITUDEvalues in dynap_dframe headers.- Parameters:
dynap_dframe (
tfs.TfsDataFrame) -- The dynap data frame returned bymake_footprint_table().- Returns:
matplotlib.collections.PatchCollection-- ThePatchCollectionwith 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
DYNAPcommand, lettingMAD-Xinfer their tunes. Particules are instantiated for different angle variables for each amplitude, creating an ensemble able to represent the tune footprint.Warning
Since the
DYNAPcommand makes use of tracking, your sequence needs to be sliced before calling this function.- Parameters:
madx (
cpymad.madx.Madx) -- An instanciatedMadxobject. Positional only.sigma (
float) -- The maximum amplitude of the tracked particles, in bunch \(\sigma\). Defaults to 5.dense (
bool) -- If set toTrue, an increased number of particles will be tracked. Defaults toFalse.file (
str, optional) -- If given, theDYNAPTUNEtable will be exported as aTFSfile with the provided name.cleanup (
bool) -- IfTrue, the fort.69 and lyapunov.data files are cleared before returning theDYNAPTUNEtable. Defaults toTrue.**kwargs -- Any keyword argument will be transmitted to the
DYNAPcommand inMAD-X.
- Returns:
tfs.TfsDataFrame-- The resultingDYNAPTUNEtable, as aTfsDataFrame.
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
TWISStable for desired variables from the providedMadxobject, for elements matching the provided patterns. The table is returned as aTfsDataFrame, the headers of which are the contents of the internalSUMMtable.Note
The
TWISSflag will be fully cleared after running this function.Warning
Although the patterns parameter should accept a regex,
MAD-Xdoes not implement actual regexes. Please refer to the MAD-X manual, sectionRegular Expressionsfor details on what is implemented inMAD-Xitself.- Parameters:
madx (
cpymad.madx.Madx) -- An instanciatedMadxobject. Positional only.columns (
Sequence[str], optional) -- The variables to be returned, as columns in theTfsDataFrame. Defaults toNone, which will return all available columns.patterns (
Sequence[str]) -- The different element patterns (such asMQXorBPM) to be applied to theTWISScommand, which will determine the rows in the returnedTfsDataFrame. Defaults to an empty sequence, which will select all elements.**kwargs -- Any keyword argument that can be given to the
MAD-XTWISScommand, such aschrom,ripken,centre; or starting values forbetx,betyetc.
- Returns:
tfs.TfsDataFrame-- ATfsDataFramewith the selected columns for all elements matching the provided patterns, and the internalSUMMtable 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
TfsDataFramefrom theMadxinstance’sTWISStable, typically in the way we’re used to getting it fromMAD-Xoutputting theTWISS(uppercase names, colnames,SUMMtable in headers). This will call theTWISScommand first before returning the dframe to you.- Parameters:
madx (
cpymad.madx.Madx) -- An instanciatedMadxobject. Positional only.**kwargs -- Any keyword argument that can be given to the
MAD-XTWISScommand, such aschrom,ripken,centre; or starting values forbetx,betyetc.
- Returns:
tfs.TfsDataFrame-- ATfsDataFrameof theTWISStable, with the internalSUMMtable 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-Xprocess into aTfsDataFrameon disk.Important
Tables can only be correctly read back in
MAD-X(throughREADTABLE) if the written file has aNAMEand aTYPEentries 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 instanciatedMadxobject. 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 ofpandas.DataFrame.filter.headers_table (
str) -- The name of the internal table to use for headers. Defaults to using theSUMMtable.**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-Xprocess into aTfsDataFrame.- Parameters:
madx (
cpymad.madx.Madx) -- An instanciatedMadxobject. 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 theSUMMtable.
- Returns:
tfs.frame.TfsDataFrame-- ATfsDataFrameobject with the table_name data, and the desired headers_table (usuallySUMM) as headers.
Example
twiss_tfs = get_table_tfs(madx, table_name="TWISS")