Skip to content

Commit e7065e3

Browse files
authored
Ruff (#103)
1 parent 818a053 commit e7065e3

30 files changed

+69
-126
lines changed

docs/conf.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,11 @@
1414
import sys
1515
import warnings
1616

17+
from sphinx_gallery.scrapers import matplotlib_scraper
18+
from sphinx_gallery.sorting import ExampleTitleSortKey
19+
20+
import pyhdtoolkit
21+
1722
# ignore numpy warnings, see:
1823
# https://stackoverflow.com/questions/40845304/runtimewarning-numpy-dtype-size-changed-may-indicate-binary-incompatibility
1924
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
@@ -31,11 +36,6 @@
3136
if str(TOPLEVEL_DIR) not in sys.path:
3237
sys.path.insert(0, str(TOPLEVEL_DIR))
3338

34-
from sphinx_gallery.scrapers import matplotlib_scraper
35-
from sphinx_gallery.sorting import ExampleTitleSortKey
36-
37-
import pyhdtoolkit
38-
3939
# This is to tell Sphinx how to print some specific type annotations
4040
# See: https://stackoverflow.com/a/67483317
4141
# See: https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html#confval-autodoc_type_aliases

examples/demo_lhc_rigid_waist_shift.py

+9-9
Original file line numberDiff line numberDiff line change
@@ -179,12 +179,12 @@
179179
madx.call("acc-models-lhc/lhc.seq")
180180
lhc.make_lhc_beams(madx, energy=6800)
181181
madx.call("acc-models-lhc/operation/optics/R2022a_A30cmC30cmA10mL200cm.madx")
182-
madx.command.use(sequence=f"lhcb1")
182+
madx.command.use(sequence="lhcb1")
183183

184-
lhc.re_cycle_sequence(madx, sequence=f"lhcb1", start=f"MSIA.EXIT.B1")
185-
madx.command.use(sequence=f"lhcb1")
186-
lhc.make_lhc_thin(madx, sequence=f"lhcb1", slicefactor=4)
187-
lhc.add_markers_around_lhc_ip(madx, sequence=f"lhcb1", ip=1, n_markers=1000, interval=0.001)
184+
lhc.re_cycle_sequence(madx, sequence="lhcb1", start="MSIA.EXIT.B1")
185+
madx.command.use(sequence="lhcb1")
186+
lhc.make_lhc_thin(madx, sequence="lhcb1", slicefactor=4)
187+
lhc.add_markers_around_lhc_ip(madx, sequence="lhcb1", ip=1, n_markers=1000, interval=0.001)
188188
madx.command.twiss()
189189
initial_twiss = madx.table.twiss.dframe()
190190

@@ -206,7 +206,7 @@
206206

207207
initial_twiss.name = initial_twiss.name.apply(lambda x: x[:-2])
208208
twiss_df.name = twiss_df.name.apply(lambda x: x[:-2])
209-
ip_s = twiss_df.s[f"ip1"]
209+
ip_s = twiss_df.s["ip1"]
210210
slimits = (ip_s - 10, ip_s + 10)
211211

212212
around_ip = twiss_df[twiss_df.s.between(*slimits)]
@@ -285,12 +285,12 @@
285285
# Manipulating the equation to determine the waist yields:
286286
# :math:`w = L^{*} - \sqrt{\beta_0 \beta_w - \beta_w^2}`
287287

288-
q1_right_s = twiss_df[twiss_df.name.str.contains(f"mqxa.1r1")].s[0] # to calculate from the right Q1
289-
q1_left_s = twiss_df[twiss_df.name.str.contains(f"mqxa.1l1")].s[-1] # to calculate from the left Q1
288+
q1_right_s = twiss_df[twiss_df.name.str.contains("mqxa.1r1")].s[0] # to calculate from the right Q1
289+
q1_left_s = twiss_df[twiss_df.name.str.contains("mqxa.1l1")].s[-1] # to calculate from the left Q1
290290

291291
L_star = ip_s - q1_left_s # we calculate from left Q1
292292
# beta0 = twiss_df[twiss_df.name.str.contains(f"mqxa.1r1")].betx[0] # to calculate from the right
293-
beta0 = twiss_df[twiss_df.name.str.contains(f"mqxa.1l1")].betx[-1] # to calculate from the left
293+
beta0 = twiss_df[twiss_df.name.str.contains("mqxa.1l1")].betx[-1] # to calculate from the left
294294
betaw = around_ip.betx.min()
295295

296296
###############################################################################

examples/demo_lhc_setup.py

-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
"""
1616
# sphinx_gallery_thumbnail_number = 3
1717
import matplotlib.pyplot as plt
18-
import numpy as np
1918

2019
from pyhdtoolkit.cpymadtools import coupling, lhc, twiss
2120
from pyhdtoolkit.plotting.aperture import plot_physical_apertures

examples/demo_stats_fitting.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ def chi_dist(num: int, meas_used: int) -> np.ndarray:
147147
best_fit_func, best_fit_params = fitting.best_fit_distribution(data, 200, ax)
148148
ax.set_ylim(data_y_lim)
149149

150-
ax.set_title(f"All Fitted Distributions")
150+
ax.set_title("All Fitted Distributions")
151151
ax.set_ylabel("Normed Hist Counts")
152152
plt.legend()
153153
plt.show()
@@ -188,7 +188,7 @@ def chi_dist(num: int, meas_used: int) -> np.ndarray:
188188
fontsize=25,
189189
)
190190
plt.vlines(pdf.idxmax(), ymin=0, ymax=max(pdf.to_numpy()), linestyles="--", color="indianred")
191-
ax.set_title(f"Best fit to distribution:\n" + dist_str)
191+
ax.set_title("Best fit to distribution:\n" + dist_str)
192192
ax.set_ylabel("Normed Hist Counts")
193193
ax.set_xlabel("x")
194194
ax.legend()
@@ -242,7 +242,7 @@ def chi_dist(num: int, meas_used: int) -> np.ndarray:
242242
# Find best fit candidate
243243
best_fit_func, best_fit_params = fitting.best_fit_distribution(chi_data, 200, ac)
244244
ac.set_ylim(dataYLim)
245-
ac.set_title(f"All Fitted Distributions")
245+
ac.set_title("All Fitted Distributions")
246246
ac.set_ylabel("Normed Hist Counts")
247247
plt.legend()
248248

pyhdtoolkit/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
:copyright: (c) 2019-2020 by Felix Soubelet.
88
:license: MIT, see LICENSE for more details.
99
"""
10-
from . import cpymadtools, maths, models, optics, plotting, utils, version
10+
from . import cpymadtools, maths, models, optics, plotting, utils, version # noqa: F401
1111

1212
__title__ = "pyhdtoolkit"
1313
__description__ = "An all-in-one toolkit package to easy my Python work in my PhD."

pyhdtoolkit/cpymadtools/coupling.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,7 @@ def get_cminus_from_coupling_rdts(
201201
202202
>>> complex_cminus = get_cminus_from_coupling_rdts(madx, patterns=["^BPM.*B[12]$"])
203203
"""
204-
logger.debug(f"Getting coupling RDTs at selected elements thoughout the machine")
204+
logger.debug("Getting coupling RDTs at selected elements thoughout the machine")
205205
twiss_with_rdts = get_pattern_twiss(madx, patterns=patterns, columns=MONITOR_TWISS_COLUMNS)
206206
twiss_with_rdts.columns = twiss_with_rdts.columns.str.upper() # optics_functions needs capitalized names
207207
twiss_with_rdts[["F1001", "F1010"]] = coupling_via_cmatrix(twiss_with_rdts, output=["rdts"])

pyhdtoolkit/cpymadtools/lhc/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
from pyhdtoolkit.cpymadtools.lhc._setup import LHCSetup
2929
# use this now
3030
"""
31-
from ._coupling import correct_lhc_global_coupling, get_lhc_bpms_twiss_and_rdts
31+
from ._coupling import get_lhc_bpms_twiss_and_rdts
3232
from ._elements import add_markers_around_lhc_ip, install_ac_dipole_as_kicker, install_ac_dipole_as_matrix
3333
from ._errors import misalign_lhc_ir_quadrupoles, misalign_lhc_triplets
3434
from ._misc import (

pyhdtoolkit/cpymadtools/lhc/_elements.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -209,8 +209,8 @@ def install_ac_dipole_as_matrix(madx: Madx, /, deltaqx: float, deltaqy: float, b
209209
madx.input(f"vacmap43 = 2 * (cos(2*pi*{q2_dipole}) - cos(2*pi*{q2})) / (betyac * sin(2*pi*{q2}));")
210210

211211
logger.debug("Defining matrix elements for transverse planes")
212-
madx.input(f"hacmap: matrix, l=0, rm21=hacmap21;")
213-
madx.input(f"vacmap: matrix, l=0, rm43=vacmap43;")
212+
madx.input("hacmap: matrix, l=0, rm21=hacmap21;")
213+
madx.input("vacmap: matrix, l=0, rm43=vacmap43;")
214214

215215
logger.debug(f"Installing AC Dipole matrix with driven tunes of Qx_D = {q1_dipole:.5f} | Qy_D = {q2_dipole:.5f}")
216216
madx.command.seqedit(sequence=f"lhcb{beam:d}")

pyhdtoolkit/cpymadtools/lhc/_routines.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
1-
import numpy as np
2-
31
"""
42
.. _lhc-routines:
53
64
**Routine Utilities**
75
86
The functions below are routines mimicking manipulations that would be done in the ``LHC``.
97
"""
8+
import numpy as np
109
import tfs
1110

1211
from cpymad.madx import Madx

pyhdtoolkit/cpymadtools/matching.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
77
Module with functions to perform ``MAD-X`` matchings through a `~cpymad.madx.Madx` object.
88
"""
9-
from typing import Dict, Optional, Sequence, Tuple
9+
from typing import Optional, Sequence
1010

1111
from cpymad.madx import Madx
1212
from loguru import logger

pyhdtoolkit/cpymadtools/ptc.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -315,7 +315,7 @@ def ptc_twiss(
315315
icase = kwargs.pop("icase", 6)
316316
normal = kwargs.pop("normal", True)
317317

318-
logger.debug(f"Creating PTC universe")
318+
logger.debug("Creating PTC universe")
319319
madx.ptc_create_universe()
320320

321321
logger.trace("Creating PTC layout")
@@ -448,7 +448,7 @@ def ptc_track_particle(
448448
logger.debug(f"Using sequence '{sequence}' for tracking")
449449
madx.use(sequence=sequence)
450450

451-
logger.debug(f"Creating PTC universe")
451+
logger.debug("Creating PTC universe")
452452
madx.ptc_create_universe()
453453

454454
logger.trace("Creating PTC layout")

pyhdtoolkit/cpymadtools/tune.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,7 @@ def get_footprint_patches(dynap_dframe: tfs.TfsDataFrame) -> matplotlib.collecti
203203
"Cannot group tune points according to starting angles and amplitudes. Try changing "
204204
"the 'AMPLITUDE' value in the provided TfsDataFrame's headers."
205205
)
206-
raise
206+
raise tune_grouping_error
207207

208208
logger.debug("Determining polygon vertices")
209209
sx = A.shape[0] - 1

pyhdtoolkit/cpymadtools/twiss.py

+1
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ def get_pattern_twiss(
7676
... ],
7777
... )
7878
"""
79+
columns = columns or DEFAULT_TWISS_COLUMNS
7980
logger.trace("Clearing 'TWISS' flag")
8081
madx.select(flag="twiss", clear=True)
8182

pyhdtoolkit/cpymadtools/utils.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -60,10 +60,10 @@ def export_madx_table(
6060
logger.debug(f"Setting NAME column as index and filtering extracted table with regex pattern '{pattern}'")
6161
dframe = dframe.set_index("NAME").filter(regex=pattern, axis="index").reset_index()
6262
if "NAME" not in dframe.headers:
63-
logger.debug(f"No 'NAME' header found, adding a default value 'EXPORT'")
63+
logger.debug("No 'NAME' header found, adding a default value 'EXPORT'")
6464
dframe.headers["NAME"] = "EXPORT"
6565
if "TYPE" not in dframe.headers:
66-
logger.debug(f"No 'TYPE' header found, adding a default value 'EXPORT'")
66+
logger.debug("No 'TYPE' header found, adding a default value 'EXPORT'")
6767
dframe.headers["TYPE"] = "EXPORT"
6868
logger.debug("Writing to disk")
6969
tfs.write(file_path, dframe, **kwargs)

pyhdtoolkit/maths/stats_fitting.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
from typing import Dict, Tuple, Union
1212

1313
import matplotlib
14-
import matplotlib.pyplot as plt # if omitted, get AttributeError: module 'matplotlib' has no attribute 'axes'
14+
import matplotlib.pyplot as plt # noqa: F401 | if omitted, get AttributeError: module 'matplotlib' has no attribute 'axes'
1515
import numpy as np
1616
import pandas as pd
1717
import scipy.stats as st

pyhdtoolkit/models/beam.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -79,4 +79,4 @@ def __repr__(self) -> str:
7979
)
8080

8181
def __str__(self) -> str:
82-
return f""
82+
return ""

pyhdtoolkit/optics/ripken.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ def _beam_size(coordinates_distribution: np.ndarray, method: str = "std") -> flo
8080
return coordinates_distribution.std()
8181
elif method == "rms":
8282
return np.sqrt(np.mean(np.square(coordinates_distribution)))
83-
raise NotImplementedError(f"Invalid method provided")
83+
raise NotImplementedError("Invalid method provided")
8484

8585

8686
def _add_beam_size_to_df(df: tfs.TfsDataFrame, geom_emit_x: float, geom_emit_y: float) -> tfs.TfsDataFrame:

pyhdtoolkit/plotting/aperture.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ def plot_aperture(
148148
aperture_df = aperture_df[aperture_df.s.between(*xlimits)] if xlimits else aperture_df
149149

150150
# Create a subplot for the lattice patches (takes a third of figure)
151-
figure = plt.gcf()
151+
# figure = plt.gcf()
152152
quadrupole_patches_axis = plt.subplot2grid((3, 3), (0, 0), colspan=3, rowspan=1)
153153
plot_machine_layout(
154154
madx,
@@ -246,7 +246,7 @@ def plot_physical_apertures(
246246
logger.error(f"'plane' argument should be 'x', 'horizontal', 'y' or 'vertical' not '{plane}'")
247247
raise ValueError("Invalid 'plane' argument.")
248248

249-
logger.debug(f"Plotting real element apertures")
249+
logger.debug("Plotting real element apertures")
250250
axis, kwargs = maybe_get_ax(**kwargs)
251251

252252
if xlimits is not None:

pyhdtoolkit/plotting/crossing.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ def plot_two_lhc_ips_crossings(
8383

8484
# ----- Plotting figure ----- #
8585
logger.debug(f"Plotting crossing schemes for IP{first_ip} and IP{second_ip}")
86-
figure = plt.gcf()
86+
# figure = plt.gcf()
8787
first_ip_x_axis = plt.subplot2grid((2, 2), (0, 0), colspan=1, rowspan=1)
8888
first_ip_y_axis = plt.subplot2grid((2, 2), (1, 0), colspan=1, rowspan=1)
8989
second_ip_x_axis = plt.subplot2grid((2, 2), (0, 1), colspan=1, rowspan=1)

pyhdtoolkit/plotting/lattice.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ def plot_latwiss(
146146
xlimits = (twiss_df.s.min(), twiss_df.s.max()) if xlimits is None else xlimits
147147

148148
# Create a subplot for the lattice patches (takes a third of figure)
149-
figure = plt.gcf()
149+
# figure = plt.gcf()
150150
quadrupole_patches_axis = plt.subplot2grid((3, 3), (0, 0), colspan=3, rowspan=1)
151151
plot_machine_layout(
152152
madx,

pyhdtoolkit/plotting/sbs/coupling.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,6 @@ def _plot_sbs_coupling_rdt_component(
263263
)
264264
if model_df is not None and isinstance(model_df, tfs.TfsDataFrame):
265265
# If model dataframe is given, find S location of IP and highlight it
266-
logger.debug(f"Plotting the IP location in the segment.")
266+
logger.debug("Plotting the IP location in the segment.")
267267
ips = find_ip_s_from_segment_start(segment_df=segment_df, model_df=model_df, ip=ip)
268268
ax.axvline(ips, ls="--", color="grey")

pyhdtoolkit/plotting/sbs/phase.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,8 @@ def plot_phase_segment_one_beam(
5252
... sbs_phasex, sbs_phasey, model=b2_model_tfs, ip=5, figsize=(8, 8)
5353
... )
5454
"""
55-
logger.debug(f"Plotting the phase for both planes over the segment.")
56-
legend_bbox_to_anchor = kwargs.pop("bbox_to_anchor", (0.535, 0.97))
55+
logger.debug("Plotting the phase for both planes over the segment.")
56+
# legend_bbox_to_anchor = kwargs.pop("bbox_to_anchor", (0.535, 0.97))
5757
figure, (ax1, ax2) = plt.subplots(2, 1, **kwargs)
5858

5959
plot_phase_segment(ax1, segment_df=phase_x, model_df=model, plane="x", ip=ip)
@@ -118,7 +118,7 @@ def plot_phase_segment_both_beams(
118118
... bbox_to_anchor=(0.535, 0.94),
119119
... )
120120
"""
121-
logger.debug(f"Plotting the phase for both planes over the segment.")
121+
logger.debug("Plotting the phase for both planes over the segment.")
122122
legend_bbox_to_anchor = kwargs.pop("bbox_to_anchor", (0.535, 0.97))
123123
figure, ((b1x, b2x), (b1y, b2y)) = plt.subplots(2, 2, sharex=True, sharey="row", **kwargs)
124124

@@ -212,6 +212,6 @@ def plot_phase_segment(
212212
)
213213
if model_df is not None and isinstance(model_df, tfs.TfsDataFrame):
214214
# If model dataframe is given, find S location of IP and highlight it
215-
logger.debug(f"Plotting the IP location in the segment.")
215+
logger.debug("Plotting the IP location in the segment.")
216216
ips = find_ip_s_from_segment_start(segment_df=segment_df, model_df=model_df, ip=ip)
217217
ax.axvline(ips, ls="--", color="grey")

0 commit comments

Comments
 (0)