Skip to content

Commit

Permalink
Papercut type fixes (#3022) (#3092)
Browse files Browse the repository at this point in the history
* 🐛 Fix "type: ignore" comment

* 🐛 Add  Missing type parameters for generic type "List"

* 🐛 Add missing return type annotation

* 🐛 Fix untyped function "modify" in typed context

* 🐛 Fix some missing return type annotations

* Update bluemira/base/constants.py

Co-authored-by: je-cook <[email protected]>

* 🐛 revert implicit return None typing

* 🐛 Fix annotations thing

* 🐛 Fix some no return type errors

* 🐛 Fix some Missing return type annotation error in bluemira.fuel_cycle

* 🐛 Fix some "missing a return type annotation" errors in bluemira.builders

* 🐛 Fix missing return type errors in bluemira.materials

* 🐛 Fix some missing return type errors

* 🐛 Fix some missing return type errors in bluemira.structural

* 🐛 Fix missing return type errors in bluemira.magnetostatics

* 🐛 Fix missing return type errors in bluemira.utilities

* 🗑️ cleanup type: ignore comments from bluemira.structural

* 🐛 Add missing return type

* 🐛 Fix missing return type in bluemira.mesh

* 🗑️cleanup type: ignore comments in bluemira.materials

* 🗑️cleanup type: ignore comments in bluemira.magnetostatics

* 🐛 Fix missing return types in bluemira.geometry

* 🗑️ cleanup type: ignore comments in fuel cycle

* 🗑️ cleanup rest of the type: ignore comments

* 🐛 Fix some missing return type error from bluemira.equilibrium

* 🐛 fix some [type-arg]s

* ⚰️ remove any

* ⚰️ Remove None return types

* Update bluemira/gen_params.py

Co-authored-by: je-cook <[email protected]>

* Update bluemira/magnetostatics/finite_element_2d.py

Co-authored-by: je-cook <[email protected]>

---------

Co-authored-by: Athoy Nilima <[email protected]>
Co-authored-by: je-cook <[email protected]>
  • Loading branch information
3 people authored Mar 12, 2024
1 parent 7163920 commit d21b53a
Show file tree
Hide file tree
Showing 58 changed files with 157 additions and 114 deletions.
6 changes: 4 additions & 2 deletions bluemira/base/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
A collection of generic physical constants, conversions, and miscellaneous constants.
"""

from __future__ import annotations

from enum import Enum, auto
from typing import Callable, List, Optional, Union

Expand All @@ -29,7 +31,7 @@ class CoilType(Enum):
NONE = auto()

@classmethod
def _missing_(cls, value: str):
def _missing_(cls, value: Union[str, CoilType]) -> CoilType:
if not isinstance(value, str):
raise TypeError("Input must be a string.")
try:
Expand Down Expand Up @@ -194,7 +196,7 @@ def _transform(
reverse_transform: Callable[
[UnitRegistry, Union[float, complex, Quantity]], float
],
):
) -> Context:
formatters = ["{}", "{} / [time]"]

for form in formatters:
Expand Down
4 changes: 2 additions & 2 deletions bluemira/base/look_and_feel.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from getpass import getuser
from pathlib import Path
from textwrap import dedent, wrap
from typing import Callable, Dict, List, Optional
from typing import Callable, Dict, List, Optional, Union

from bluemira import __version__
from bluemira.base.constants import ANSI_COLOR, EXIT_COLOR
Expand Down Expand Up @@ -124,7 +124,7 @@ def count_slocs(
branch: str,
exts: Optional[List[str]] = None,
ignore: Optional[List[str]] = None,
) -> Dict:
) -> Dict[str, Union[int, List[int]]]:
"""
Counts lines of code within a given directory for a given git branch
Expand Down
6 changes: 3 additions & 3 deletions bluemira/base/parameter_frame/_parameter.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import copy
from dataclasses import dataclass
from typing import Dict, Generic, List, Optional, Tuple, Type, TypeVar, TypedDict, Union
from typing import Any, Generic, List, Optional, Tuple, Type, TypeVar, TypedDict, Union

import numpy as np
import pint
Expand Down Expand Up @@ -135,7 +135,7 @@ def __eq__(self, __o: object) -> bool:
return False
return (self.name == __o.name) and (self.value == o_value_with_correct_unit)

def __hash__(self):
def __hash__(self) -> int:
return hash((self._name, self._description, self._long_name))

def history(self) -> List[ParameterValue[ParameterValueType]]:
Expand All @@ -149,7 +149,7 @@ def set_value(self, new_value: ParameterValueType, source: str = ""):
self._source = source
self._add_history_record()

def to_dict(self) -> Dict:
def to_dict(self) -> dict[str, Any]:
"""Serialize the parameter to a dictionary."""
out = {
"name": self.name,
Expand Down
6 changes: 5 additions & 1 deletion bluemira/builders/_varied_offset.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
Module containing functions to generate variable offset curves
"""

from typing import Tuple

import numpy as np

from bluemira.geometry.error import GeometryError
Expand Down Expand Up @@ -99,7 +101,9 @@ def _throw_if_inputs_invalid(wire, inboard_offset_degree, outboard_offset_degree
)


def _sort_coords_by_angle(angles: np.ndarray, coords: np.ndarray):
def _sort_coords_by_angle(
angles: np.ndarray, coords: np.ndarray
) -> Tuple[np.ndarray, np.ndarray]:
"""Sort the given angles and use that to re-order the coords."""
angle_sort_idx = np.argsort(angles)
return angles[angle_sort_idx], coords[:, angle_sort_idx]
Expand Down
2 changes: 1 addition & 1 deletion bluemira/builders/coil_supports.py
Original file line number Diff line number Diff line change
Expand Up @@ -609,7 +609,7 @@ def bounds() -> Tuple[np.ndarray, np.ndarray]:
@staticmethod
def f_L_to_wire( # noqa: N802
wire: BluemiraWire, x_norm: Union[List[float], npt.NDArray]
):
) -> BluemiraWire:
"""
Convert a pair of normalised L values to a wire
"""
Expand Down
4 changes: 2 additions & 2 deletions bluemira/builders/tf_coils.py
Original file line number Diff line number Diff line change
Expand Up @@ -518,13 +518,13 @@ def objective(parameterisation: GeometryParameterisation) -> float:
"""
return parameterisation.create_shape().length

def keep_out_zones(self):
def keep_out_zones(self) -> list[KeepOutZone]:
"""
Keep out zone
"""
return self._keep_out_zone

def ineq_constraints(self):
def ineq_constraints(self) -> GeomConstraintT:
"""
Inequality constraints
"""
Expand Down
2 changes: 1 addition & 1 deletion bluemira/builders/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ def circular_pattern_component(
origin: Tuple[float, float, float] = (0.0, 0.0, 0.0),
direction: Tuple[float, float, float] = (0.0, 0.0, 1.0),
degree: float = 360.0,
):
) -> list[bm_comp.Component]:
"""
Pattern the provided Component equally spaced around a circle n_children times.
Expand Down
2 changes: 1 addition & 1 deletion bluemira/codes/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ def _map_external_outputs_to_bluemira_params(
if not (mapping.recv or recv_all):
continue
# out name is set name if it's not provided
output_value = self._get_output_or_raise(external_outputs, mapping.out_name) # type: ignore type
output_value = self._get_output_or_raise(external_outputs, mapping.out_name) # type: ignore[type]
if mapping.unit is None:
bluemira_warn(
f"{mapping.out_name} from code {self._name} has no known unit"
Expand Down
11 changes: 6 additions & 5 deletions bluemira/display/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

import pprint
from dataclasses import asdict
from typing import Any, Dict


class Options:
Expand All @@ -22,7 +23,7 @@ class Options:
def __init__(self, **kwargs):
self.modify(**kwargs)

def __setattr__(self, attr, val):
def __setattr__(self, attr: str, val: Any):
"""
Set attributes in options dictionary
"""
Expand All @@ -33,7 +34,7 @@ def __setattr__(self, attr, val):
else:
super().__setattr__(attr, val)

def __getattribute__(self, attr):
def __getattribute__(self, attr: str):
"""
Get attributes or from "_options" dict
"""
Expand All @@ -47,18 +48,18 @@ def __getattribute__(self, attr):
raise ae from None
raise

def modify(self, **kwargs):
def modify(self, **kwargs: Any):
"""Modify options"""
for k, v in kwargs.items():
setattr(self, k, v)

def as_dict(self):
def as_dict(self) -> Dict[str, Any]:
"""
Returns the instance as a dictionary.
"""
return asdict(self._options)

def __repr__(self):
def __repr__(self) -> str:
"""
Representation string of the DisplayOptions.
"""
Expand Down
2 changes: 1 addition & 1 deletion bluemira/equilibria/coils/_coil.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ def plot(
label: bool = False,
force: Optional[Iterable] = None,
**kwargs,
):
) -> Optional[CoilGroupPlotter]:
"""
Plot a Coil
Expand Down
4 changes: 2 additions & 2 deletions bluemira/equilibria/coils/_field.py
Original file line number Diff line number Diff line change
Expand Up @@ -538,7 +538,7 @@ def _Bz_response_analytical(
coil_z: Optional[np.ndarray] = None,
coil_dx: Optional[np.ndarray] = None,
coil_dz: Optional[np.ndarray] = None,
):
) -> np.ndarray:
"""
Calculate vertical magnetic field Bz response at (x, z) due to a unit
current using semi-analytic method.
Expand Down Expand Up @@ -978,7 +978,7 @@ def _B_response_analytical(
z: np.ndarray,
*_args,
**_kwargs,
):
) -> np.ndarray:
"""
Calculate [psi, Bx, Bz] response at (x, z) due to a unit
current using semi-analytic method.
Expand Down
8 changes: 4 additions & 4 deletions bluemira/equilibria/coils/_grouping.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ def plot(
label: bool = False,
force: Optional[Iterable] = None,
**kwargs,
):
) -> CoilGroupPlotter:
"""
Plot a CoilGroup
Expand Down Expand Up @@ -265,7 +265,7 @@ def remove_coil(self, *coil_name: str, _top_level: bool = True) -> Union[None, L
return None

@classmethod
def from_group_vecs(cls, eqdsk: EQDSKInterface):
def from_group_vecs(cls, eqdsk: EQDSKInterface) -> CoilGroup:
"""
Initialises an instance of CoilSet from group vectors.
Expand Down Expand Up @@ -501,7 +501,7 @@ def _get_coiltype(self, ctype):
coils.append(c)
return coils

def get_coiltype(self, ctype: Union[str, CoilType]):
def get_coiltype(self, ctype: Union[str, CoilType]) -> Optional[CoilGroup]:
"""Get coils matching coil type"""
if coiltype := self._get_coiltype(ctype):
return CoilGroup(*coiltype)
Expand Down Expand Up @@ -1002,7 +1002,7 @@ def get_coiltype(self, ctype):
@classmethod
def from_group_vecs(
cls, eqdsk: EQDSKInterface, control_coiltypes=(CoilType.PF, CoilType.CS)
):
) -> CoilGroup:
"""Create CoilSet from eqdsk group vectors.
Automatically sets all coils that are not implicitly passive to control coils
Expand Down
2 changes: 1 addition & 1 deletion bluemira/equilibria/coils/_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def make_mutual_inductance_matrix(coilset: CoilSet) -> np.ndarray:
return M


def _get_symmetric_coils(coilset: CoilSet):
def _get_symmetric_coils(coilset: CoilSet) -> list[list]:
"""
Coilset symmetry utility
"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@
"""

from dataclasses import dataclass
from typing import Callable, Iterable, Optional, Union
from typing import Callable, Iterable, Optional, Tuple, Union

import dolfin
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.figure import Figure
from mpl_toolkits.axes_grid1 import make_axes_locatable

from bluemira.base.constants import MU_0
Expand Down Expand Up @@ -412,7 +413,7 @@ def _equilibrium(self):
)

@staticmethod
def _setup_plot(debug: bool):
def _setup_plot(debug: bool) -> Tuple[Figure, np.ndarray, list]:
n_col = 3 if debug else 2
fig, ax = plt.subplots(1, n_col, figsize=(18, 10))
plt.subplots_adjust(wspace=0.5)
Expand Down
2 changes: 1 addition & 1 deletion bluemira/equilibria/fem_fixed_boundary/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def save_fixed_boundary_to_file(
file_format: str = "json",
json_kwargs: Optional[Dict] = None,
**kwargs,
):
) -> EQDSKInterface:
"""
Save a fixed boundary equilibrium to a file.
Expand Down
4 changes: 3 additions & 1 deletion bluemira/equilibria/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
Input and output file interface. EQDSK and json. NOTE: jsons are better :)
"""

from __future__ import annotations

import json
import time
from dataclasses import asdict, dataclass
Expand Down Expand Up @@ -128,7 +130,7 @@ def __post_init__(self):
self.psinorm = _derive_psinorm(self.fpol)

@classmethod
def from_file(cls, file_path: str):
def from_file(cls, file_path: str) -> EQDSKInterface:
"""
Create an EQDSKInterface object from a file.
Expand Down
2 changes: 1 addition & 1 deletion bluemira/equilibria/limiter.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def __next__(self):
self._i += 1
return next(self.xz[self._i - 1])

def plot(self, ax: Optional[Axes] = None):
def plot(self, ax: Optional[Axes] = None) -> LimiterPlotter:
"""
Plots the Limiter object
"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ def prepare(self, equilibrium: Equilibrium, I_not_dI=False, fixed_coils=False):
self._args["a_mat"] = self.control_response(equilibrium.coilset)
self._args["b_vec"] = self.target_harmonics - self.evaluate(equilibrium)

def control_response(self, coilset: CoilSet):
def control_response(self, coilset: CoilSet) -> np.ndarray:
"""
Calculate control response of a CoilSet to the constraint.
"""
Expand Down
4 changes: 3 additions & 1 deletion bluemira/equilibria/optimisation/problem/_minimal_current.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,9 @@ def __init__(
self.opt_parameters = opt_parameters
self._constraints = [] if constraints is None else constraints

def optimise(self, x0: Optional[npt.NDArray] = None, fixed_coils: bool = True):
def optimise(
self, x0: Optional[npt.NDArray] = None, fixed_coils: bool = True
) -> CoilsetOptimiserResult:
"""
Run the optimisation problem
Expand Down
6 changes: 4 additions & 2 deletions bluemira/equilibria/optimisation/problem/_position.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
#
# SPDX-License-Identifier: LGPL-2.1-or-later

from typing import Dict, List, Optional
from typing import Dict, List, Optional, Tuple

import numpy as np
import numpy.typing as npt
Expand Down Expand Up @@ -151,7 +151,9 @@ def objective(self, vector: npt.NDArray[np.float64]) -> float:

return regularised_lsq_fom(currents * self.scale, a_mat, b_vec, self.gamma)[0]

def get_mapped_state_bounds(self, max_currents: Optional[npt.ArrayLike] = None):
def get_mapped_state_bounds(
self, max_currents: Optional[npt.ArrayLike] = None
) -> Tuple[np.ndarray, np.ndarray]:
"""
Get mapped bounds on the coilset state vector from the coil regions and
maximum coil currents.
Expand Down
2 changes: 1 addition & 1 deletion bluemira/equilibria/optimisation/problem/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ def get_state_bounds(
@staticmethod
def get_current_bounds(
coilset: CoilSet, max_currents: npt.ArrayLike, current_scale: float
):
) -> Tuple[np.ndarray, np.ndarray]:
"""
Gets the scaled current vector bounds. Must be called prior to optimise.
Expand Down
6 changes: 3 additions & 3 deletions bluemira/equilibria/positioner.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"""
Coil positioning routines (automatic and adjustable)
"""

from __future__ import annotations
import re
from copy import deepcopy
from typing import Dict, List, Tuple, Union
Expand Down Expand Up @@ -48,7 +48,7 @@ class ReactorType(Enum):
SPHERICAL_TOKAMAK = auto()

@classmethod
def _missing_(cls, value: str):
def _missing_(cls, value: Union[str, ReactorType]) -> ReactorType:
try:
return cls[value.upper()]
except KeyError:
Expand All @@ -64,7 +64,7 @@ class CoilsetLayoutType(Enum):
DEMO = auto()

@classmethod
def _missing_(cls, value: str):
def _missing_(cls, value: Union[str, CoilsetLayoutType]) -> CoilsetLayoutType:
try:
return cls[value.upper()]
except KeyError:
Expand Down
Loading

0 comments on commit d21b53a

Please sign in to comment.