Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ruff #103

Merged
merged 6 commits into from
Mar 12, 2023
Merged

Ruff #103

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -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
Expand Down
18 changes: 9 additions & 9 deletions examples/demo_lhc_rigid_waist_shift.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand All @@ -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)]
Expand Down Expand Up @@ -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()

###############################################################################
Expand Down
1 change: 0 additions & 1 deletion examples/demo_lhc_setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions examples/demo_stats_fitting.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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()

Expand Down
2 changes: 1 addition & 1 deletion pyhdtoolkit/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."
Expand Down
2 changes: 1 addition & 1 deletion pyhdtoolkit/cpymadtools/coupling.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"])
Expand Down
2 changes: 1 addition & 1 deletion pyhdtoolkit/cpymadtools/lhc/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down
4 changes: 2 additions & 2 deletions pyhdtoolkit/cpymadtools/lhc/_elements.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
Expand Down
3 changes: 1 addition & 2 deletions pyhdtoolkit/cpymadtools/lhc/_routines.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import numpy as np

"""
.. _lhc-routines:

**Routine Utilities**

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
Expand Down
2 changes: 1 addition & 1 deletion pyhdtoolkit/cpymadtools/matching.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions pyhdtoolkit/cpymadtools/ptc.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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")
Expand Down
2 changes: 1 addition & 1 deletion pyhdtoolkit/cpymadtools/tune.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions pyhdtoolkit/cpymadtools/twiss.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
4 changes: 2 additions & 2 deletions pyhdtoolkit/cpymadtools/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion pyhdtoolkit/maths/stats_fitting.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion pyhdtoolkit/models/beam.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,4 +79,4 @@ def __repr__(self) -> str:
)

def __str__(self) -> str:
return f""
return ""
2 changes: 1 addition & 1 deletion pyhdtoolkit/optics/ripken.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
4 changes: 2 additions & 2 deletions pyhdtoolkit/plotting/aperture.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion pyhdtoolkit/plotting/crossing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion pyhdtoolkit/plotting/lattice.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion pyhdtoolkit/plotting/sbs/coupling.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
8 changes: 4 additions & 4 deletions pyhdtoolkit/plotting/sbs/phase.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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")
Loading