Skip to content

Commit

Permalink
resolved mypy type checks, some pylint checks (#89)
Browse files Browse the repository at this point in the history
* resolved mypy type checks, some pylint checks
* final version 2.0.4
  • Loading branch information
o-murphy authored Aug 17, 2024
1 parent 5e90cf7 commit 4cc7e2c
Show file tree
Hide file tree
Showing 9 changed files with 56 additions and 37 deletions.
1 change: 1 addition & 0 deletions py_ballisticcalc/drag_tables.py
Original file line number Diff line number Diff line change
Expand Up @@ -670,6 +670,7 @@


def get_drag_tables_names():
"""Return a list of drag table names"""
return [f"TableG{n}" for n in (1, 7, 2, 5, 6, 8, 'I', 'S')]


Expand Down
2 changes: 1 addition & 1 deletion py_ballisticcalc/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class Calculator:
@property
def cdm(self):
"""returns custom drag function based on input data"""
return self._calc._table_data
return self._calc.table_data

def barrel_elevation_for_target(self, shot: Shot, target_distance: Union[float, Distance]) -> Angular:
"""Calculates barrel elevation to hit target at zero_distance.
Expand Down
24 changes: 19 additions & 5 deletions py_ballisticcalc/trajectory_calc.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,13 +128,23 @@ def __neg__(self) -> 'Vector':
class TrajectoryCalc:
"""All calculations are done in units of feet and fps"""

# the attributes have to be defined before usage
barrel_azimuth: float
barrel_elevation: float
twist: float

def __init__(self, ammo: Ammo):
self.ammo: Ammo = ammo
self._bc: float = self.ammo.dm.BC
self._table_data: List[DragDataPoint] = ammo.dm.drag_table
self._curve = calculate_curve(self._table_data)
self.gravity_vector = Vector(.0, cGravityConstant, .0)

@property
def table_data(self) -> List[DragDataPoint]:
""":return: List[DragDataPoint]"""
return self._table_data

@staticmethod
def get_calc_step(step: float = 0):
"""Keep step under max_calc_step_size
Expand Down Expand Up @@ -187,9 +197,9 @@ def zero_angle(self, shot_info: Shot, distance: Distance) -> Angular:
zero_distance = math.cos(self.look_angle) * (distance >> Distance.Foot)
height_at_zero = math.sin(self.look_angle) * (distance >> Distance.Foot)
maximum_range = zero_distance - 1.5 * self.calc_step
self.barrel_azimuth = 0.0
self.barrel_elevation = math.atan(height_at_zero / zero_distance)
self.twist = 0
# self.barrel_azimuth = 0.0
# self.barrel_elevation = math.atan(height_at_zero / zero_distance)
# self.twist = 0.0

iterations_count = 0
zero_finding_error = cZeroFindingAccuracy * 2
Expand All @@ -208,7 +218,7 @@ def zero_angle(self, shot_info: Shot, distance: Distance) -> Angular:

if zero_finding_error > cZeroFindingAccuracy:
# TODO: Don't raise exception; return a tuple that contains the error so caller can check how close zero is
raise Exception(f'Zero vertical error {zero_finding_error} feet, after {iterations_count} iterations.')
raise RuntimeError(f'Zero vertical error {zero_finding_error} feet, after {iterations_count} iterations.')
return Angular.Radian(self.barrel_elevation)

def _trajectory(self, shot_info: Shot, maximum_range: float, step: float,
Expand All @@ -224,6 +234,10 @@ def _trajectory(self, shot_info: Shot, maximum_range: float, step: float,
previous_mach: float = .0
drag: float = 0

# guarantee that mach and density_factor would be referenced before assignment
mach: float = .0
density_factor: float = .0

# region Initialize wind-related variables to first wind reading (if any)
len_winds = len(shot_info.winds)
current_wind = 0
Expand Down Expand Up @@ -291,7 +305,7 @@ def _trajectory(self, shot_info: Shot, maximum_range: float, step: float,
seen_zero |= TrajFlag.ZERO_DOWN

# Mach crossing check
if (velocity / mach <= 1) and (previous_mach > 1):
if previous_mach > 1 >= velocity / mach: # (velocity / mach <= 1) and (previous_mach > 1)
_flag |= TrajFlag.MACH

# Next range check
Expand Down
23 changes: 12 additions & 11 deletions py_ballisticcalc/trajectory_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,26 @@
from dataclasses import dataclass, field
from enum import IntFlag
from typing_extensions import NamedTuple, Optional, Union, Any

from py_ballisticcalc.conditions import Shot
from py_ballisticcalc.unit import Angular, Distance, Weight, Velocity, Energy, AbstractUnit, Unit, PreferredUnits


pandas: Any
DataFrame: Any
matplotlib: Any
Polygon: Any
Axes: Any


try:
import pandas
import pandas # type: ignore
except ImportError as error:
logging.warning("Install pandas to convert trajectory to dataframe")
logging.warning("Install pandas to convert trajectory to pandas.DataFrame")
pandas = None

try:
import matplotlib
from matplotlib.patches import Polygon
import matplotlib # type: ignore
from matplotlib.patches import Polygon # type: ignore
except ImportError as error:
logging.warning("Install matplotlib to get results as a plot")
matplotlib = None
Expand Down Expand Up @@ -155,10 +156,10 @@ def __str__(self) -> str:
+ f'ranges from {self.begin.distance << PreferredUnits.distance} ' \
+ f'to {self.end.distance << PreferredUnits.distance}'

def overlay(self, ax: 'Axes', label: Optional[str] = None):
def overlay(self, ax: 'Axes', label: Optional[str] = None): # type: ignore
"""Highlights danger-space region on plot"""
if matplotlib is None or not Polygon:
raise ImportError("Install matplotlib to get results as a plot")
raise ImportError("Use `pip install py_ballisticcalc[charts]` to get results as a plot")

cosine = math.cos(self.look_angle >> Angular.Radian)
begin_dist = (self.begin.distance >> PreferredUnits.distance) * cosine
Expand Down Expand Up @@ -299,27 +300,27 @@ def find_end_danger(row_num: int) -> TrajectoryData:
find_end_danger(index),
look_angle)

def dataframe(self, formatted: bool = False) -> 'DataFrame':
def dataframe(self, formatted: bool = False) -> 'DataFrame': # type: ignore
"""
:param formatted: False for values as floats; True for strings with prefer_units
:return: the trajectory table as a DataFrame
"""
if pandas is None:
raise ImportError("Install pandas to get trajectory as dataframe")
raise ImportError("Use `pip install py_ballisticcalc[charts]` to get trajectory as pandas.DataFrame")
col_names = list(TrajectoryData._fields)
if formatted:
trajectory = [p.formatted() for p in self]
else:
trajectory = [p.in_def_units() for p in self]
return pandas.DataFrame(trajectory, columns=col_names)

def plot(self, look_angle: Optional[Angular] = None) -> 'Axes':
def plot(self, look_angle: Optional[Angular] = None) -> 'Axes': # type: ignore
""":return: graph of the trajectory"""
if look_angle is None:
look_angle = self.shot.look_angle

if matplotlib is None:
raise ImportError("Install matplotlib to plot results")
raise ImportError("Use `pip install py_ballisticcalc[charts]` to get results as a plot")
if not self.extra:
logging.warning("HitResult.plot: To show extended data"
"Use Calculator.fire(..., extra_data=True)")
Expand Down
5 changes: 1 addition & 4 deletions py_ballisticcalc/unit.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,20 @@

from py_ballisticcalc.logger import logger

# pylint: disable=invalid-name
AbstractUnitType = TypeVar('AbstractUnitType', bound='AbstractUnit')


class UnitTypeError(TypeError):
"""Unit type error"""
pass


class UnitConversionError(UnitTypeError):
"""Unit conversion error"""
pass


class UnitAliasError(ValueError):
"""Unit alias error"""
pass


# pylint: disable=invalid-name
Expand Down Expand Up @@ -811,7 +809,6 @@ def create_as_preferred(value_):
'UnitAliasError',
'UnitTypeError',
'UnitConversionError',
# opt
'_parse_unit',
'_parse_value'
)
26 changes: 14 additions & 12 deletions py_ballisticcalc_exts/py_ballisticcalc_exts/trajectory_calc.pyi
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
from dataclasses import dataclass
from py_ballisticcalc.conditions import Atmo, Shot
from py_ballisticcalc.drag_model import DragDataPoint
from py_ballisticcalc.munition import Ammo
from py_ballisticcalc.unit import Angular, Distance
from _typeshed import Incomplete
from dataclasses import dataclass
from typing import NamedTuple
from typing_extensions import NamedTuple, Union

__all__ = ['TrajectoryCalc', 'get_global_max_calc_step_size', 'get_global_use_powder_sensitivity', 'set_global_max_calc_step_size', 'set_global_use_powder_sensitivity', 'reset_globals']

def get_global_max_calc_step_size() -> Distance: ...
def get_global_use_powder_sensitivity() -> bool: ...
def reset_globals() -> None: ...
def set_global_max_calc_step_size(value: float | Distance) -> None: ...
def set_global_max_calc_step_size(value: Union[float, Distance]) -> None: ...
def set_global_use_powder_sensitivity(value: bool) -> None: ...

class CurvePoint(NamedTuple):
Expand All @@ -36,22 +36,24 @@ class Vector:
def __sub__(self, other: Vector) -> Vector: ...
def __rsub__(self, other: Vector) -> Vector: ...
def __isub__(self, other: Vector) -> Vector: ...
def __mul__(self, other: int | float | Vector) -> float | Vector: ...
def __rmul__(self, other: int | float | Vector) -> float | Vector: ...
def __imul__(self, other: int | float | Vector) -> float | Vector: ...
def __mul__(self, other: Union[int, float, 'Vector']) -> Union[float, 'Vector']: ...
def __rmul__(self, other: Union[int, float, 'Vector']) -> Union[float, 'Vector']: ...
def __imul__(self, other: Union[int, float, 'Vector']) -> Union[float, 'Vector']: ...
def __neg__(self) -> Vector: ...
def __init__(self, x, y, z) -> None: ...

class TrajectoryCalc:
ammo: Incomplete
gravity_vector: Incomplete
ammo: Ammo
gravity_vector: Vector
barrel_azimuth: float
barrel_elevation: float
twist: float
def __init__(self, ammo: Ammo) -> None: ...
@property
def table_data(self) -> list[DragDataPoint]: ...
@staticmethod
def get_calc_step(step: float = 0): ...
def trajectory(self, shot_info: Shot, max_range: Distance, dist_step: Distance, extra_data: bool = False): ...
barrel_azimuth: float
barrel_elevation: Incomplete
twist: int
def zero_angle(self, shot_info: Shot, distance: Distance) -> Angular: ...
def drag_by_mach(self, mach: float) -> float: ...
def spin_drift(self, time) -> float: ...
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,10 @@ cdef class TrajectoryCalc:
self._curve = calculate_curve(self._table_data)
self.gravity_vector = Vector(.0, cGravityConstant, .0)

@property
def table_data(self) -> list:
return self._table_data

def zero_angle(self, shot_info: Shot, distance: Distance):
return self._zero_angle(shot_info, distance)

Expand Down Expand Up @@ -224,7 +228,7 @@ cdef class TrajectoryCalc:
break
iterations_count += 1
if zero_finding_error > cZeroFindingAccuracy:
raise Exception(f'Zero vertical error {zero_finding_error} feet, after {iterations_count} iterations.')
raise RuntimeError(f'Zero vertical error {zero_finding_error} feet, after {iterations_count} iterations.')
return Angular.Radian(self.barrel_elevation)

cdef _trajectory(TrajectoryCalc self, object shot_info,
Expand Down
2 changes: 1 addition & 1 deletion py_ballisticcalc_exts/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "py_ballisticcalc.exts"
version = "2.0.4rc2"
version = "2.0.4"

authors = [
{ name="o-murphy", email="[email protected]" },
Expand Down
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "py_ballisticcalc"
version = "2.0.4rc2"
version = "2.0.4"

authors = [
{ name="o-murphy", email="[email protected]" },
Expand Down Expand Up @@ -51,7 +51,7 @@ exclude = ["py_ballisticcalc_exts*"]


[project.optional-dependencies]
exts = ['py_ballisticcalc.exts==2.0.4rc2']
exts = ['py_ballisticcalc.exts==2.0.4']
charts = ['matplotlib', 'pandas']
dev = [
'jupyter',
Expand Down

0 comments on commit 4cc7e2c

Please sign in to comment.