Skip to content

Commit

Permalink
fix error messages not declared before raising
Browse files Browse the repository at this point in the history
  • Loading branch information
fsoubelet committed Aug 12, 2024
1 parent 39c3dc4 commit 06cde54
Show file tree
Hide file tree
Showing 12 changed files with 42 additions and 21 deletions.
9 changes: 6 additions & 3 deletions pyhdtoolkit/cpymadtools/lhc/_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,13 +143,16 @@ def misalign_lhc_ir_quadrupoles(
"""
if any(ip not in (1, 2, 5, 8) for ip in ips):
logger.error("The IP number provided is invalid, not applying any error.")
raise ValueError("Invalid 'ips' parameter")
msg = "Invalid 'ips' parameter"
raise ValueError(msg)
if beam and beam not in (1, 2, 3, 4):
logger.error("The beam number provided is invalid, not applying any error.")
raise ValueError("Invalid 'beam' parameter")
msg = "Invalid 'beam' parameter"
raise ValueError(msg)
if any(side.upper() not in ("R", "L") for side in sides):
logger.error("The side provided is invalid, not applying any error.")
raise ValueError("Invalid 'sides' parameter")
msg = "Invalid 'sides' parameter"
raise ValueError(msg)

sides = [side.upper() for side in sides]
logger.debug("Clearing error flag")
Expand Down
9 changes: 6 additions & 3 deletions pyhdtoolkit/cpymadtools/lhc/_powering.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,8 @@ def apply_lhc_rigidity_waist_shift_knob(
madx.globals[left_knob] = (1 - rigidty_waist_shift_value * 0.005) * current_left_knob
else:
logger.error(f"Given side '{side}' invalid, only 'left' and 'right' are accepted values.")
raise ValueError("Invalid value for parameter 'side'.")
msg = "Invalid value for parameter 'side'."
raise ValueError(msg)

logger.debug(f"Set '{right_knob}' to {madx.globals[right_knob]}")
logger.debug(f"Set '{left_knob}' to {madx.globals[left_knob]}")
Expand Down Expand Up @@ -237,7 +238,8 @@ def power_landau_octupoles(madx: Madx, /, beam: int, mo_current: float, defectiv
brho = madx.globals.nrj * 1e9 / madx.globals.clight # clight is MAD-X constant
except AttributeError as madx_error:
logger.exception("The global MAD-X variable 'NRJ' should have been set in the optics files but is not defined.")
raise AttributeError("No 'NRJ' variable found in scripts") from madx_error
msg = "No 'NRJ' variable found in scripts"
raise AttributeError(msg) from madx_error

logger.debug(f"Powering Landau Octupoles, beam {beam} @ {madx.globals.nrj} GeV with {mo_current} A.")
strength = mo_current / madx.globals.Imax_MO * madx.globals.Kmax_MO / brho
Expand Down Expand Up @@ -317,7 +319,8 @@ def vary_independent_ir_quadrupoles(
or any(quad not in (4, 5, 6, 7, 8, 9, 10, 11, 12, 13) for quad in quad_numbers)
):
logger.error("Either the IP number of the side provided are invalid, not applying any error.")
raise ValueError("Invalid 'quad_numbers', 'ip', 'sides' argument")
msg = "Invalid 'quad_numbers', 'ip', 'sides' argument"
raise ValueError(msg)

logger.debug(f"Preparing a knob involving quadrupoles {quad_numbers}")
# Each quad has a specific power circuit used for their k1 boundaries
Expand Down
15 changes: 10 additions & 5 deletions pyhdtoolkit/cpymadtools/lhc/_setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@ def prepare_lhc_run2(
"""
if use_b4 and beam != 2:
logger.error("Cannot use beam 4 sequence file for beam 1")
raise ValueError("Cannot use beam 4 sequence file for beam 1")
msg = "Cannot use beam 4 sequence file for beam 1"
raise ValueError(msg)

def _run2_sequence_from_opticsfile(opticsfile: Path, use_b4: bool = False) -> Path:
filename = "lhc_as-built.seq" if not use_b4 else "lhcb4_as-built.seq"
Expand Down Expand Up @@ -137,7 +138,8 @@ def prepare_lhc_run3(
"""
if use_b4 and beam != 2:
logger.error("Cannot use beam 4 sequence file for beam 1")
raise ValueError("Cannot use beam 4 sequence file for beam 1")
msg = "Cannot use beam 4 sequence file for beam 1"
raise ValueError(msg)

logger.debug("Creating Run 3 setup MAD-X instance")
echo, warn = kwargs.pop("echo", False), kwargs.pop("warn", False)
Expand Down Expand Up @@ -238,10 +240,12 @@ def __init__(
assert opticsfile is not None, "An opticsfile must be provided"
if use_b4 and beam != 2:
logger.error("Cannot use beam 4 sequence file for beam 1")
raise ValueError("Cannot use beam 4 sequence file for beam 1")
msg = "Cannot use beam 4 sequence file for beam 1"
raise ValueError(msg)

if int(run) not in (2, 3):
raise NotImplementedError("This setup is only possible for Run 2 and Run 3 configurations.")
msg = "This setup is only possible for Run 2 and Run 3 configurations."
raise NotImplementedError(msg)
elif run == 2:
self.madx = prepare_lhc_run2(
opticsfile=opticsfile, beam=beam, use_b4=use_b4, energy=energy, slicefactor=slicefactor, **kwargs
Expand Down Expand Up @@ -496,7 +500,8 @@ def setup_lhc_orbit(madx: Madx, /, scheme: str = "flat", **kwargs) -> dict[str,
"""
if scheme not in LHC_CROSSING_SCHEMES.keys():
logger.error(f"Invalid scheme parameter, should be one of {LHC_CROSSING_SCHEMES.keys()}")
raise ValueError("Invalid scheme parameter given")
msg = "Invalid scheme parameter given"
raise ValueError(msg)

logger.debug("Getting orbit variables")
variables, special = lhc_orbit_variables()
Expand Down
3 changes: 2 additions & 1 deletion pyhdtoolkit/cpymadtools/ptc.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,8 @@ def get_amplitude_detuning(
"""
if order >= 3:
logger.error(f"Maximum amplitude detuning order in PTC is 2, but {order:d} was requested")
raise NotImplementedError("PTC amplitude detuning is not implemented for order > 2")
msg = "PTC amplitude detuning is not implemented for order > 2"
raise NotImplementedError(msg)

logger.debug("Looking for PTC universe parameters in keyword arguments")
model = kwargs.pop("model", 3)
Expand Down
3 changes: 2 additions & 1 deletion pyhdtoolkit/cpymadtools/tune.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,8 @@ def make_footprint_table(
"Remote MAD-X process crashed, most likely because you did not slice the sequence "
"before running DYNAP. Restart and slice before calling this function."
)
raise RuntimeError("DYNAP command crashed the MAD-X process") from madx_crash
msg = "DYNAP command crashed the MAD-X process"
raise RuntimeError(msg) from madx_crash

if cleanup and sys.platform not in ("win32", "cygwin"):
# fails on Windows due to its I/O system, since MAD-X still has "control" of the files
Expand Down
3 changes: 2 additions & 1 deletion pyhdtoolkit/cpymadtools/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,8 @@ def _get_k_strings(start: int = 0, stop: int = 8, orientation: str = "both") ->
"""
if orientation not in ("straight", "skew", "both"):
logger.error(f"Orientation '{orientation}' is not accepted, should be one of 'straight', 'skew', 'both'.")
raise ValueError("Invalid 'orientation' parameter")
msg = "Invalid 'orientation' parameter"
raise ValueError(msg)

if orientation == "straight":
orientation = ("",)
Expand Down
3 changes: 2 additions & 1 deletion pyhdtoolkit/optics/ripken.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,8 @@ 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("Invalid method provided")
msg = "Invalid method provided"
raise NotImplementedError(msg)


def _add_beam_size_to_df(df: tfs.TfsDataFrame, geom_emit_x: float, geom_emit_y: float) -> tfs.TfsDataFrame:
Expand Down
3 changes: 2 additions & 1 deletion pyhdtoolkit/plotting/aperture.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,8 @@ def plot_physical_apertures(
# pylint: disable=too-many-arguments
if plane.lower() not in ("x", "y", "horizontal", "vertical"):
logger.error(f"'plane' argument should be 'x', 'horizontal', 'y' or 'vertical' not '{plane}'")
raise ValueError("Invalid 'plane' argument.")
msg = "Invalid 'plane' argument."
raise ValueError(msg)

logger.debug("Plotting real element apertures")
axis, kwargs = maybe_get_ax(**kwargs)
Expand Down
3 changes: 2 additions & 1 deletion pyhdtoolkit/plotting/envelope.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,8 @@ def plot_beam_envelope(
# pylint: disable=too-many-arguments
if plane.lower() not in ("x", "y", "horizontal", "vertical"):
logger.error(f"'plane' argument should be 'x', 'horizontal', 'y' or 'vertical' not '{plane}'")
raise ValueError("Invalid 'plane' argument.")
msg = "Invalid 'plane' argument."
raise ValueError(msg)

logger.debug(f"Plotting machine orbit and {nsigma:.2f}sigma beam envelope")
axis, kwargs = maybe_get_ax(**kwargs)
Expand Down
6 changes: 4 additions & 2 deletions pyhdtoolkit/plotting/phasespace.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@ def plot_courant_snyder_phase_space(
"""
if plane.lower() not in ("horizontal", "vertical"):
logger.error(f"Plane should be either Horizontal or Vertical but '{plane}' was given")
raise ValueError("Invalid plane value")
msg = "Invalid 'plane' value."
raise ValueError(msg)

logger.debug("Plotting phase space for normalized Courant-Snyder coordinates")
axis, kwargs = maybe_get_ax(**kwargs)
Expand Down Expand Up @@ -131,7 +132,8 @@ def plot_courant_snyder_phase_space_colored(
"""
if plane.upper() not in ("HORIZONTAL", "VERTICAL"):
logger.error(f"Plane should be either horizontal or vertical but '{plane}' was given")
raise ValueError("Invalid plane value")
msg = "Invalid 'plane' value."
raise ValueError(msg)

# Getting a sufficiently long array of colors to use
colors = int(np.floor(len(u_coordinates) / 100)) * SORTED_COLORS
Expand Down
3 changes: 2 additions & 1 deletion pyhdtoolkit/plotting/sbs/phase.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,8 @@ def plot_phase_segment(
"""
if plane.upper() not in ("X", "Y"):
logger.error("The provided plane is invalid, should be either 'x' or 'y', case-insensitively.")
raise ValueError("Invalid 'plane' parameter")
msg = "Invalid 'plane' parameter"
raise ValueError(msg)
plane = plane.upper()

logger.debug(f"Plotting phase for plane {plane.upper()} over the segment")
Expand Down
3 changes: 2 additions & 1 deletion pyhdtoolkit/plotting/tune.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,8 @@ def plot_tune_diagram(
"""
if max_order > 6 or max_order < 1:
logger.error("Plotting is not supported outside of 1st-6th order (and not recommended)")
raise ValueError("The 'max_order' argument should be between 1 and 6 included")
msg = "The 'max_order' argument should be between 1 and 6 included"
raise ValueError(msg)

logger.debug(f"Plotting resonance lines up to {ORDER_TO_LABEL[max_order]}")
axis, kwargs = maybe_get_ax(**kwargs)
Expand Down

0 comments on commit 06cde54

Please sign in to comment.