Skip to content

Commit 11875bf

Browse files
authored
Doc tweaks (#96)
1 parent ee85248 commit 11875bf

27 files changed

+247
-77
lines changed

pyhdtoolkit/cpymadtools/coupling.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -191,13 +191,18 @@ def get_cminus_from_coupling_rdts(
191191
The calculated :math:`|C^{-}|` value.
192192
193193
Examples:
194+
195+
To compute the :math:`|C^{-}|` taking in consideration all elements in the sequence:
196+
194197
.. code-block:: python
195198
196199
>>> complex_cminus = get_cminus_from_coupling_rdts(madx)
197200
201+
202+
To simulate the calculation from a measurement, with RDTs computed at BPMs only:
203+
198204
.. code-block:: python
199205
200-
>>> # To simulate the calculation from a measurement, with RDTs at BPMs only
201206
>>> complex_cminus = get_cminus_from_coupling_rdts(madx, patterns=["^BPM.*B[12]$"])
202207
"""
203208
logger.debug(f"Getting coupling RDTs at selected elements thoughout the machine")
@@ -235,7 +240,7 @@ def match_no_coupling_through_ripkens(
235240
madx: Madx, sequence: str = None, location: str = None, vary_knobs: Sequence[str] = None
236241
) -> None:
237242
"""
238-
..versionadded:: 0.16.0
243+
.. versionadded:: 0.16.0
239244
240245
Matching routine to get cross-term Ripken parameters :math:`\\beta_{12}` and :math:`\\beta_{21}`
241246
to be 0 at a given location.

pyhdtoolkit/cpymadtools/errors.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,11 @@ def misalign_lhc_ir_quadrupoles(
139139
.. code-block:: python
140140
141141
>>> misalign_lhc_ir_quadrupoles(
142-
... madx, ips=[5], quadrupoles=[7, 8, 9, 10], beam=1, sides="RL", dpsi="1E-3 + 8E-4 * TGAUSS(2.5)"
142+
... madx, ips=[5],
143+
... quadrupoles=[7, 8, 9, 10],
144+
... beam=1,
145+
... sides="RL",
146+
... dpsi="1E-3 + 8E-4 * TGAUSS(2.5)",
143147
... )
144148
145149
For several error types on the elements, here ``DY`` and ``DPSI``:

pyhdtoolkit/cpymadtools/lhc.py

Lines changed: 30 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ def make_lhc_beams(
4545
energy (float): beam energy, in [GeV]. Defaults to 6500.
4646
emittance_x (float): horizontal emittance in [m]. Will be used to calculate
4747
geometric emittance which is then fed to the ``BEAM`` command.
48-
emittance_x (float): vertical emittance in [m]. Will be used to calculate
48+
emittance_y (float): vertical emittance in [m]. Will be used to calculate
4949
geometric emittance which is then fed to the ``BEAM`` command.
5050
**kwargs: Any keyword argument that can be given to the ``MAD-X`` ``BEAM`` command.
5151
@@ -170,7 +170,7 @@ def apply_lhc_colinearity_knob(madx: Madx, colinearity_knob_value: float = 0, ir
170170
"""
171171
.. versionadded:: 0.15.0
172172
173-
Applies the LHC colinearity knob.
173+
Applies the a trim of the LHC colinearity knob.
174174
175175
.. note::
176176
If you don't know what this is, you really should not be using this function.
@@ -209,7 +209,7 @@ def apply_lhc_colinearity_knob_delta(madx: Madx, colinearity_knob_delta: float =
209209
.. versionadded:: 0.21.0
210210
211211
This is essentially the same as `.apply_lhc_colinearity_knob`, but instead of a applying fixed powering
212-
value, it applies to delta to the existing value.
212+
value, it applies a delta to the (potentially) existing value.
213213
214214
.. note::
215215
If you don't know what this is, you really should not be using this function.
@@ -249,12 +249,12 @@ def apply_lhc_rigidity_waist_shift_knob(
249249
"""
250250
.. versionadded:: 0.15.0
251251
252-
Applies the LHC rigidity waist shift knob, moving the waist left or right of IP.
252+
Applies a trim of the LHC rigidity waist shift knob, moving the waist left or right of IP.
253+
The waist shift is achieved by moving all four betatron waists simltaneously: unbalancing
254+
the triplet powering knobs of the left and right-hand sides of the IP.
253255
254256
.. note::
255-
If you don't know what this is, you really should not be using this function. The waist shift
256-
is achieved by moving all four betatron waists simltaneously: unbalancing the triplet powering
257-
knobs of the left and right-hand sides of the IP,
257+
If you don't know what this is, you really should not be using this function.
258258
259259
.. warning::
260260
Applying the shift will modify your tunes and is likely to flip them, making a subsequent matching
@@ -307,7 +307,7 @@ def apply_lhc_coupling_knob(
307307
"""
308308
.. versionadded:: 0.15.0
309309
310-
Applies the LHC coupling knob to reach the desired :math:`|C^{-}|` value.
310+
Applies a trim of the LHC coupling knob to reach the desired :math:`|C^{-}|` value.
311311
312312
Args:
313313
madx (cpymad.madx.Madx): an instanciated `~cpymad.madx.Madx` object.
@@ -327,7 +327,7 @@ def apply_lhc_coupling_knob(
327327
logger.warning("You should re-match tunes & chromaticities after this coupling knob is applied")
328328
suffix = "_sq" if telescopic_squeeze else ""
329329
# NOTE: Only using this knob will give a dqmin very close to coupling_knob
330-
# If one wants to also assign f"CMIS.b{beam:d}{suffix}" the dqmin be > coupling_knob
330+
# If one wants to also assign f"CMIS.b{beam:d}{suffix}" the dqmin will be > coupling_knob
331331
knob_name = f"CMRS.b{beam:d}{suffix}"
332332

333333
logger.trace(f"Knob '{knob_name}' is {madx.globals[knob_name]} before implementation")
@@ -346,7 +346,7 @@ def carry_colinearity_knob_over(madx: Madx, ir: int, to_left: bool = True) -> No
346346
madx (cpymad.madx.Madx): an instanciated `~cpymad.madx.Madx` object.
347347
ir (int): The Interaction Region around which to apply the change, should be
348348
one of [1, 2, 5, 8].
349-
to_left (bool): If `True`, the magnet right of IP is powered of and its powering
349+
to_left (bool): If `True`, the magnet right of IP is de-powered of and its powering
350350
is transferred to the magnet left of IP. If `False`, then the opposite happens.
351351
Defaults to `True`.
352352
@@ -446,8 +446,9 @@ def vary_independent_ir_quadrupoles(
446446
The independent quadrupoles for which this is implemented are Q4 to Q13 included. This is useful
447447
to setup some specific matching involving these elements.
448448
449-
..important::
450-
It is necessary to have defined a ``brho`` variable when creating your beams.
449+
.. important::
450+
It is necessary to have defined a ``brho`` variable when creating your beams. If one has used
451+
`make_lhc_beams` to create the beams, this has already been done automatically.
451452
452453
Args:
453454
madx (cpymad.madx.Madx): an instanciated `~cpymad.madx.Madx` object.
@@ -827,7 +828,9 @@ def add_markers_around_lhc_ip(madx: Madx, sequence: str, ip: int, n_markers: int
827828
Example:
828829
.. code-block:: python
829830
830-
>>> add_markers_around_lhc_ip(madx, sequence=f"lhcb1", ip=1, n_markers=1000, interval=0.001)
831+
>>> add_markers_around_lhc_ip(
832+
... madx, sequence=f"lhcb1", ip=1, n_markers=1000, interval=0.001
833+
... )
831834
"""
832835
logger.debug(f"Adding {n_markers:d} markers on each side of IP{ip:d}")
833836
madx.command.seqedit(sequence=sequence)
@@ -1011,15 +1014,15 @@ def get_magnets_powering(
10111014
.. note::
10121015
Here are below certain useful patterns for the ``LHC`` and their meaning:
10131016
1014-
* ``^mb\.`` :math:`\\rightarrow` main bends.
1015-
* ``^mq\.`` :math:`\\rightarrow` main quadrupoles.
1016-
* ``^ms\.`` :math:`\\rightarrow` main sextupoles.
1017-
* ``^mb[rswx]`` :math:`\\rightarrow` separation dipoles.
1018-
* ``^mq[mwxy]`` :math:`\\rightarrow` insertion quads.
1019-
* ``^mqt.1[23]`` :math:`\\rightarrow` short tuning quads (12 & 13).
1020-
* ``^mqtl`` :math:`\\rightarrow` long tuning quads.
1021-
* ``^mcbx`` :math:`\\rightarrow` crossing scheme magnets.
1022-
* ``^mcb[cy]`` :math:`\\rightarrow` crossing scheme magnets.
1017+
* ``^mb\.`` :math:`\rightarrow` main bends.
1018+
* ``^mq\.`` :math:`\rightarrow` main quadrupoles.
1019+
* ``^ms\.`` :math:`\rightarrow` main sextupoles.
1020+
* ``^mb[rswx]`` :math:`\rightarrow` separation dipoles.
1021+
* ``^mq[mwxy]`` :math:`\rightarrow` insertion quads.
1022+
* ``^mqt.1[23]`` :math:`\rightarrow` short tuning quads (12 & 13).
1023+
* ``^mqtl`` :math:`\rightarrow` long tuning quads.
1024+
* ``^mcbx`` :math:`\rightarrow` crossing scheme magnets.
1025+
* ``^mcb[cy]`` :math:`\rightarrow` crossing scheme magnets.
10231026
10241027
To make no selection, one can give ``patterns=[""]`` and this will give back
10251028
the results for *all* elements. One can also give a specific magnet's exact
@@ -1043,6 +1046,11 @@ def get_magnets_powering(
10431046
Returns:
10441047
A `~tfs.TfsDataFrame` of the ``TWISS`` table, with the relevant newly defined columns
10451048
and including the elements matching the regex *patterns* that were provided.
1049+
1050+
Example:
1051+
.. code-block:: python
1052+
1053+
>>> sextupoles_powering = get_magnets_powering(madx, patterns=[r"^ms\."])
10461054
"""
10471055
logger.debug("Computing magnets field and powering limits proportions")
10481056
NEW_COLNAMES = ["name", "keyword", "ampere", "imax", "percent", "kn", "kmax", "integrated_field", "L"]

pyhdtoolkit/cpymadtools/matching.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ def match_tunes_and_chromaticities(
116116
... q2_target=60.32,
117117
... dq1_target=2.0,
118118
... dq2_target=2.0,
119-
... telescopic_squeeze=True, # influences the knobs definition
119+
... run3=True, # influences the knobs definition
120120
... )
121121
"""
122122
if accelerator and not varied_knobs:

pyhdtoolkit/cpymadtools/parameters.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,11 @@ def query_beam_attributes(madx: Madx) -> MADXBeam:
3030
3131
Returns:
3232
A validated `~.models.madx.MADXBeam` object.
33+
34+
Example:
35+
.. code-block:: python
36+
37+
>>> beam_parameters = query_beam_attributes(madx)
3338
"""
3439
logger.debug("Retrieving BEAM attributes from the MAD-X process")
3540
return MADXBeam(**dict(madx.beam))

pyhdtoolkit/cpymadtools/setup.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,9 @@ def prepare_lhc_run2(opticsfile: str, beam: int = 1, energy: float = 6500, slice
5050
Example:
5151
.. code-block:: python
5252
53-
>>> madx = prepare_lhc_run2("/afs/cern.ch/eng/lhc/optics/runII/2018/PROTON/opticsfile.22", beam=2, stdout=True)
53+
>>> madx = prepare_lhc_run2(
54+
... "/afs/cern.ch/eng/lhc/optics/runII/2018/PROTON/opticsfile.22", beam=2, stdout=True
55+
... )
5456
"""
5557

5658
def _run2_sequence_from_opticsfile(opticsfile: Path) -> Path:
@@ -112,7 +114,9 @@ def prepare_lhc_run3(opticsfile: str, beam: int = 1, energy: float = 6800, slice
112114
Example:
113115
.. code-block:: python
114116
115-
>>> madx = prepare_lhc_run3("R2022a_A30cmC30cmA10mL200cm.madx", slicefactor=4, stdout=True)
117+
>>> madx = prepare_lhc_run3(
118+
... "R2022a_A30cmC30cmA10mL200cm.madx", slicefactor=4, stdout=True
119+
... )
116120
"""
117121
logger.debug("Creating Run 3 setup MAD-X instance")
118122
echo, warn = kwargs.pop("echo", False), kwargs.pop("warn", False)

pyhdtoolkit/cpymadtools/tune.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
Tune Utilities
55
--------------
66
7-
Module with functions to manipulate to manipulate ``MAD-X`` functionality around the tune through
7+
Module with functions to manipulate ``MAD-X`` functionality around the tune through
88
a `~cpymad.madx.Madx` object.
99
"""
1010
import math
@@ -55,7 +55,7 @@ def make_footprint_table(
5555
>>> dynap_dframe = make_footprint_table(madx)
5656
"""
5757
logger.debug(f"Initiating particules up to {sigma:d} bunch sigma to create a tune footprint table")
58-
small, big = 0.05, math.sqrt(1 - 0.05**2)
58+
small, big = 0.05, math.sqrt(1 - 0.05 ** 2)
5959
sigma_multiplier, angle_multiplier = 0.1, 0.0
6060

6161
logger.debug("Initializing particles")

pyhdtoolkit/cpymadtools/twiss.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
"""
1010
from typing import Sequence
1111

12-
import numpy as np
1312
import tfs
1413

1514
from cpymad.madx import Madx
@@ -70,9 +69,9 @@ def get_pattern_twiss(
7069
>>> triplets_df = get_pattern_twiss(
7170
... madx=madx,
7271
... patterns=[
73-
... f"MQXA.[12345][RL]1", # Q1 and Q3 LHC
74-
... f"MQXB.[AB][12345][RL]1", # Q2A and Q2B LHC
75-
... f"MQXF[AB].[AB][12345][RL]1", # Q1 to Q3 A and B HL-LHC
72+
... r"MQXA.[12345][RL]1", # Q1 and Q3 LHC
73+
... r"MQXB.[AB][12345][RL]1", # Q2A and Q2B LHC
74+
... r"MQXF[AB].[AB][12345][RL]1", # Q1 to Q3 A and B HL-LHC
7675
... ],
7776
... )
7877
"""

pyhdtoolkit/cpymadtools/utils.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,12 @@ def export_madx_table(
3939
headers_table (str): the name of the internal table to use for headers.
4040
Defaults to ``SUMM``.
4141
**kwargs: any keyword arguments will be passed to `~tfs.writer.write_tfs`.
42+
43+
Example:
44+
.. code-block:: python
45+
46+
>>> madx.command.twiss()
47+
>>> export_madx_table(madx, table_name="TWISS", file_name="twiss.tfs")
4248
"""
4349
file_path = Path(file_name)
4450
logger.debug(f"Exporting table {table_name} into '{file_path.absolute()}'")

pyhdtoolkit/maths/stats_fitting.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,8 @@ def set_distributions_dict(dist_dict: Dict[st.rv_continuous, str]) -> None:
3434
.. versionadded:: 0.5.0
3535
3636
Sets ``DISTRIBUTIONS`` as the provided `dict`. This allows the user to define the
37-
distributions to try and fit against the data.
37+
distributions to try and fit against the data. One can find an example use of this
38+
function in the :ref:`gallery <demo-distributions-fitting>`.
3839
3940
Args:
4041
dist_dict (Dict[st.rv_continuous, str]): dictionnary with the wanted distributions,
@@ -131,7 +132,8 @@ def make_pdf(distribution: st.rv_continuous, params: Tuple[float, ...], size: in
131132
.. versionadded:: 0.5.0
132133
133134
Generates a `pandas.Series` for the distributions's Probability Distribution Function.
134-
This Series will have axis values as index, and PDF values as column.
135+
This Series will have axis values as index, and PDF values as column. One can find an
136+
example use of this function in the :ref:`gallery <demo-distributions-fitting>`.
135137
136138
Args:
137139
distribution (st.rv_continuous): a `scipy.stats` generator.

pyhdtoolkit/optics/beam.py

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,9 @@ def compute_beam_parameters(pc_gev: float, en_x_m: float, en_y_m: float, deltap_
1717
"""
1818
.. versionadded:: 0.12.0
1919
20-
Calculates beam parameters from provided values, for *proton* particles.
20+
Calculates beam parameters from provided values, for *proton* particles. One can find
21+
an example use of this function in the :ref:`beam enveloppe <demo-beam-enveloppe>`
22+
example gallery.
2123
2224
Args:
2325
pc_gev (float): particle momentum, in [GeV].
@@ -27,11 +29,29 @@ def compute_beam_parameters(pc_gev: float, en_x_m: float, en_y_m: float, deltap_
2729
2830
Returns:
2931
A `~.optics.beam.BeamParameters` object with the calculated values.
32+
33+
Example:
34+
.. code-block:: python
35+
36+
>>> params = compute_beam_parameters(1.9, 5e-6, 5e-6, 2e-3)
37+
>>> print(params)
38+
Beam Parameters for particle of charge 1
39+
Beam momentum = 1.900 GeV/c
40+
Normalized x-emittance = 5.000 mm mrad
41+
Normalized y-emittance = 5.000 mm mrad
42+
Momentum deviation deltap/p = 0.002
43+
-> Beam total energy = 2.119 GeV
44+
-> Beam kinetic energy = 1.181 GeV
45+
-> Beam rigidity = 6.333 Tm
46+
-> Relativistic beta = 0.89663
47+
-> Relativistic gamma = 2.258
48+
-> Geometrical x emittance = 2.469 mm mrad
49+
-> Geometrical y emittance = 2.469 mm mrad
3050
"""
3151
e0_gev = 0.9382720813
32-
e_tot_gev = np.sqrt(pc_gev**2 + e0_gev**2)
52+
e_tot_gev = np.sqrt(pc_gev ** 2 + e0_gev ** 2)
3353
gamma_r = e_tot_gev / e0_gev
34-
beta_r = pc_gev / np.sqrt(pc_gev**2 + e0_gev**2)
54+
beta_r = pc_gev / np.sqrt(pc_gev ** 2 + e0_gev ** 2)
3555

3656
return BeamParameters(
3757
pc_GeV=pc_gev,
@@ -80,7 +100,7 @@ def gamma_rel(self) -> float:
80100
@property
81101
def beta_rel(self) -> float:
82102
"""Relativistic beta."""
83-
return np.sqrt(1 + 1 / (self.gamma_rel**2))
103+
return np.sqrt(1 + 1 / (self.gamma_rel ** 2))
84104

85105
@property
86106
def brho(self) -> float:
@@ -123,7 +143,7 @@ def eta(self, alpha_p: float) -> float:
123143
Returns:
124144
The slip factor.
125145
"""
126-
return (1 / (self.gamma_rel**2)) - alpha_p
146+
return (1 / (self.gamma_rel ** 2)) - alpha_p
127147

128148
@staticmethod
129149
def gamma_transition(alpha_p: float) -> float:

pyhdtoolkit/optics/twiss.py

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,20 @@
1010

1111

1212
def courant_snyder_transform(u_vector: np.ndarray, alpha: float, beta: float) -> np.ndarray:
13-
"""
13+
r"""
1414
.. versionadded:: 0.5.0
1515
1616
Perform the Courant-Snyder transform on regular (nonchaotic) phase-space coordinates.
1717
Specifically, if considering the horizontal plane and noting :math:`U = (x, px)` the
18-
phase-space vector, it returns :math:`\\bar{U} = (\\bar{x}, \\bar{px})` according to
19-
the transform :math:`\\bar{U} = P \\cdot U`, where::
18+
phase-space vector, it returns :math:`\bar{U} = (\bar{x}, \bar{px})` according to
19+
the transform :math:`\bar{U} = P \cdot U`, where
20+
21+
.. math::
2022
21-
P = [1/sqrt(beta_x) 0 ]
22-
[alpha_x/sqrt(beta_x) sqrt(beta_x)]
23+
P = \begin{pmatrix}
24+
\frac{1}{\sqrt{\beta_x}} & 0 \\
25+
\frac{\alpha_x}{\sqrt{\beta_x}} & \sqrt{\beta_x} \\
26+
\end{pmatrix}
2327
2428
Args:
2529
u_vector (np.ndarray): two-dimentional array of phase-space (spatial and momenta)
@@ -29,6 +33,14 @@ def courant_snyder_transform(u_vector: np.ndarray, alpha: float, beta: float) ->
2933
3034
Returns:
3135
The normalized phase-space coordinates from the Courant-Snyder transform.
36+
37+
Example:
38+
.. code-block:: python
39+
40+
>>> alfx = madx.table.twiss.alfx[0]
41+
>>> betx = madx.table.twiss.betx[0]
42+
>>> u = np.array([x_coords, px_coord])
43+
>>> u_bar = courant_snyder_transform(u, alfx, betx)
3244
"""
3345
p_matrix = np.array([[1 / np.sqrt(beta), 0], [alpha / np.sqrt(beta), np.sqrt(beta)]])
3446
return p_matrix @ u_vector

0 commit comments

Comments
 (0)