diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 85d8dc2d00..0e4804cac7 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,6 +1,6 @@ repos: - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.4.0 + rev: v4.5.0 hooks: - id: trailing-whitespace exclude: test_data @@ -12,7 +12,7 @@ repos: exclude: test_data - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.3.4 + rev: v0.4.4 hooks: - id: ruff args: [ --fix ] diff --git a/bluemira/base/look_and_feel.py b/bluemira/base/look_and_feel.py index a42ef3e063..2a606b8790 100644 --- a/bluemira/base/look_and_feel.py +++ b/bluemira/base/look_and_feel.py @@ -176,7 +176,7 @@ def count_slocs( continue lines[".py"] += LOCAL_LINES - lines["total"] = sum([lines[k] for k in lines]) + lines["total"] = sum(lines[k] for k in lines) return lines diff --git a/bluemira/builders/coil_supports.py b/bluemira/builders/coil_supports.py index 012416c311..1b293f49ef 100644 --- a/bluemira/builders/coil_supports.py +++ b/bluemira/builders/coil_supports.py @@ -152,7 +152,7 @@ def _get_intersection_wire(self, width): "Boolean cutting returned nothing... check your geometry please." ) - return sorted(cut_result, key=lambda wire: wire.length)[0] + return min(cut_result, key=lambda wire: wire.length) def _make_connection_block(self, width, v1, v4, intersection_wire): """ @@ -442,9 +442,9 @@ def _get_intersecting_wire(self, v1, v2, v3, v4, angle): cut_box = make_polygon([v1, v2, v3, v4], closed=True) - return sorted( + return min( boolean_cut(self.tf_xz_keep_out_zone, cut_box), key=lambda wire: wire.length - )[0] + ) def _make_rib_profile(self, support_face): # Then, project sideways to find the minimum distance from a support point diff --git a/bluemira/codes/_freecadapi.py b/bluemira/codes/_freecadapi.py index 7b6141d7d1..050906dae8 100644 --- a/bluemira/codes/_freecadapi.py +++ b/bluemira/codes/_freecadapi.py @@ -498,8 +498,8 @@ def make_ellipse( center = Base.Vector(center) output = Part.Ellipse(s1, s2, center) - start_angle = start_angle % 360.0 - end_angle = end_angle % 360.0 + start_angle %= 360.0 + end_angle %= 360.0 if start_angle != end_angle: output = Part.ArcOfEllipse( @@ -1805,7 +1805,7 @@ def boolean_fuse( raise ValueError( # noqa: TRY301 f"Fuse function still not implemented for {_type} instances." ) - except Exception as e: # noqa: BLE001 + except Exception as e: raise FreeCADError(str(e)) from e diff --git a/bluemira/codes/plasmod/equilibrium_2d_coupling.py b/bluemira/codes/plasmod/equilibrium_2d_coupling.py index 5d3aaa0d3a..d31e3ea042 100644 --- a/bluemira/codes/plasmod/equilibrium_2d_coupling.py +++ b/bluemira/codes/plasmod/equilibrium_2d_coupling.py @@ -657,9 +657,9 @@ def calc_curr_dens_profiles( dum2 = cumulative_trapezoid(B, psi_norm_1D, initial=0) dum1 = np.exp(2.0 * dum2) - dum1 = dum1 / dum1[-1] + dum1 /= dum1[-1] dum3 = cumulative_trapezoid(C / dum1, psi_norm_1D, initial=0) - dum3 = dum3 - dum3[-1] + dum3 -= dum3[-1] y = dum1 * (dum3 + 0.5 * Fb**2) dum2 = g2 / q3 diff --git a/bluemira/display/auto_config.py b/bluemira/display/auto_config.py index 2ea88ca300..fba00c7a90 100644 --- a/bluemira/display/auto_config.py +++ b/bluemira/display/auto_config.py @@ -108,8 +108,7 @@ def get_figure_scale_factor(figsize): for ds, ss in zip(dpi_size, screen_size, strict=False): if ds > ss: scale_temp = ss / ds - if scale_temp < sf: - sf = scale_temp + sf = min(scale_temp, sf) return sf diff --git a/bluemira/equilibria/equilibrium.py b/bluemira/equilibria/equilibrium.py index c629c9121e..3fc1cc89cb 100644 --- a/bluemira/equilibria/equilibrium.py +++ b/bluemira/equilibria/equilibrium.py @@ -141,14 +141,14 @@ def _get_eqdsk( psi = e.psi elif "SCENE" in e.name and not isinstance(cls, Breakdown): psi = e.psi - e.dxc = e.dxc / 2 - e.dzc = e.dzc / 2 + e.dxc /= 2 + e.dzc /= 2 elif "fiesta" in e.name.lower(): psi = e.psi else: # CREATE psi = e.psi / (2 * np.pi) # V.s as opposed to V.s/rad - e.dxc = e.dxc / 2 - e.dzc = e.dzc / 2 + e.dxc /= 2 + e.dzc /= 2 e.cplasma = abs(e.cplasma) grid = Grid.from_eqdsk(e) diff --git a/bluemira/equilibria/flux_surfaces.py b/bluemira/equilibria/flux_surfaces.py index 93ef256ab7..60d6e122d1 100644 --- a/bluemira/equilibria/flux_surfaces.py +++ b/bluemira/equilibria/flux_surfaces.py @@ -483,7 +483,7 @@ def clip(self, first_wall: Coordinates): first_wall.xz.T[fw_arg + 1], np.array([self.x_end, self.z_end]), ): - fw_arg = fw_arg + 1 + fw_arg += 1 # Relying on the fact that first wall is ccw, get the intersection angle self.alpha = get_angle_between_points( diff --git a/bluemira/equilibria/num_control.py b/bluemira/equilibria/num_control.py index 5465f9c498..9dbca41118 100644 --- a/bluemira/equilibria/num_control.py +++ b/bluemira/equilibria/num_control.py @@ -113,7 +113,7 @@ def adjust_currents(self, d_current: float): """ Adjust the currents in the virtual control coils. """ - self.current = self.current + d_current + self.current += d_current def stabilise(self): """ diff --git a/bluemira/equilibria/optimisation/constraints.py b/bluemira/equilibria/optimisation/constraints.py index dd4d45bcbd..3d8c3800d3 100644 --- a/bluemira/equilibria/optimisation/constraints.py +++ b/bluemira/equilibria/optimisation/constraints.py @@ -114,7 +114,7 @@ def __init__( z = np.array([z]) if is_num(B_max): - B_max = B_max * np.ones(len(x)) + B_max *= np.ones(len(x)) if len(B_max) != len(x): raise ValueError( "Maximum field vector length not equal to the number of points." @@ -123,7 +123,7 @@ def __init__( if tolerance is None: tolerance = 1e-3 * B_max if is_num(tolerance): - tolerance = tolerance * np.ones(len(x)) + tolerance *= np.ones(len(x)) if len(tolerance) != len(x): raise ValueError("Tolerance vector length not equal to the number of coils.") @@ -225,7 +225,7 @@ def __init__( ): n_coils = coilset.n_coils() if is_num(B_max): - B_max = B_max * np.ones(n_coils) + B_max *= np.ones(n_coils) if len(B_max) != n_coils: raise ValueError( "Maximum field vector length not equal to the number of coils." @@ -310,7 +310,7 @@ def __init__( * np.ones(n_f_constraints) ) if is_num(tolerance): - tolerance = tolerance * np.ones(n_f_constraints) + tolerance *= np.ones(n_f_constraints) elif len(tolerance) != n_f_constraints: raise ValueError(f"Tolerance vector not of length {n_f_constraints}") @@ -394,9 +394,9 @@ def __init__( tolerance = 1e-3 if target_value == 0 else 1e-3 * target_value if is_num(tolerance): if f_constraint == L2NormConstraint: - tolerance = tolerance * np.ones(1) + tolerance *= np.ones(1) else: - tolerance = tolerance * np.ones(len(self)) + tolerance *= np.ones(len(self)) self.weights = weights self._f_constraint = f_constraint self._args = {"a_mat": None, "b_vec": None, "value": 0.0, "scale": 1.0} @@ -726,7 +726,7 @@ def plot(self, ax): ax.plot(self.x, self.z, **kwargs) -class MagneticConstraintSet(ABC): +class MagneticConstraintSet: """ A set of magnetic constraints to be applied to an equilibrium. The optimisation problem is of the form: @@ -791,7 +791,7 @@ def __len__(self) -> int: """ The mathematical size of the constraint set. """ - return sum([len(c) for c in self.constraints]) + return sum(len(c) for c in self.constraints) def get_weighted_arrays(self) -> tuple[np.ndarray, np.ndarray, np.ndarray]: """ diff --git a/bluemira/equilibria/optimisation/harmonics/harmonics_approx_functions.py b/bluemira/equilibria/optimisation/harmonics/harmonics_approx_functions.py index dc63cd741e..d103d433b1 100644 --- a/bluemira/equilibria/optimisation/harmonics/harmonics_approx_functions.py +++ b/bluemira/equilibria/optimisation/harmonics/harmonics_approx_functions.py @@ -400,7 +400,7 @@ def lcfs_fit_metric(coords1: Coordinates, coords2: Coordinates) -> float: result2 = boolean_cut(c2_face, c1_face) # Calculate metric - return (sum([f.area for f in result1]) + sum([f.area for f in result2])) / ( + return (sum(f.area for f in result1) + sum(f.area for f in result2)) / ( c1_face.area + c2_face.area ) diff --git a/bluemira/equilibria/optimisation/harmonics/harmonics_constraints.py b/bluemira/equilibria/optimisation/harmonics/harmonics_constraints.py index 28fd9e80c3..c6ddf134dd 100644 --- a/bluemira/equilibria/optimisation/harmonics/harmonics_constraints.py +++ b/bluemira/equilibria/optimisation/harmonics/harmonics_constraints.py @@ -64,7 +64,7 @@ def __init__( ord_mag = np.floor(np.log10(np.absolute(ref_harmonics))) - 3 tolerance = [max(smallest_tol, 10**x) for x in ord_mag] elif is_num(tolerance): - tolerance = tolerance * np.ones(len(ref_harmonics)) + tolerance *= np.ones(len(ref_harmonics)) elif len(tolerance) != len(ref_harmonics): raise ValueError(f"Tolerance vector not of length {len(ref_harmonics)}") diff --git a/bluemira/equilibria/optimisation/objectives.py b/bluemira/equilibria/optimisation/objectives.py index ca74888ad0..8a3900ecec 100644 --- a/bluemira/equilibria/optimisation/objectives.py +++ b/bluemira/equilibria/optimisation/objectives.py @@ -84,7 +84,7 @@ def __init__( def f_objective(self, vector: npt.NDArray[np.float64]) -> float: """Objective function for an optimisation.""" - vector = vector * self.scale + vector = vector * self.scale # nlopt read only # noqa: PLR6104 fom, _ = regularised_lsq_fom(vector, self.a_mat, self.b_vec, self.gamma) if fom <= 0: raise EquilibriaError( @@ -94,7 +94,7 @@ def f_objective(self, vector: npt.NDArray[np.float64]) -> float: def df_objective(self, vector: npt.NDArray[np.float64]) -> npt.NDArray[np.float64]: """Gradient of the objective function for an optimisation.""" - vector = vector * self.scale + vector = vector * self.scale # nlopt read only # noqa: PLR6104 jac = 2 * self.a_mat.T @ self.a_mat @ vector / float(len(self.b_vec)) jac -= 2 * self.a_mat.T @ self.b_vec / float(len(self.b_vec)) jac += 2 * self.gamma * self.gamma * vector diff --git a/bluemira/fuel_cycle/timeline.py b/bluemira/fuel_cycle/timeline.py index c993e5bef2..8755606e33 100644 --- a/bluemira/fuel_cycle/timeline.py +++ b/bluemira/fuel_cycle/timeline.py @@ -376,7 +376,7 @@ def concatenate(p_phases, k_key): for key in ["t", "inventory", "DT_rate", "DD_rate"]: setattr(self, key, concatenate(phases, key)) - self.t_unplanned_m = sum([p.t_unplanned_down for p in phases]) + self.t_unplanned_m = sum(p.t_unplanned_down for p in phases) t = [p.t for p in phases] lens = np.array([len(i) for i in t]) self.mci = np.cumsum(lens) diff --git a/bluemira/fuel_cycle/tools.py b/bluemira/fuel_cycle/tools.py index f0c9d07a35..297baaa9fd 100644 --- a/bluemira/fuel_cycle/tools.py +++ b/bluemira/fuel_cycle/tools.py @@ -397,7 +397,7 @@ def find_max_load_factor(time_years: np.ndarray, time_fpy: np.ndarray) -> float: """ _t, rt = discretise_1d(time_years, time_fpy, int(np.ceil(time_years[-1]))) try: - a = max([x - x1 for x1, x in pairwise(rt)]) + a = max(x - x1 for x1, x in pairwise(rt)) except ValueError: # Shortened time overflow error (only happens when debugging) a = 1 @@ -621,9 +621,8 @@ def _fountain_linear_sink( inventory = min_inventory topup = min_inventory * (1 - np.exp(-T_LAMBDA * (t_out - t_in - t15))) - m_out_temp = mass_in - m_in * t15 - topup - m_out_temp = max(m_out_temp, 0) - m_out = m_out_temp / dts # spread evenly over timestep + # spread evenly over timestep + m_out = max(mass_in - m_in * t15 - topup, 0) / dts elif i_mdot2 >= max_inventory: # Case (unlikely) where massive overshoot occurs # TODO: Handle properly @@ -634,9 +633,9 @@ def _fountain_linear_sink( topup = max_inventory * ( 1 - np.exp(-T_LAMBDA * (t_out - t_in - t175 - t15)) ) - m_out_temp = mass_in - topup - m_in * t15 - (1 - fs) * m_in * t175 - m_out_temp = max(m_out_temp, 0) - m_out = m_out_temp / dts + m_out = ( + max(mass_in - topup - m_in * t15 - (1 - fs) * m_in * t175, 0) / dts + ) else: # Case where successfully crosses up dt2 = t_out - t_in - t15 @@ -662,10 +661,8 @@ def _fountain_linear_sink( inventory = min_inventory topup = min_inventory * (1 - np.exp(-T_LAMBDA * (t_out - t_in - t15))) - m_out_temp = mass_in - m_in * t15 - topup - if m_out_temp < 0: - m_out_temp = 0 - m_out = m_out_temp / dts # spread evenly over timestep + # spread evenly over timestep + m_out = max(mass_in - m_in * t15 - topup, 0) / dts elif i_mdot >= max_inventory: t15 = _find_t15(inventory, 1 - fs, m_in, t_in, t_out, max_inventory) diff --git a/bluemira/gen_params.py b/bluemira/gen_params.py index 086a1d0bf4..b7e36a71cf 100644 --- a/bluemira/gen_params.py +++ b/bluemira/gen_params.py @@ -199,8 +199,7 @@ def main(): for vv in param_classes.values(): add_to_dict(vv, output, params) - with open(Path(args.directory, "params.py"), "w") as fh: - fh.write(create_parameterframe(params)) + Path(args.directory, "params.py").write_text(create_parameterframe(params)) json_writer(output, file=Path(args.directory, "params.json")) else: diff --git a/bluemira/geometry/parameterisations.py b/bluemira/geometry/parameterisations.py index 82de8b3ca9..8da96b3ffd 100644 --- a/bluemira/geometry/parameterisations.py +++ b/bluemira/geometry/parameterisations.py @@ -1272,7 +1272,7 @@ def create_shape(self, label: str = "") -> BluemiraWire: l_end = variables[15:] tilt = np.deg2rad(tilt) - height = 0.5 * height + height *= 0.5 ds_z = flat * height * np.cos(tilt) ds_x = flat * height * np.sin(tilt) diff --git a/bluemira/geometry/plane.py b/bluemira/geometry/plane.py index 050104c1e5..93b3f4f188 100644 --- a/bluemira/geometry/plane.py +++ b/bluemira/geometry/plane.py @@ -117,7 +117,7 @@ def axis(self, value: Iterable[float]): def move(self, vector: Iterable[float]): """Moves the Plane along the given vector""" - self.base = self.base + np.array(vector) + self.base += np.array(vector) def __repr__(self) -> str: """ diff --git a/bluemira/geometry/tools.py b/bluemira/geometry/tools.py index 3fb6ccc3f6..1b40a9b362 100644 --- a/bluemira/geometry/tools.py +++ b/bluemira/geometry/tools.py @@ -1391,9 +1391,7 @@ def _signed_distance_2D(point: np.ndarray, polygon: np.ndarray) -> float: e = polygon[j] - polygon[i] w = point - polygon[i] b = w - e * _nb_clip(_nb_dot_2D(w, e) / _nb_dot_2D(e, e), 0.0, 1.0) - d_new = _nb_dot_2D(b, b) - if d_new < d: - d = d_new + d = min(_nb_dot_2D(b, b), d) cond = np.array([ point[1] >= polygon[i][1], diff --git a/bluemira/magnetostatics/baseclass.py b/bluemira/magnetostatics/baseclass.py index 6d7940ad57..a4586ddda1 100644 --- a/bluemira/magnetostatics/baseclass.py +++ b/bluemira/magnetostatics/baseclass.py @@ -136,9 +136,9 @@ def rotate(self, angle: float, axis: np.ndarray | str): The axis of rotation """ r = rotation_matrix(np.deg2rad(angle), axis).T - self._origin = self._origin @ r + self._origin @= r self._points = np.array([p @ r for p in self._points], dtype=object) - self._dcm = self._dcm @ r + self._dcm @= r def _local_to_global( self, points: npt.NDArray[np.float64] @@ -315,7 +315,7 @@ def rotate(self, angle: float, axis: np.ndarray | str): """ for source in self.sources: source.rotate(angle, axis) - self._points = self._points @ rotation_matrix(angle, axis) + self._points @= rotation_matrix(angle, axis) def plot(self, ax: Axes | None = None, *, show_coord_sys: bool = False): """ diff --git a/bluemira/magnetostatics/biot_savart.py b/bluemira/magnetostatics/biot_savart.py index 2d509a5ea8..6b039b53c9 100644 --- a/bluemira/magnetostatics/biot_savart.py +++ b/bluemira/magnetostatics/biot_savart.py @@ -238,11 +238,11 @@ def rotate(self, angle: float, axis: str | np.ndarray): The axis of rotation """ r = rotation_matrix(np.deg2rad(angle), axis).T - self._points = self._points @ r - self._d_l = self._d_l @ r - self._mid_points = self._mid_points @ r - self.ref_d_l = self.ref_d_l @ r - self.ref_mid_points = self.ref_mid_points @ r + self._points @= r + self._d_l @= r + self._mid_points @= r + self.ref_d_l @= r + self.ref_mid_points @= r self._arrays = [array @ r for array in self._arrays] def plot(self, ax: Axes | None = None, *, show_coord_sys: bool = False): diff --git a/bluemira/magnetostatics/semianalytic_2d.py b/bluemira/magnetostatics/semianalytic_2d.py index c0a714927a..5e73ec5c14 100644 --- a/bluemira/magnetostatics/semianalytic_2d.py +++ b/bluemira/magnetostatics/semianalytic_2d.py @@ -81,7 +81,7 @@ def _partial_z_integrand_nojit(phi: float, rr: float, zz: float) -> float: result = result - 0.5 * rr if rr - 1 < EPS else result - 0.5 / rr # F3 if 0.5 * np.pi * sin_phi > 1e-9: # noqa: PLR2004 - result = result - sin_phi * np.arctan(zz * (rr - cos_phi) / (r0 * sin_phi)) + result -= sin_phi * np.arctan(zz * (rr - cos_phi) / (r0 * sin_phi)) return result @@ -127,7 +127,7 @@ def _get_working_coords( """ Convert coil and global coordinates to working coordinates. """ - z = z - zc + z = z - zc # numba issue # noqa: PLR6104 r1, r2 = (xc - d_xc) / x, (xc + d_xc) / x z1, z2 = (-d_zc - z) / x, (d_zc - z) / x j_tor = 1 / (4 * d_xc * d_zc) # Keep current out of the equation @@ -293,7 +293,7 @@ def _full_psi_integrand(x, phi, xc, zc, z, d_xc, d_zc): """ Integrand for psi = xBz """ - z = z - zc + z = z - zc # numba issue # noqa: PLR6104 r1, r2 = (xc - d_xc) / x, (xc + d_xc) / x z1, z2 = (-d_zc - z) / x, (d_zc - z) / x return x**2 * ( diff --git a/bluemira/mesh/meshing.py b/bluemira/mesh/meshing.py index 1165eaee83..b36010e769 100644 --- a/bluemira/mesh/meshing.py +++ b/bluemira/mesh/meshing.py @@ -11,9 +11,11 @@ from __future__ import annotations import inspect +import operator import pprint from dataclasses import asdict, dataclass from enum import Enum, IntEnum, auto +from pathlib import Path from typing import TYPE_CHECKING import gmsh @@ -346,7 +348,7 @@ def __create_dict_for_mesh_size(self, buffer: dict): points_lcar += [(p[1], v["lcar"]) for p in points_tags] for o in v["boundary"]: points_lcar += self.__create_dict_for_mesh_size(o) - points_lcar = sorted(points_lcar, key=lambda element: (element[0], element[1])) + points_lcar = sorted(points_lcar, key=operator.itemgetter(0, 1)) points_lcar.reverse() points_lcar = dict(points_lcar) return list(points_lcar.items()) @@ -585,9 +587,7 @@ def _save_mesh(meshfile: str = "Mesh.geo_unrolled"): @staticmethod def _finalise_mesh(logfile: str = "gmsh.log"): - with open(logfile, "w") as file_handler: - file_handler.write("\n".join(str(item) for item in gmsh.logger.get())) - + Path(logfile).write_text("\n".join(str(item) for item in gmsh.logger.get())) # This should be called when you are done using the Gmsh Python API: # gmsh.logger.stop() # gmsh.finalize() diff --git a/bluemira/radiation_transport/radiation_profile.py b/bluemira/radiation_transport/radiation_profile.py index ffaf379d62..b26ebb1c47 100644 --- a/bluemira/radiation_transport/radiation_profile.py +++ b/bluemira/radiation_transport/radiation_profile.py @@ -474,8 +474,8 @@ def radiation_distribution_plot( else: fig = ax.figure - p_min = min([np.amin(p) for p in power_density]) - p_max = max([np.amax(p) for p in power_density]) + p_min = min(np.amin(p) for p in power_density) + p_max = max(np.amax(p) for p in power_density) separatrix = self.eq.get_separatrix() if isinstance(separatrix, Coordinates): @@ -1164,8 +1164,8 @@ def radiation_distribution_plot(self, flux_tubes, power_density, firstwall, ax=N tubes = functools.reduce(operator.iadd, flux_tubes, []) power = functools.reduce(operator.iadd, power_density, []) - p_min = min([min(p) for p in power]) - p_max = max([max(p) for p in power]) + p_min = min(min(p) for p in power) + p_max = max(max(p) for p in power) plot_coordinates(firstwall, ax=ax, linewidth=0.5, fill=False) separatrix = self.eq.get_separatrix() diff --git a/bluemira/radiation_transport/radiation_tools.py b/bluemira/radiation_transport/radiation_tools.py index dbb2d58bcc..032835f528 100644 --- a/bluemira/radiation_transport/radiation_tools.py +++ b/bluemira/radiation_transport/radiation_tools.py @@ -370,8 +370,8 @@ def electron_density_and_temperature_sol_decay( far_sol_gradient = 1 - near_sol_gradient # power decay length modified according to the flux expansion - lambda_q_near = lambda_q_near * f_exp - lambda_q_far = lambda_q_far * f_exp + lambda_q_near *= f_exp + lambda_q_far *= f_exp # Assuming conduction-limited regime. lambda_t_near = t_factor * lambda_q_near diff --git a/bluemira/structural/geometry.py b/bluemira/structural/geometry.py index 6826457f83..0047070a6e 100644 --- a/bluemira/structural/geometry.py +++ b/bluemira/structural/geometry.py @@ -248,33 +248,36 @@ def add_element( e_nodes = sorted([elem.node_1.id_number, elem.node_2.id_number]) if e_nodes == new_element_nodes: - # An element already exists here, update properties - elem_id = elem.id_number - - element = Element( - self.nodes[node_id1], - self.nodes[node_id2], - elem_id, - cross_section, - material, - ) + # An element already exists here + break + else: + # There is no such Element; add a new one to the model + element = Element( + self.nodes[node_id1], + self.nodes[node_id2], + self.n_elements, + cross_section, + material, + ) + self.elements.append(element) + # Keep track of Element connectivity + self.nodes[node_id1].add_connection(element.id_number) + self.nodes[node_id2].add_connection(element.id_number) + return element.id_number - self.elements[elem_id] = element - return elem_id + # An element already exists here, update properties + elem_id = elem.id_number - # There is no such Element; add a new one to the model element = Element( self.nodes[node_id1], self.nodes[node_id2], - self.n_elements, + elem_id, cross_section, material, ) - self.elements.append(element) - # Keep track of Element connectivity - self.nodes[node_id1].add_connection(element.id_number) - self.nodes[node_id2].add_connection(element.id_number) - return element.id_number + + self.elements[elem_id] = element + return elem_id def remove_element(self, elem_id: int): """ diff --git a/bluemira/structural/plotting.py b/bluemira/structural/plotting.py index a378481c7d..841f1f196a 100644 --- a/bluemira/structural/plotting.py +++ b/bluemira/structural/plotting.py @@ -391,7 +391,7 @@ def _plot_element_load(self, element, load): load = arrow_scale(load, 10 * self.unit_length, self.force_size) dcm = element.lambda_matrix[0:3, 0:3] - load = load @ dcm + load @= dcm point = np.array( [element.node_1.x, element.node_1.y, element.node_1.z], dtype=float ) @@ -402,23 +402,17 @@ def _plot_distributed_load(self, element, load): length = element.length n = int(length * 10) dcm = element.lambda_matrix[0:3, 0:3] - load = load["w"] * LOAD_STR_VECTORS[load["sub_type"]] / length - load = arrow_scale(load, 10 * self.unit_length, self.force_size) + load = load["w"] * LOAD_STR_VECTORS[load["sub_type"]] / length + load = arrow_scale(load, 10 * self.unit_length, self.force_size) @ dcm + load = (load * np.ones((n, 3))).T - load = load @ dcm - load = load * np.ones((3, n)).T - load = load.T point = np.array( [element.node_1.x, element.node_1.y, element.node_1.z], dtype=float ) - point = point * np.ones((3, n)).T - point += ( - np.array([x * np.array([1.0, 0.0, 0.0]) for x in np.linspace(0, length, n)]) - @ dcm - ) - point = point.T - self.ax.quiver(*point - load, *load, color="r") + point = point * np.ones((n, 3)) # noqa: PLR6104 + point += (np.linspace(0, length, n)[:, None] * np.array([1.0, 0, 0])) @ dcm + self.ax.quiver(*point.T - load, *load, color="r") def _set_aspect_equal(self): """ diff --git a/bluemira/utilities/opt_variables.py b/bluemira/utilities/opt_variables.py index 31b45f1c4b..3ce7349af6 100644 --- a/bluemira/utilities/opt_variables.py +++ b/bluemira/utilities/opt_variables.py @@ -11,6 +11,7 @@ from __future__ import annotations import json +import operator from dataclasses import MISSING, Field, field from pathlib import Path from typing import TYPE_CHECKING, TextIO, TypedDict @@ -615,7 +616,9 @@ def tabulate(self, tablefmt: str = "fancy_grid") -> str: tabulated: The tabulated data """ - records = sorted([val.as_dict() for val in self], key=lambda x: x["name"]) + records = sorted( + [val.as_dict() for val in self], key=operator.itemgetter("name") + ) return f"{self.__class__.__name__}\n" + tabulate( records, diff --git a/eudemo/eudemo/maintenance/lower_port/builder.py b/eudemo/eudemo/maintenance/lower_port/builder.py index 46aa23ab92..39bb5eb6bf 100644 --- a/eudemo/eudemo/maintenance/lower_port/builder.py +++ b/eudemo/eudemo/maintenance/lower_port/builder.py @@ -250,11 +250,11 @@ def build_lower_port_xyz( straight_duct = boolean_fuse([straight_duct_backwall, straight_duct_length]) angled_pieces = boolean_cut(angled_duct, [straight_duct]) - angled_top = sorted( + angled_top = min( angled_pieces, key=lambda s: np.hypot(s.center_of_mass[0], s.center_of_mass[2]) - )[0] + ) angled_void_pieces = boolean_cut(angled_void, [straight_duct_void]) - angled_void_piece = sorted(angled_void_pieces, key=lambda s: -s.center_of_mass[2])[0] + angled_void_piece = min(angled_void_pieces, key=lambda s: -s.center_of_mass[2]) void = boolean_fuse([angled_void_piece, straight_duct_void]) straight_with_hole = boolean_cut(straight_duct, [angled_top])[0] diff --git a/eudemo/eudemo/maintenance/lower_port/duct_designer.py b/eudemo/eudemo/maintenance/lower_port/duct_designer.py index e8f4a39c40..e12cf18b63 100644 --- a/eudemo/eudemo/maintenance/lower_port/duct_designer.py +++ b/eudemo/eudemo/maintenance/lower_port/duct_designer.py @@ -8,6 +8,7 @@ EU-DEMO Lower Port Duct KOZ Designer """ +import operator from dataclasses import dataclass import numpy as np @@ -154,7 +155,7 @@ def _get_div_pts_at_angle(self) -> tuple[tuple[float, ...], ...]: closest_pts = self._closest_points(search_wire, self.divertor_face) # just take the point with the highest z, if there's more than one - z_highest_pt = max(closest_pts, key=lambda p: p[2]) + z_highest_pt = max(closest_pts, key=operator.itemgetter(2)) return (z_highest_pt[0], z_highest_pt[2]), self.div_wall_join_pt @@ -340,8 +341,8 @@ def _straight_duct_xz_boundary(self, angled_duct_boundary: BluemiraWire): ) # find the top and bottom itc points - itc_top_ob_pt = max(itc_pts, key=lambda p: p[2]) - itc_bot_ib_pt = min(itc_pts, key=lambda p: p[2]) + itc_top_ob_pt = max(itc_pts, key=operator.itemgetter(2)) + itc_bot_ib_pt = min(itc_pts, key=operator.itemgetter(2)) # remap to 2D point itc_top_ob_pt = (itc_top_ob_pt[0], itc_top_ob_pt[2]) diff --git a/eudemo/eudemo/maintenance/upper_port.py b/eudemo/eudemo/maintenance/upper_port.py index 81e7aa0981..8093b6f8c3 100644 --- a/eudemo/eudemo/maintenance/upper_port.py +++ b/eudemo/eudemo/maintenance/upper_port.py @@ -8,6 +8,7 @@ Some crude EU-DEMO remote maintenance considerations. """ +import operator from dataclasses import dataclass import numpy as np @@ -148,7 +149,7 @@ def get_outer_cut_point(self, ci: float, gamma: float): # Get the last intersection with the angled cut plane and the outer intersections = slice_shape(self.bb.boundary[0], angled_cut_plane) intersections = intersections[intersections[:, -1] > z + EPS] - return min(intersections, key=lambda x: x[-1]) + return min(intersections, key=operator.itemgetter(-1)) @dataclass diff --git a/eudemo/eudemo/tools.py b/eudemo/eudemo/tools.py index 3a6cc7a876..9fb3629f0d 100644 --- a/eudemo/eudemo/tools.py +++ b/eudemo/eudemo/tools.py @@ -8,6 +8,8 @@ A collection of tools used in the EU-DEMO design. """ +import operator + import numpy as np from bluemira.base.components import PhysicalComponent @@ -26,7 +28,7 @@ def get_inner_cut_point(breeding_blanket_xz, r_inner_cut): # Get the first intersection with the vertical inner cut plane intersections = slice_shape(breeding_blanket_xz.boundary[0], cut_plane) intersections = intersections[intersections[:, -1] > 0.0] - return sorted(intersections, key=lambda x: x[-1])[0] + return min(intersections, key=operator.itemgetter(-1)) def make_2d_view_components( diff --git a/eudemo/eudemo_tests/maintenance/test_lower_port.py b/eudemo/eudemo_tests/maintenance/test_lower_port.py index ec0e4db275..43a18e8e85 100644 --- a/eudemo/eudemo_tests/maintenance/test_lower_port.py +++ b/eudemo/eudemo_tests/maintenance/test_lower_port.py @@ -150,13 +150,13 @@ def test_duct_angle(self, duct_angle, tf_wp_depth): rotated_duct = duct_xyz_cad.deepcopy() rotated_duct.rotate(degree=-180 / self.duct_des_params.n_TF.value) phat_tf = self._make_tf(10) - cut_duct = sorted( + cut_duct = min( boolean_cut(rotated_duct, phat_tf), key=lambda shape: -shape.volume - )[0] + ) koz = lp_duct_xz_koz.deepcopy() koz.translate((0, -5, 0)) koz = extrude_shape(koz, (0, 10, 0)) - cut_koz = sorted(boolean_cut(koz, phat_tf), key=lambda shape: -shape.volume)[0] + cut_koz = min(boolean_cut(koz, phat_tf), key=lambda shape: -shape.volume) fuse = boolean_fuse([cut_koz, cut_duct]) assert cut_koz.volume == pytest.approx(fuse.volume) diff --git a/eudemo/eudemo_tests/pf_coils/test_tools.py b/eudemo/eudemo_tests/pf_coils/test_tools.py index ed9d6d377b..7a603d99ff 100644 --- a/eudemo/eudemo_tests/pf_coils/test_tools.py +++ b/eudemo/eudemo_tests/pf_coils/test_tools.py @@ -60,11 +60,11 @@ def setup_class(cls): @pytest.mark.parametrize("track", tracks) def test_cuts(self, track): segments = boolean_cut(track, self.exclusions) - actual_length = sum([seg.length for seg in segments]) + actual_length = sum(seg.length for seg in segments) mapper = make_coil_mapper(track, self.exclusions, self.coils) - interp_length = sum([ + interp_length = sum( tool.geometry.length for tool in mapper.interpolators.values() - ]) + ) assert np.isclose(actual_length, interp_length, rtol=1e-2) @pytest.mark.parametrize("track", tracks) diff --git a/examples/equilibria/Spherical_Approximation_how_it_works.ex.py b/examples/equilibria/Spherical_Approximation_how_it_works.ex.py index c8672c9de9..f0a0353ae5 100644 --- a/examples/equilibria/Spherical_Approximation_how_it_works.ex.py +++ b/examples/equilibria/Spherical_Approximation_how_it_works.ex.py @@ -303,7 +303,7 @@ approx_psi_vac_data = psi_harmonic_amplitudes[0] * np.ones(np.shape(total_psi)) for degree in np.arange(1, plot_max_degree + 1): - approx_psi_vac_data = approx_psi_vac_data + ( + approx_psi_vac_data += ( psi_harmonic_amplitudes[degree] * eq.x * (r / r_t) ** degree diff --git a/examples/equilibria/fem_fixed_boundary/fem_boundary_conditions_example.py b/examples/equilibria/fem_fixed_boundary/fem_boundary_conditions_example.py index 747dd0686d..9794af36d5 100644 --- a/examples/equilibria/fem_fixed_boundary/fem_boundary_conditions_example.py +++ b/examples/equilibria/fem_fixed_boundary/fem_boundary_conditions_example.py @@ -294,7 +294,7 @@ def create_mesh(solovev, LCFS, lcar): # than that with exact solution. for dirich_bc in (None, dirichlet_bcs_1), (dirichlet_bcs_2, dirichlet_bcs_3): for d in dirich_bc: - i = i + 1 + i += 1 print(f"boundary conditions n.{i}") # solve the Grad-Shafranov equation diff --git a/pyproject.toml b/pyproject.toml index b24ebc9f87..a4f4399c35 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -74,9 +74,9 @@ examples = ["notebook", "jupytext"] pinned = [ "nlopt==2.7.1", "numba==0.59.1", - "numba-scipy @ git+https://github.com/numba/numba-scipy@1e2f244", + "numba-scipy==0.4.0", "numpy==1.26.4", - "matplotlib==3.8.3", + "matplotlib==3.8.4", "scipy==1.10.1", ] openmc = ["openmc>=0.14.0", "openmc_data"] @@ -316,8 +316,7 @@ ignore-names = [ "bluemira/codes/__init__.py" = ["E402"] "bluemira/codes/process/model_mapping.py" = ["PLR6301"] "bluemira/geometry/parameterisations.py" = ["E731"] -"bluemira/codes/plasmod/api/_outputs.py" = ["N815"] -"bluemira/codes/plasmod/api/_inputs.py" = ["N815"] +"bluemira/codes/plasmod/api/{_inputs,_outputs}.py" = ["N815"] "data/*" = ["INP001"] "scripts/*" = ["INP001", "CPY001", "T201"] "setup.py" = ["CPY001"] @@ -327,34 +326,7 @@ ignore-names = [ "examples/optimisation/geometry_optimisation.ex.py" = ["E402"] "examples/optimisation/nonlinearly_constrained_problem.ex.py" = ["E402", "W505"] "eudemo/eudemo/reactor.py" = ["ARG001"] -"eudemo/eudemo_tests/*" = [ - "INP001", - "PLR2004", - "PLR6301", - "S101", - "F841", - "D100", - "D101", - "D102", - "D103", - "D104", - "D105", - "D202", - "D205", - "D210", - "D300", - "D301", - "D401", - "D403", - "D404", - "D406", - "D409", - "N802", - "PLC2701", - "PT023", - "T201", -] -"tests/*" = [ +"{tests,eudemo/eudemo_tests}/*" = [ "INP001", "PLR2004", "PLR6301", diff --git a/requirements-conda.txt b/requirements-conda.txt index 82d7faf50f..fd80e2060d 100644 --- a/requirements-conda.txt +++ b/requirements-conda.txt @@ -1,12 +1,12 @@ -gmsh-interop==2021.1.1 -h5py==3.10.0 +gmsh-interop==2024.1 +h5py==3.11.0 importlib-metadata==7.1.0 -pybind11==2.11.1 -pybind11-global==2.11.1 +pybind11==2.12.0 +pybind11-global==2.12.0 PySide2==5.15.8 -pytools==2024.1.1 +pytools==2024.1.2 PyYAML==6.0.1 shiboken2==5.15.8 -typing_extensions==4.10.0 +typing_extensions==4.11.0 vtk==9.2.6 zipp==3.18.1 diff --git a/requirements-develop.txt b/requirements-develop.txt index 162298854b..1f3163cfd7 100644 --- a/requirements-develop.txt +++ b/requirements-develop.txt @@ -1,42 +1,42 @@ alabaster==0.7.16 -astroid==3.1.0 +astroid==3.2.0 attrs==23.2.0 certifi==2024.2.2 cfgv==3.4.0 charset-normalizer==3.3.2 -coverage[toml]==7.4.4 +coverage[toml]==7.5.1 distlib==0.3.8 docutils==0.20.1 -filelock==3.13.3 +filelock==3.14.0 greenlet==3.0.3 -identify==2.5.35 +identify==2.5.36 idna==3.7 imagesize==1.4.1 importlib-metadata==7.1.0 iniconfig==2.0.0 Jinja2==3.1.4 jupyter-cache==1.0.0 -jupytext==1.16.1 +jupytext==1.16.2 MarkupSafe==2.1.5 mypy-extensions==1.0.0 -myst-nb==1.0.0 -myst-parser==2.0.0 +myst-nb==1.1.0 +myst-parser==3.0.1 nbclient==0.10.0 nodeenv==1.8.0 -platformdirs==4.2.0 -pluggy==1.4.0 -pre-commit==3.7.0 -Pygments==2.17.2 -pytest==8.1.1 +platformdirs==4.2.1 +pluggy==1.5.0 +pre-commit==3.7.1 +Pygments==2.18.0 +pytest==8.2.0 pytest-cov==5.0.0 pytest-html==4.1.1 pytest-metadata==3.1.1 pytest-json-report==1.5.0 PyYAML==6.0.1 requests==2.31.0 -ruff==0.3.4 +ruff==0.4.4 snowballstemmer==2.2.0 -Sphinx==7.2.6 +Sphinx==7.3.7 sphinx-autoapi==3.0.0 sphinx-copybutton==0.5.2 sphinx-rtd-theme==2.0.0 @@ -46,10 +46,10 @@ sphinxcontrib-htmlhelp==2.0.5 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.7 sphinxcontrib-serializinghtml==1.1.10 -sqlalchemy==2.0.29 +sqlalchemy==2.0.30 toml==0.10.2 tomli==2.0.1 -typing_extensions==4.10.0 +typing_extensions==4.11.0 urllib3==2.2.1 -virtualenv==20.25.1 +virtualenv==20.26.1 zipp==3.18.1 diff --git a/requirements-examples.txt b/requirements-examples.txt index f9d0fb6337..17a2eb2902 100644 --- a/requirements-examples.txt +++ b/requirements-examples.txt @@ -12,24 +12,24 @@ defusedxml==0.7.1 executing==2.0.1 fastjsonschema==2.19.1 importlib-resources==6.4.0 -ipykernel==6.29.3 -ipython==8.22.2 +ipykernel==6.29.4 +ipython==8.24.0 jedi==0.19.1 -jsonschema==4.21.1 +jsonschema==4.22.0 jupyter-client==8.6.1 jupyter-core==5.7.2 jupyterlab-pygments==0.3.0 -jupytext==1.16.1 +jupytext==1.16.2 MarkupSafe==2.1.5 -matplotlib-inline==0.1.6 +matplotlib-inline==0.1.7 mistune==3.0.2 nbclient==0.10.0 -nbconvert==7.16.3 -nbformat==5.10.3 +nbconvert==7.16.4 +nbformat==5.10.4 nest-asyncio==1.6.0 -notebook==7.1.2 +notebook==7.1.3 pandocfilters==1.5.1 -parso==0.8.3 +parso==0.8.4 pexpect==4.9.0 pickleshare==0.7.5 prometheus-client==0.20.0 @@ -37,16 +37,16 @@ prompt-toolkit==3.0.43 psutil==5.9.8 ptyprocess==0.7.0 pure-eval==0.2.2 -pycparser==2.21 -Pygments==2.17.2 -pyzmq==25.1.2 -Send2Trash==1.8.2 +pycparser==2.22 +Pygments==2.18.0 +pyzmq==26.0.3 +Send2Trash==1.8.3 soupsieve==2.5 stack-data==0.6.3 terminado==0.18.1 -tinycss2==1.2.1 +tinycss2==1.3.0 tornado==6.4 -traitlets==5.14.2 +traitlets==5.14.3 wcwidth==0.2.13 webencodings==0.5.1 zipp==3.18.1 diff --git a/requirements.txt b/requirements.txt index 88df75f4b9..bd3e3b8bbc 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,16 +1,16 @@ anytree==2.12.1 asteval==0.9.32 -Babel==2.14.0 +Babel==2.15.0 cherab==1.4.0 click==8.1.7 -contourpy==1.2.0 +contourpy==1.2.1 CoolProp==6.6.0 cycler==0.12.1 -fonttools==4.50.0 +fonttools==4.51.0 fortranformat==2.0.0 -gmsh==4.12.2 -imageio==2.34.0 -joblib==1.3.2 +gmsh==4.13.0 +imageio==2.34.1 +joblib==1.4.2 kiwisolver==1.4.5 llvmlite==0.42.0 matplotlib==3.8.3 @@ -18,28 +18,28 @@ neutronics-material-maker==1.1.4 nlopt==2.7.1 meshio==5.3.5 numba==0.59.1 -numba-scipy @ git+https://github.com/numba/numba-scipy@1e2f244 -numexpr==2.9.0 +numba-scipy==0.4.0 +numexpr==2.10.0 numpy==1.26.4 openmc_data==0.2.2 packaging==24.0 -pandas==2.2.1 +pandas==2.2.2 periodictable==1.7.0 Pillow==10.3.0 Pint==0.23 pyclipper==1.3.0.post5 -polyscope==2.1.0 +polyscope==2.2.1 pyparsing==3.1.2 pypet==0.6.1 python-dateutil==2.9.0.post0 pytz==2024.1 -pyvista==0.43.4 +pyvista==0.43.7 rich==13.7.1 -scikit-learn==1.4.1.post1 +scikit-learn==1.4.2 scipy==1.10.1 seaborn==0.13.2 six==1.16.0 tables==3.9.2 tabulate==0.9.0 -threadpoolctl==3.4.0 +threadpoolctl==3.5.0 typeguard==4.2.1 diff --git a/scripts/openmc_data_download/multithreaded_download.py b/scripts/openmc_data_download/multithreaded_download.py index 16aa91c767..135b9e4860 100644 --- a/scripts/openmc_data_download/multithreaded_download.py +++ b/scripts/openmc_data_download/multithreaded_download.py @@ -13,7 +13,7 @@ from rich.progress import Progress -async def get_size(url: str, timeout: int = 10) -> int: +async def get_size(url: str, timeout: int = 10) -> int: # noqa: RUF029 """Get size of file""" response = requests.head( # noqa: ASYNC100 url, allow_redirects=True, timeout=timeout diff --git a/tests/balance_of_plant/test_data/sankey_test.png b/tests/balance_of_plant/test_data/sankey_test.png index ec9b66b29d..1fa09f10ce 100644 Binary files a/tests/balance_of_plant/test_data/sankey_test.png and b/tests/balance_of_plant/test_data/sankey_test.png differ diff --git a/tests/balance_of_plant/test_plotting.py b/tests/balance_of_plant/test_plotting.py index eaa41d4a84..086a558fc8 100644 --- a/tests/balance_of_plant/test_plotting.py +++ b/tests/balance_of_plant/test_plotting.py @@ -4,10 +4,8 @@ # # SPDX-License-Identifier: LGPL-2.1-or-later -import tempfile from pathlib import Path -import matplotlib.pyplot as plt from matplotlib.testing import compare as mpl_compare from bluemira.balance_of_plant.plotting import SuperSankey @@ -16,7 +14,7 @@ class TestSuperSankey: - def test_sankey_ring(self): + def test_sankey_ring(self, tmp_path): plot_defaults(force=True) scale = 0.001 @@ -56,10 +54,10 @@ def test_sankey_ring(self): connect=[(2, 0), (1, 1)], ) sankey.finish() - figure = plt.gcf() - new_file = tempfile.NamedTemporaryFile() + figure = sankey.ax.figure + new_file = tmp_path / "sankey_test.png" figure.savefig(new_file) path = get_bluemira_path("balance_of_plant/test_data", subfolder="tests") reference_file = Path(path, "sankey_test.png") - assert mpl_compare.compare_images(reference_file, new_file.name, 0.001) is None + assert mpl_compare.compare_images(reference_file, new_file, 0.001) is None diff --git a/tests/base/test_logs.py b/tests/base/test_logs.py index b6398d5e47..0c6f013727 100644 --- a/tests/base/test_logs.py +++ b/tests/base/test_logs.py @@ -31,7 +31,7 @@ def setup_class(cls): cls.orig_log.handlers or cls.orig_log.parent.handlers ) cls.original_level = LogLevel( - max([handler.level for handler in cls.original_handlers]) + max(handler.level for handler in cls.original_handlers) ) @classmethod diff --git a/tests/codes/plasmod/test_solver.py b/tests/codes/plasmod/test_solver.py index f3aac31746..cb2ced70bc 100644 --- a/tests/codes/plasmod/test_solver.py +++ b/tests/codes/plasmod/test_solver.py @@ -462,8 +462,7 @@ def _plasmod_run_subprocess_fake(command: list[str], **_): """ def write_file(file_path: str, content: str): - with open(file_path, "w") as f: - f.write(content) + Path(file_path).write_text(content) output_file = command[2] output_file_content = TestPlasmodSolver.read_data_file("sample_output.dat") diff --git a/tests/equilibria/fem_fixed_boundary/test_fem_utils.py b/tests/equilibria/fem_fixed_boundary/test_fem_utils.py index dc7f0c4eb1..ea916c00f1 100644 --- a/tests/equilibria/fem_fixed_boundary/test_fem_utils.py +++ b/tests/equilibria/fem_fixed_boundary/test_fem_utils.py @@ -4,6 +4,7 @@ # # SPDX-License-Identifier: LGPL-2.1-or-later +import operator from pathlib import Path import gmsh @@ -76,12 +77,9 @@ def test_integrate_f(self): area = integrate_f(func, self.mesh, self.ct, 1) assert np.allclose(area, self.l**2) - def expr(x): - return x[0] - V = FunctionSpace(self.mesh, ("Lagrange", 1)) # noqa: N806 dofs_points = V.tabulate_dof_coordinates() func = BluemiraFemFunction(V) - func.x.array[:] = np.array([expr(x) for x in dofs_points]) + func.x.array[:] = np.array([operator.itemgetter(0)(x) for x in dofs_points]) area = integrate_f(func, self.mesh, self.ct, 1) assert np.allclose(area, 0.5 * self.l**2 * self.l) diff --git a/tests/equilibria/test_coils.py b/tests/equilibria/test_coils.py index bf9cafbbeb..bc418572d3 100644 --- a/tests/equilibria/test_coils.py +++ b/tests/equilibria/test_coils.py @@ -346,15 +346,11 @@ def test_fields(self, fieldtype): ] for point in points: - coil_psi = sum([ + coil_psi = sum( getattr(coil, f"psi{fieldtype}")(*point) for coil in self.coils - ]) - coil_Bx = sum([ - getattr(coil, f"Bx{fieldtype}")(*point) for coil in self.coils - ]) - coil_Bz = sum([ - getattr(coil, f"Bz{fieldtype}")(*point) for coil in self.coils - ]) + ) + coil_Bx = sum(getattr(coil, f"Bx{fieldtype}")(*point) for coil in self.coils) + coil_Bz = sum(getattr(coil, f"Bz{fieldtype}")(*point) for coil in self.coils) circuit_psi = getattr(self.circuit, f"psi{fieldtype}")(*point) circuit_Bx = getattr(self.circuit, f"Bx{fieldtype}")(*point) @@ -385,7 +381,7 @@ def test_attributes(self): def test_position(self): circ = copy.deepcopy(self.circuit) before = circ.x.copy() - circ.x = circ.x + 1 + circ.x = circ.x + 1 # immuatble array # noqa: PLR6104 assert np.allclose(before + 1, circ.x) @@ -643,7 +639,7 @@ def test_normal(self): test_m = np.zeros((3, 3)) test_m[idxs] = tri_upper - test_m = test_m + test_m.T + test_m += test_m.T diag = np.diag_indices(3) m[diag] = 0.0 assert np.allclose(m, test_m) diff --git a/tests/equilibria/test_st_equilibrium.py b/tests/equilibria/test_st_equilibrium.py index 05147f2f32..d0db7c4e87 100644 --- a/tests/equilibria/test_st_equilibrium.py +++ b/tests/equilibria/test_st_equilibrium.py @@ -155,8 +155,8 @@ def test_equilibrium(self): # Scale up Agnieszka isoflux constraints size_scaling = R_0 / 2.5 - x_div = size_scaling * x_div - z_div = size_scaling * z_div + x_div *= size_scaling + z_div *= size_scaling xx = np.concatenate([x_core, x_div]) zz = np.concatenate([z_core, z_div]) diff --git a/tests/geometry/test_face.py b/tests/geometry/test_face.py index 2b4ffd6dcd..1decf19391 100644 --- a/tests/geometry/test_face.py +++ b/tests/geometry/test_face.py @@ -100,7 +100,7 @@ class TestNormalAt: @pytest.mark.parametrize("normal", normals) def test_circle_normal(self, normal): - normal = normal / np.linalg.norm(normal) + normal /= np.linalg.norm(normal) circle = BluemiraFace(make_circle(axis=normal)) np.testing.assert_allclose(circle.normal_at(), normal) @@ -121,7 +121,7 @@ def test_xy_polygon_normal(self, alphas): def test_curved_solid_face_normals(self, wire): face = BluemiraFace(wire) solid = extrude_shape(face, (10, 1, 1)) - biggest_face = sorted(solid.faces, key=lambda face: face.area)[-1] + biggest_face = max(solid.faces, key=lambda face: face.area) normal_1 = biggest_face.normal_at(0, 0) normal_2 = biggest_face.normal_at(0.5, 0.5) assert not np.allclose(normal_1, normal_2) @@ -129,7 +129,7 @@ def test_curved_solid_face_normals(self, wire): @pytest.mark.parametrize("wire", wires) def test_curved_shell_face_normals(self, wire): shell = extrude_shape(wire, (10, 1, 1)) - biggest_face = sorted(shell.faces, key=lambda face: face.area)[-1] + biggest_face = max(shell.faces, key=lambda face: face.area) normal_1 = biggest_face.normal_at(0, 0) normal_2 = biggest_face.normal_at(0.5, 0.5) assert not np.allclose(normal_1, normal_2) diff --git a/tests/geometry/test_tools.py b/tests/geometry/test_tools.py index fec9e229e1..5fdcd8d0ef 100644 --- a/tests/geometry/test_tools.py +++ b/tests/geometry/test_tools.py @@ -752,7 +752,7 @@ def test_simple_rectangle_chamfer(self, wire, radius): n = 4 if wire.is_closed() else 2 # I'll be honest, I don't understand why this modified radius happens... # I worry about what happens at other angles... - radius = 0.5 * np.sqrt(2) * radius + radius *= 0.5 * np.sqrt(2) correct_length = wire.length - n * 2 * radius correct_length += n * np.sqrt(2 * radius**2) diff --git a/tests/magnetostatics/test_circuits.py b/tests/magnetostatics/test_circuits.py index 3c9ca90249..cb2197c93b 100644 --- a/tests/magnetostatics/test_circuits.py +++ b/tests/magnetostatics/test_circuits.py @@ -155,7 +155,7 @@ class TestArbitraryPlanarXSCircuit: p_inputs = (pd_inputs, ta_inputs, pf_inputs) clockwises = [False] * len(p_inputs) + [True] * len(p_inputs) - p_inputs = p_inputs * 2 + p_inputs *= 2 parameterisations = tuple( [ PrincetonD,