diff --git a/docs/conf.py b/docs/conf.py index 44f89ecf..42453122 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -14,6 +14,11 @@ import sys import warnings +from sphinx_gallery.scrapers import matplotlib_scraper +from sphinx_gallery.sorting import ExampleTitleSortKey + +import pyhdtoolkit + # ignore numpy warnings, see: # https://stackoverflow.com/questions/40845304/runtimewarning-numpy-dtype-size-changed-may-indicate-binary-incompatibility warnings.filterwarnings("ignore", message="numpy.dtype size changed") @@ -31,11 +36,6 @@ if str(TOPLEVEL_DIR) not in sys.path: sys.path.insert(0, str(TOPLEVEL_DIR)) -from sphinx_gallery.scrapers import matplotlib_scraper -from sphinx_gallery.sorting import ExampleTitleSortKey - -import pyhdtoolkit - # This is to tell Sphinx how to print some specific type annotations # See: https://stackoverflow.com/a/67483317 # See: https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html#confval-autodoc_type_aliases diff --git a/examples/demo_lhc_rigid_waist_shift.py b/examples/demo_lhc_rigid_waist_shift.py index 0114ae1e..3d114be0 100755 --- a/examples/demo_lhc_rigid_waist_shift.py +++ b/examples/demo_lhc_rigid_waist_shift.py @@ -179,12 +179,12 @@ madx.call("acc-models-lhc/lhc.seq") lhc.make_lhc_beams(madx, energy=6800) madx.call("acc-models-lhc/operation/optics/R2022a_A30cmC30cmA10mL200cm.madx") - madx.command.use(sequence=f"lhcb1") + madx.command.use(sequence="lhcb1") - lhc.re_cycle_sequence(madx, sequence=f"lhcb1", start=f"MSIA.EXIT.B1") - madx.command.use(sequence=f"lhcb1") - lhc.make_lhc_thin(madx, sequence=f"lhcb1", slicefactor=4) - lhc.add_markers_around_lhc_ip(madx, sequence=f"lhcb1", ip=1, n_markers=1000, interval=0.001) + lhc.re_cycle_sequence(madx, sequence="lhcb1", start="MSIA.EXIT.B1") + madx.command.use(sequence="lhcb1") + lhc.make_lhc_thin(madx, sequence="lhcb1", slicefactor=4) + lhc.add_markers_around_lhc_ip(madx, sequence="lhcb1", ip=1, n_markers=1000, interval=0.001) madx.command.twiss() initial_twiss = madx.table.twiss.dframe() @@ -206,7 +206,7 @@ initial_twiss.name = initial_twiss.name.apply(lambda x: x[:-2]) twiss_df.name = twiss_df.name.apply(lambda x: x[:-2]) -ip_s = twiss_df.s[f"ip1"] +ip_s = twiss_df.s["ip1"] slimits = (ip_s - 10, ip_s + 10) around_ip = twiss_df[twiss_df.s.between(*slimits)] @@ -285,12 +285,12 @@ # Manipulating the equation to determine the waist yields: # :math:`w = L^{*} - \sqrt{\beta_0 \beta_w - \beta_w^2}` -q1_right_s = twiss_df[twiss_df.name.str.contains(f"mqxa.1r1")].s[0] # to calculate from the right Q1 -q1_left_s = twiss_df[twiss_df.name.str.contains(f"mqxa.1l1")].s[-1] # to calculate from the left Q1 +q1_right_s = twiss_df[twiss_df.name.str.contains("mqxa.1r1")].s[0] # to calculate from the right Q1 +q1_left_s = twiss_df[twiss_df.name.str.contains("mqxa.1l1")].s[-1] # to calculate from the left Q1 L_star = ip_s - q1_left_s # we calculate from left Q1 # beta0 = twiss_df[twiss_df.name.str.contains(f"mqxa.1r1")].betx[0] # to calculate from the right -beta0 = twiss_df[twiss_df.name.str.contains(f"mqxa.1l1")].betx[-1] # to calculate from the left +beta0 = twiss_df[twiss_df.name.str.contains("mqxa.1l1")].betx[-1] # to calculate from the left betaw = around_ip.betx.min() ############################################################################### diff --git a/examples/demo_lhc_setup.py b/examples/demo_lhc_setup.py index 1eab3590..e8d4aaa3 100644 --- a/examples/demo_lhc_setup.py +++ b/examples/demo_lhc_setup.py @@ -15,7 +15,6 @@ """ # sphinx_gallery_thumbnail_number = 3 import matplotlib.pyplot as plt -import numpy as np from pyhdtoolkit.cpymadtools import coupling, lhc, twiss from pyhdtoolkit.plotting.aperture import plot_physical_apertures diff --git a/examples/demo_stats_fitting.py b/examples/demo_stats_fitting.py index bddee0a9..e9dfa89d 100755 --- a/examples/demo_stats_fitting.py +++ b/examples/demo_stats_fitting.py @@ -147,7 +147,7 @@ def chi_dist(num: int, meas_used: int) -> np.ndarray: best_fit_func, best_fit_params = fitting.best_fit_distribution(data, 200, ax) ax.set_ylim(data_y_lim) -ax.set_title(f"All Fitted Distributions") +ax.set_title("All Fitted Distributions") ax.set_ylabel("Normed Hist Counts") plt.legend() plt.show() @@ -188,7 +188,7 @@ def chi_dist(num: int, meas_used: int) -> np.ndarray: fontsize=25, ) plt.vlines(pdf.idxmax(), ymin=0, ymax=max(pdf.to_numpy()), linestyles="--", color="indianred") -ax.set_title(f"Best fit to distribution:\n" + dist_str) +ax.set_title("Best fit to distribution:\n" + dist_str) ax.set_ylabel("Normed Hist Counts") ax.set_xlabel("x") ax.legend() @@ -242,7 +242,7 @@ def chi_dist(num: int, meas_used: int) -> np.ndarray: # Find best fit candidate best_fit_func, best_fit_params = fitting.best_fit_distribution(chi_data, 200, ac) ac.set_ylim(dataYLim) -ac.set_title(f"All Fitted Distributions") +ac.set_title("All Fitted Distributions") ac.set_ylabel("Normed Hist Counts") plt.legend() diff --git a/pyhdtoolkit/__init__.py b/pyhdtoolkit/__init__.py index 483bef54..4fd3ca37 100644 --- a/pyhdtoolkit/__init__.py +++ b/pyhdtoolkit/__init__.py @@ -7,7 +7,7 @@ :copyright: (c) 2019-2020 by Felix Soubelet. :license: MIT, see LICENSE for more details. """ -from . import cpymadtools, maths, models, optics, plotting, utils, version +from . import cpymadtools, maths, models, optics, plotting, utils, version # noqa: F401 __title__ = "pyhdtoolkit" __description__ = "An all-in-one toolkit package to easy my Python work in my PhD." diff --git a/pyhdtoolkit/cpymadtools/coupling.py b/pyhdtoolkit/cpymadtools/coupling.py index 54abbfae..1e34df49 100644 --- a/pyhdtoolkit/cpymadtools/coupling.py +++ b/pyhdtoolkit/cpymadtools/coupling.py @@ -201,7 +201,7 @@ def get_cminus_from_coupling_rdts( >>> complex_cminus = get_cminus_from_coupling_rdts(madx, patterns=["^BPM.*B[12]$"]) """ - logger.debug(f"Getting coupling RDTs at selected elements thoughout the machine") + logger.debug("Getting coupling RDTs at selected elements thoughout the machine") twiss_with_rdts = get_pattern_twiss(madx, patterns=patterns, columns=MONITOR_TWISS_COLUMNS) twiss_with_rdts.columns = twiss_with_rdts.columns.str.upper() # optics_functions needs capitalized names twiss_with_rdts[["F1001", "F1010"]] = coupling_via_cmatrix(twiss_with_rdts, output=["rdts"]) diff --git a/pyhdtoolkit/cpymadtools/lhc/__init__.py b/pyhdtoolkit/cpymadtools/lhc/__init__.py index 6880f968..b2c5cfe6 100644 --- a/pyhdtoolkit/cpymadtools/lhc/__init__.py +++ b/pyhdtoolkit/cpymadtools/lhc/__init__.py @@ -28,7 +28,7 @@ from pyhdtoolkit.cpymadtools.lhc._setup import LHCSetup # use this now """ -from ._coupling import correct_lhc_global_coupling, get_lhc_bpms_twiss_and_rdts +from ._coupling import get_lhc_bpms_twiss_and_rdts from ._elements import add_markers_around_lhc_ip, install_ac_dipole_as_kicker, install_ac_dipole_as_matrix from ._errors import misalign_lhc_ir_quadrupoles, misalign_lhc_triplets from ._misc import ( diff --git a/pyhdtoolkit/cpymadtools/lhc/_elements.py b/pyhdtoolkit/cpymadtools/lhc/_elements.py index 1f20e2d0..16e59a25 100644 --- a/pyhdtoolkit/cpymadtools/lhc/_elements.py +++ b/pyhdtoolkit/cpymadtools/lhc/_elements.py @@ -209,8 +209,8 @@ def install_ac_dipole_as_matrix(madx: Madx, /, deltaqx: float, deltaqy: float, b madx.input(f"vacmap43 = 2 * (cos(2*pi*{q2_dipole}) - cos(2*pi*{q2})) / (betyac * sin(2*pi*{q2}));") logger.debug("Defining matrix elements for transverse planes") - madx.input(f"hacmap: matrix, l=0, rm21=hacmap21;") - madx.input(f"vacmap: matrix, l=0, rm43=vacmap43;") + madx.input("hacmap: matrix, l=0, rm21=hacmap21;") + madx.input("vacmap: matrix, l=0, rm43=vacmap43;") logger.debug(f"Installing AC Dipole matrix with driven tunes of Qx_D = {q1_dipole:.5f} | Qy_D = {q2_dipole:.5f}") madx.command.seqedit(sequence=f"lhcb{beam:d}") diff --git a/pyhdtoolkit/cpymadtools/lhc/_routines.py b/pyhdtoolkit/cpymadtools/lhc/_routines.py index 0613da0e..018e764a 100644 --- a/pyhdtoolkit/cpymadtools/lhc/_routines.py +++ b/pyhdtoolkit/cpymadtools/lhc/_routines.py @@ -1,5 +1,3 @@ -import numpy as np - """ .. _lhc-routines: @@ -7,6 +5,7 @@ The functions below are routines mimicking manipulations that would be done in the ``LHC``. """ +import numpy as np import tfs from cpymad.madx import Madx diff --git a/pyhdtoolkit/cpymadtools/matching.py b/pyhdtoolkit/cpymadtools/matching.py index 92251e4b..db9a8ab0 100644 --- a/pyhdtoolkit/cpymadtools/matching.py +++ b/pyhdtoolkit/cpymadtools/matching.py @@ -6,7 +6,7 @@ Module with functions to perform ``MAD-X`` matchings through a `~cpymad.madx.Madx` object. """ -from typing import Dict, Optional, Sequence, Tuple +from typing import Optional, Sequence from cpymad.madx import Madx from loguru import logger diff --git a/pyhdtoolkit/cpymadtools/ptc.py b/pyhdtoolkit/cpymadtools/ptc.py index ded118ed..65dcb379 100644 --- a/pyhdtoolkit/cpymadtools/ptc.py +++ b/pyhdtoolkit/cpymadtools/ptc.py @@ -315,7 +315,7 @@ def ptc_twiss( icase = kwargs.pop("icase", 6) normal = kwargs.pop("normal", True) - logger.debug(f"Creating PTC universe") + logger.debug("Creating PTC universe") madx.ptc_create_universe() logger.trace("Creating PTC layout") @@ -448,7 +448,7 @@ def ptc_track_particle( logger.debug(f"Using sequence '{sequence}' for tracking") madx.use(sequence=sequence) - logger.debug(f"Creating PTC universe") + logger.debug("Creating PTC universe") madx.ptc_create_universe() logger.trace("Creating PTC layout") diff --git a/pyhdtoolkit/cpymadtools/tune.py b/pyhdtoolkit/cpymadtools/tune.py index 9350315a..fd0af11a 100644 --- a/pyhdtoolkit/cpymadtools/tune.py +++ b/pyhdtoolkit/cpymadtools/tune.py @@ -203,7 +203,7 @@ def get_footprint_patches(dynap_dframe: tfs.TfsDataFrame) -> matplotlib.collecti "Cannot group tune points according to starting angles and amplitudes. Try changing " "the 'AMPLITUDE' value in the provided TfsDataFrame's headers." ) - raise + raise tune_grouping_error logger.debug("Determining polygon vertices") sx = A.shape[0] - 1 diff --git a/pyhdtoolkit/cpymadtools/twiss.py b/pyhdtoolkit/cpymadtools/twiss.py index b4b84c25..90685af8 100644 --- a/pyhdtoolkit/cpymadtools/twiss.py +++ b/pyhdtoolkit/cpymadtools/twiss.py @@ -76,6 +76,7 @@ def get_pattern_twiss( ... ], ... ) """ + columns = columns or DEFAULT_TWISS_COLUMNS logger.trace("Clearing 'TWISS' flag") madx.select(flag="twiss", clear=True) diff --git a/pyhdtoolkit/cpymadtools/utils.py b/pyhdtoolkit/cpymadtools/utils.py index 26de7626..690230f5 100644 --- a/pyhdtoolkit/cpymadtools/utils.py +++ b/pyhdtoolkit/cpymadtools/utils.py @@ -60,10 +60,10 @@ def export_madx_table( logger.debug(f"Setting NAME column as index and filtering extracted table with regex pattern '{pattern}'") dframe = dframe.set_index("NAME").filter(regex=pattern, axis="index").reset_index() if "NAME" not in dframe.headers: - logger.debug(f"No 'NAME' header found, adding a default value 'EXPORT'") + logger.debug("No 'NAME' header found, adding a default value 'EXPORT'") dframe.headers["NAME"] = "EXPORT" if "TYPE" not in dframe.headers: - logger.debug(f"No 'TYPE' header found, adding a default value 'EXPORT'") + logger.debug("No 'TYPE' header found, adding a default value 'EXPORT'") dframe.headers["TYPE"] = "EXPORT" logger.debug("Writing to disk") tfs.write(file_path, dframe, **kwargs) diff --git a/pyhdtoolkit/maths/stats_fitting.py b/pyhdtoolkit/maths/stats_fitting.py index dce38f40..6f68c3cd 100644 --- a/pyhdtoolkit/maths/stats_fitting.py +++ b/pyhdtoolkit/maths/stats_fitting.py @@ -11,7 +11,7 @@ from typing import Dict, Tuple, Union import matplotlib -import matplotlib.pyplot as plt # if omitted, get AttributeError: module 'matplotlib' has no attribute 'axes' +import matplotlib.pyplot as plt # noqa: F401 | if omitted, get AttributeError: module 'matplotlib' has no attribute 'axes' import numpy as np import pandas as pd import scipy.stats as st diff --git a/pyhdtoolkit/models/beam.py b/pyhdtoolkit/models/beam.py index 9ba82c9b..9bf00203 100644 --- a/pyhdtoolkit/models/beam.py +++ b/pyhdtoolkit/models/beam.py @@ -79,4 +79,4 @@ def __repr__(self) -> str: ) def __str__(self) -> str: - return f"" + return "" diff --git a/pyhdtoolkit/optics/ripken.py b/pyhdtoolkit/optics/ripken.py index e51401fa..2ac15f05 100644 --- a/pyhdtoolkit/optics/ripken.py +++ b/pyhdtoolkit/optics/ripken.py @@ -80,7 +80,7 @@ def _beam_size(coordinates_distribution: np.ndarray, method: str = "std") -> flo return coordinates_distribution.std() elif method == "rms": return np.sqrt(np.mean(np.square(coordinates_distribution))) - raise NotImplementedError(f"Invalid method provided") + raise NotImplementedError("Invalid method provided") def _add_beam_size_to_df(df: tfs.TfsDataFrame, geom_emit_x: float, geom_emit_y: float) -> tfs.TfsDataFrame: diff --git a/pyhdtoolkit/plotting/aperture.py b/pyhdtoolkit/plotting/aperture.py index 166dd324..0829f4bd 100644 --- a/pyhdtoolkit/plotting/aperture.py +++ b/pyhdtoolkit/plotting/aperture.py @@ -148,7 +148,7 @@ def plot_aperture( aperture_df = aperture_df[aperture_df.s.between(*xlimits)] if xlimits else aperture_df # Create a subplot for the lattice patches (takes a third of figure) - figure = plt.gcf() + # figure = plt.gcf() quadrupole_patches_axis = plt.subplot2grid((3, 3), (0, 0), colspan=3, rowspan=1) plot_machine_layout( madx, @@ -246,7 +246,7 @@ def plot_physical_apertures( logger.error(f"'plane' argument should be 'x', 'horizontal', 'y' or 'vertical' not '{plane}'") raise ValueError("Invalid 'plane' argument.") - logger.debug(f"Plotting real element apertures") + logger.debug("Plotting real element apertures") axis, kwargs = maybe_get_ax(**kwargs) if xlimits is not None: diff --git a/pyhdtoolkit/plotting/crossing.py b/pyhdtoolkit/plotting/crossing.py index 0fcf4e3e..e55d1ed6 100644 --- a/pyhdtoolkit/plotting/crossing.py +++ b/pyhdtoolkit/plotting/crossing.py @@ -83,7 +83,7 @@ def plot_two_lhc_ips_crossings( # ----- Plotting figure ----- # logger.debug(f"Plotting crossing schemes for IP{first_ip} and IP{second_ip}") - figure = plt.gcf() + # figure = plt.gcf() first_ip_x_axis = plt.subplot2grid((2, 2), (0, 0), colspan=1, rowspan=1) first_ip_y_axis = plt.subplot2grid((2, 2), (1, 0), colspan=1, rowspan=1) second_ip_x_axis = plt.subplot2grid((2, 2), (0, 1), colspan=1, rowspan=1) diff --git a/pyhdtoolkit/plotting/lattice.py b/pyhdtoolkit/plotting/lattice.py index eff6afaa..ae80977c 100644 --- a/pyhdtoolkit/plotting/lattice.py +++ b/pyhdtoolkit/plotting/lattice.py @@ -146,7 +146,7 @@ def plot_latwiss( xlimits = (twiss_df.s.min(), twiss_df.s.max()) if xlimits is None else xlimits # Create a subplot for the lattice patches (takes a third of figure) - figure = plt.gcf() + # figure = plt.gcf() quadrupole_patches_axis = plt.subplot2grid((3, 3), (0, 0), colspan=3, rowspan=1) plot_machine_layout( madx, diff --git a/pyhdtoolkit/plotting/sbs/coupling.py b/pyhdtoolkit/plotting/sbs/coupling.py index 46bc18ab..bd11d771 100644 --- a/pyhdtoolkit/plotting/sbs/coupling.py +++ b/pyhdtoolkit/plotting/sbs/coupling.py @@ -263,6 +263,6 @@ def _plot_sbs_coupling_rdt_component( ) if model_df is not None and isinstance(model_df, tfs.TfsDataFrame): # If model dataframe is given, find S location of IP and highlight it - logger.debug(f"Plotting the IP location in the segment.") + logger.debug("Plotting the IP location in the segment.") ips = find_ip_s_from_segment_start(segment_df=segment_df, model_df=model_df, ip=ip) ax.axvline(ips, ls="--", color="grey") diff --git a/pyhdtoolkit/plotting/sbs/phase.py b/pyhdtoolkit/plotting/sbs/phase.py index b6c1a823..50b74726 100644 --- a/pyhdtoolkit/plotting/sbs/phase.py +++ b/pyhdtoolkit/plotting/sbs/phase.py @@ -52,8 +52,8 @@ def plot_phase_segment_one_beam( ... sbs_phasex, sbs_phasey, model=b2_model_tfs, ip=5, figsize=(8, 8) ... ) """ - logger.debug(f"Plotting the phase for both planes over the segment.") - legend_bbox_to_anchor = kwargs.pop("bbox_to_anchor", (0.535, 0.97)) + logger.debug("Plotting the phase for both planes over the segment.") + # legend_bbox_to_anchor = kwargs.pop("bbox_to_anchor", (0.535, 0.97)) figure, (ax1, ax2) = plt.subplots(2, 1, **kwargs) 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( ... bbox_to_anchor=(0.535, 0.94), ... ) """ - logger.debug(f"Plotting the phase for both planes over the segment.") + logger.debug("Plotting the phase for both planes over the segment.") legend_bbox_to_anchor = kwargs.pop("bbox_to_anchor", (0.535, 0.97)) figure, ((b1x, b2x), (b1y, b2y)) = plt.subplots(2, 2, sharex=True, sharey="row", **kwargs) @@ -212,6 +212,6 @@ def plot_phase_segment( ) if model_df is not None and isinstance(model_df, tfs.TfsDataFrame): # If model dataframe is given, find S location of IP and highlight it - logger.debug(f"Plotting the IP location in the segment.") + logger.debug("Plotting the IP location in the segment.") ips = find_ip_s_from_segment_start(segment_df=segment_df, model_df=model_df, ip=ip) ax.axvline(ips, ls="--", color="grey") diff --git a/pyproject.toml b/pyproject.toml index 6e6a1838..98c04753 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -79,7 +79,7 @@ test = [ dev = [ "black >= 22.1", "isort >= 5.10", - "pylint >= 2.4", + "ruff >= 0.0.250", ] docs = [ "Sphinx >= 4.4", @@ -153,6 +153,19 @@ exclude = ''' )/ ''' +[tool.ruff] +ignore = ["E501"] +line-length = 120 + +# Exclude a variety of commonly ignored directories. +exclude = ["pyhdtoolkit/cpymadtools/lhc/__init__.py"] + +# Allow unused variables when underscore-prefixed. +dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$" + +# Assume Python 3.8+. +target-version = "py38" + [tool.mypy] pretty = true strict_optional = false @@ -161,68 +174,6 @@ warn_redundant_casts = true ignore_missing_imports = true follow_imports = "skip" -[tool.pylint] -[tool.pylint.master] -jobs="1" # Auto-detect the number of processors -ignore-patterns=''' - \.eggs - |\.git - |build - |dist - |conf.py -''' -persistent="no" -load-plugins="" -limit-inference-results="100" -suggestion-mode="yes" -unsafe-load-any-extension="no" -extension-pkg-whitelist="" -exit-zero="no" -from-stdin="no" - -[tool.pylint.messages_control] -disable = [ - "attribute-defined-outside-init", - "bad-continuation", - "expression-not-assigned", - "invalid-name", - "import-error", - "logging-format-interpolation", - "protected-access", - "too-few-public-methods", - "too-many-instance-attributes", - "format", # handled by black -] - -[tool.pylint.reports] -output-format="text" -msg-template="{path}:{line}:{column}: Pylint: {msg}. [{msg_id}: {symbol}]" - -[tool.pylint.basic] -argument-naming-style="snake_case" -attr-naming-style="snake_case" -class-attribute-naming-style="snake_case" -class-naming-style="PascalCase" -const-naming-style="UPPER_CASE" -function-naming-style="snake_case" -inlinevar-naming-style="snake_case" -method-naming-style="snake_case" -module-naming-style="snake_case" -variable-naming-style="snake_case" - -[tool.pylint.design] -max-args="10" -max-attributes="10" -max-locals="15" -max-public-methods="20" -max-returns="5" - -[tool.pylint.'SIMILARITIES'] -ignore-comments=['yes'] -ignore-docstrings=['yes'] -ignore-imports=['no'] -min-similarity-lines=4 - [tool.interrogate] ignore-init-method = true ignore-init-module = true diff --git a/tests/test_cpymadtools/test_lhc.py b/tests/test_cpymadtools/test_lhc.py index bb4e7ba0..5ae1b39e 100644 --- a/tests/test_cpymadtools/test_lhc.py +++ b/tests/test_cpymadtools/test_lhc.py @@ -10,6 +10,7 @@ from cpymad.madx import Madx from pandas.testing import assert_frame_equal +from pyhdtoolkit.cpymadtools.constants import LHC_TRIPLETS_REGEX # noqa: F401 | for coverage from pyhdtoolkit.cpymadtools.constants import ( DEFAULT_TWISS_COLUMNS, LHC_ANGLE_FLAGS, @@ -33,7 +34,6 @@ LHC_KSF_KNOBS, LHC_KSS_KNOBS, LHC_PARALLEL_SEPARATION_FLAGS, - LHC_TRIPLETS_REGEX, ) from pyhdtoolkit.cpymadtools.lhc import ( LHCSetup, @@ -548,7 +548,7 @@ def test_add_ip_markers(_non_matched_lhc_madx, markers, ip): init_twiss = init_twiss[init_twiss.s.between(ip_s - 15, ip_s + 15)] make_lhc_thin(madx, sequence="lhcb1", slicefactor=4) - add_markers_around_lhc_ip(madx, sequence=f"lhcb1", ip=ip, n_markers=markers, interval=0.001) + add_markers_around_lhc_ip(madx, sequence="lhcb1", ip=ip, n_markers=markers, interval=0.001) new_twiss = madx.twiss().dframe() new_twiss = new_twiss[new_twiss.s.between(ip_s - 15, ip_s + 15)] @@ -810,21 +810,21 @@ def test_lhc_run3_setup_context_manager_fullpath_to_opticsfile(): @pytest.mark.skipif(not (TESTS_DIR.parent / "acc-models-lhc").is_dir(), reason="acc-models-lhc not found") def test_lhc_run3_setup_context_manager_raises_on_wrong_b4_conditions(): with pytest.raises(ValueError): # using b4 with beam1 setup crashes - with LHCSetup(opticsfile="R2022a_A30cmC30cmA10mL200cm.madx", beam=1, use_b4=True) as madx: + with LHCSetup(opticsfile="R2022a_A30cmC30cmA10mL200cm.madx", beam=1, use_b4=True) as madx: # noqa: F841 pass @pytest.mark.skipif(not (TESTS_DIR.parent / "acc-models-lhc").is_dir(), reason="acc-models-lhc not found") def test_lhc_run3_setup_context_manager_raises_on_wrong_run_value(): with pytest.raises(NotImplementedError): # using b4 with beam1 setup crashes - with LHCSetup(run=1, opticsfile="R2022a_A30cmC30cmA10mL200cm.madx") as madx: + with LHCSetup(run=1, opticsfile="R2022a_A30cmC30cmA10mL200cm.madx") as madx: # noqa: F841 pass @pytest.mark.skipif(not (TESTS_DIR.parent / "acc-models-lhc").is_dir(), reason="acc-models-lhc not found") def test_lhc_run3_setup_raises_on_wrong_b4_conditions(_proton_opticsfile): with pytest.raises(ValueError): # using b4 with beam1 setup crashes - madx = prepare_lhc_run3(opticsfile="R2022a_A30cmC30cmA10mL200cm.madx", beam=1, use_b4=True) + _ = prepare_lhc_run3(opticsfile="R2022a_A30cmC30cmA10mL200cm.madx", beam=1, use_b4=True) # ------------------- Run2 Setup Tests ------------------- # @@ -841,12 +841,12 @@ def test_lhc_run2_setup_context_manager(_proton_opticsfile, slicefactor): def test_lhc_run2_setup_raises_on_wrong_b4_conditions(_proton_opticsfile): with pytest.raises(ValueError): # using b4 with beam1 setup crashes - madx = prepare_lhc_run2(opticsfile=_proton_opticsfile, beam=1, use_b4=True) + _ = prepare_lhc_run2(opticsfile=_proton_opticsfile, beam=1, use_b4=True) def test_lhc_run2_setup_raises_on_absent_sequence_file(): with pytest.raises(ValueError): # will not find the sequence file from this opticsfile value - madx = prepare_lhc_run2(opticsfile="some/place/here.madx") + _ = prepare_lhc_run2(opticsfile="some/place/here.madx") # ---------------------- Private Utilities ---------------------- # diff --git a/tests/test_cpymadtools/test_tune.py b/tests/test_cpymadtools/test_tune.py index 8ae4d290..ce2431e2 100644 --- a/tests/test_cpymadtools/test_tune.py +++ b/tests/test_cpymadtools/test_tune.py @@ -23,7 +23,7 @@ def test_make_footprint_table(_non_matched_lhc_madx, tmp_path, sigma, dense): export_file = tmp_path / "out.tfs" madx = _non_matched_lhc_madx re_cycle_sequence(madx, sequence="lhcb1", start="IP3") - orbit_scheme = setup_lhc_orbit(madx, scheme="flat") + _ = setup_lhc_orbit(madx, scheme="flat") madx.use(sequence="lhcb1") match_tunes_and_chromaticities(madx, "lhc", "lhcb1", 62.31, 60.32, 2.0, 2.0, telescopic_squeeze=True) @@ -55,11 +55,11 @@ def test_make_footprint_table(_non_matched_lhc_madx, tmp_path, sigma, dense): def test_make_footprint_table_crashes_without_slicing(_non_matched_lhc_madx, caplog): madx = _non_matched_lhc_madx re_cycle_sequence(madx, sequence="lhcb1", start="IP3") - orbit_scheme = setup_lhc_orbit(madx, scheme="flat") + _ = setup_lhc_orbit(madx, scheme="flat") madx.use(sequence="lhcb1") with pytest.raises(RuntimeError): - foot = make_footprint_table(madx, sigma=2) + _ = make_footprint_table(madx, sigma=2) for record in caplog.records: assert record.levelname == "ERROR" @@ -96,7 +96,7 @@ def test_get_footprint_patches_raises_wrong_shape(_dynap_tfs_path, caplog): dynap_dframe = tfs.read(_dynap_tfs_path) with pytest.raises(ValueError): - polygons = get_footprint_patches(dynap_dframe) + _ = get_footprint_patches(dynap_dframe) for record in caplog.records: assert record.levelname == "ERROR" diff --git a/tests/test_cpymadtools/test_twiss.py b/tests/test_cpymadtools/test_twiss.py index 1e07991a..2e946de2 100644 --- a/tests/test_cpymadtools/test_twiss.py +++ b/tests/test_cpymadtools/test_twiss.py @@ -5,7 +5,7 @@ from pandas.testing import assert_frame_equal -from pyhdtoolkit.cpymadtools.constants import DEFAULT_TWISS_COLUMNS # for coverage +from pyhdtoolkit.cpymadtools.constants import DEFAULT_TWISS_COLUMNS # noqa: F401 | for coverage from pyhdtoolkit.cpymadtools.twiss import get_twiss_tfs CURRENT_DIR = pathlib.Path(__file__).parent diff --git a/tests/test_plotting/test_sbs_phase.py b/tests/test_plotting/test_sbs_phase.py index e3b861fa..09a07036 100644 --- a/tests/test_plotting/test_sbs_phase.py +++ b/tests/test_plotting/test_sbs_phase.py @@ -1,7 +1,5 @@ import pathlib -from multiprocessing.sharedctypes import Value - import pytest import tfs diff --git a/tests/test_plotting/test_styles.py b/tests/test_plotting/test_styles.py index 9a667a36..7fec04d0 100644 --- a/tests/test_plotting/test_styles.py +++ b/tests/test_plotting/test_styles.py @@ -2,7 +2,6 @@ import matplotlib import matplotlib.pyplot as plt -import pytest from pyhdtoolkit.plotting.styles import install_mpl_styles diff --git a/tests/test_utils.py b/tests/test_utils.py index 48e509b4..576dcf60 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -9,8 +9,6 @@ from typing import List -import matplotlib -import matplotlib.pyplot as plt import numpy as np import pandas as pd import pytest @@ -582,7 +580,7 @@ def test_capitalize(self, string_input, lower, result): assert StringOperations.capitalize(string_input, lower_rest=lower) == result @pytest.mark.parametrize("string_input, lower, error", [(1, True, TypeError), (_square, False, TypeError)]) - def test_camel_case_fails(self, string_input, lower, error): + def test_camel_capitalize_fails(self, string_input, lower, error): with pytest.raises(error): StringOperations.capitalize(string_input, lower_rest=lower) diff --git a/tests/test_version.py b/tests/test_version.py index e7ebedff..d7420477 100644 --- a/tests/test_version.py +++ b/tests/test_version.py @@ -1,8 +1,6 @@ import platform import sys -import pytest - from pyhdtoolkit.version import VERSION, version_info