From 5429c8544326dd1d18632b84b298a1735808f5a2 Mon Sep 17 00:00:00 2001 From: pranavvadd Date: Sun, 18 Oct 2026 17:18:34 -0400 Subject: [PATCH] Add shared unit conversion helpers (#45) New sim/units.py with mph/mps, meters/miles/km, and minutes/hours/seconds helpers. Replace duplicated 2.237, 1609.34 and 1000.0 literals in config, reporting, plotting, simulator and the planning sweep. Co-Authored-By: Claude Sonnet 5.5 --- sim/config.py | 14 ++-- sim/planning/sweep.py | 4 +- sim/plotting.py | 10 +-- sim/reporting.py | 7 +- sim/simulator.py | 7 +- sim/units.py | 36 ++++++++++ tests/test_units.py | 153 ++++++++++++++++++++++++++++++++++++++++++ 7 files changed, 213 insertions(+), 18 deletions(-) create mode 100644 sim/units.py create mode 100644 tests/test_units.py diff --git a/sim/config.py b/sim/config.py index 1114f79..9d80669 100644 --- a/sim/config.py +++ b/sim/config.py @@ -5,6 +5,8 @@ import math import numpy as np +from sim.units import meters_to_km, meters_to_miles, mps_to_mph + @dataclass class TrackConfig: @@ -24,7 +26,7 @@ def __post_init__(self): @property def lap_distance_km(self) -> float: - return self.lap_distance_m / 1000.0 + return meters_to_km(self.lap_distance_m) def validate(self): if self.lap_distance_m <= 0: @@ -186,11 +188,11 @@ class SimulationResults: @property def total_distance_km(self) -> float: - return self.total_distance_m / 1000.0 + return meters_to_km(self.total_distance_m) @property def total_distance_miles(self) -> float: - return self.total_distance_m / 1609.34 + return meters_to_miles(self.total_distance_m) @property def avg_speed_mps(self) -> float: @@ -198,7 +200,7 @@ def avg_speed_mps(self) -> float: @property def avg_speed_mph(self) -> float: - return self.avg_speed_mps * 2.237 + return mps_to_mph(self.avg_speed_mps) @property def final_soc(self) -> float: @@ -222,11 +224,11 @@ def hit_min_soc(self) -> bool: @property def max_speed_mph(self) -> float: - return float(np.max(self.speed)) * 2.237 + return mps_to_mph(float(np.max(self.speed))) @property def min_speed_mph(self) -> float: - return float(np.min(self.speed)) * 2.237 + return mps_to_mph(float(np.min(self.speed))) def get_available_tracks(courses_dir: Optional[str] = None) -> List[TrackConfig]: course_directory = ( diff --git a/sim/planning/sweep.py b/sim/planning/sweep.py index 342edd1..af91324 100644 --- a/sim/planning/sweep.py +++ b/sim/planning/sweep.py @@ -4,9 +4,9 @@ from sim.planning.comparison import build_comparison_row from sim.simulator import LapsRaceSimulator +from sim.units import mph_to_mps -MPH_TO_MPS = 1 / 2.237 SPEED_SWEEP_MPH = list(range(10, 47, 2)) DEFAULT_AGGRESSIVENESS = { @@ -29,7 +29,7 @@ def run_fixed_speed_sweep( rows = [] for mph in speeds_mph: - fixed_speed_mps = mph * MPH_TO_MPS + fixed_speed_mps = mph_to_mps(mph) race = replace( base_race, strategy="fixed", diff --git a/sim/plotting.py b/sim/plotting.py index 626ee1f..045af47 100644 --- a/sim/plotting.py +++ b/sim/plotting.py @@ -3,6 +3,8 @@ import numpy as np import matplotlib.pyplot as plt +from sim.units import mps_to_mph + class SimulationPlotter: def __init__(self, results, track): @@ -36,7 +38,7 @@ def plot_soc(self, save_path: Optional[str] = None, show: bool = False): def plot_speed(self, save_path: Optional[str] = None, show: bool = False): fig, ax = plt.subplots(figsize=(10, 5)) hours = self._time_to_hours() - speed_mph = self.results.speed * 2.237 + speed_mph = mps_to_mph(self.results.speed) ax.plot(hours, speed_mph, color="green", linewidth=1.5) ax.axhline(y=np.mean(speed_mph), color="red", linestyle="--", label=f"Average: {np.mean(speed_mph):.1f} mph", alpha=0.7) @@ -93,7 +95,7 @@ def plot_dashboard(self, save_path: Optional[str] = None, show: bool = False): ax1.set_ylim(0, 105) ax2 = fig.add_subplot(gs[0, 1]) - speed_mph = self.results.speed * 2.237 + speed_mph = mps_to_mph(self.results.speed) ax2.plot(hours, speed_mph, color="green", linewidth=1.5) ax2.axhline(y=np.mean(speed_mph), color="red", linestyle="--", alpha=0.7) ax2.set_ylabel("Speed (mph)") @@ -134,8 +136,8 @@ def plot_dashboard(self, save_path: Optional[str] = None, show: bool = False): Speed Statistics: Average: {self.results.avg_speed_mph:.1f} mph - Max: {np.max(self.results.speed)*2.237:.1f} mph - Min: {np.min(self.results.speed)*2.237:.1f} mph + Max: {mps_to_mph(np.max(self.results.speed)):.1f} mph + Min: {mps_to_mph(np.min(self.results.speed)):.1f} mph """ ax6.text( 0.1, diff --git a/sim/reporting.py b/sim/reporting.py index 8fe583b..9c4778b 100644 --- a/sim/reporting.py +++ b/sim/reporting.py @@ -1,4 +1,5 @@ import numpy as np +from sim.units import meters_to_miles, mps_to_mph class ResultsReporter: @@ -26,7 +27,7 @@ def fmt_elapsed(minute_of_day: float) -> str: print(f"\nTrack: {self.track.name}") print(f" Location: {self.track.location}") - print(f" Lap Distance: {self.track.lap_distance_km:.3f} km ({self.track.lap_distance_m/1609.34:.2f} miles)") + print(f" Lap Distance: {self.track.lap_distance_km:.3f} km ({meters_to_miles(self.track.lap_distance_m):.2f} miles)") print("\nRace Results:") print(f" Total Laps Completed: {r.total_laps}") @@ -50,8 +51,8 @@ def fmt_elapsed(minute_of_day: float) -> str: print("\nSpeed:") print(f" Average: {r.avg_speed_mps:.2f} m/s ({r.avg_speed_mph:.1f} mph)") - print(f" Maximum: {np.max(r.speed):.2f} m/s ({np.max(r.speed)*2.237:.1f} mph)") - print(f" Minimum: {np.min(r.speed):.2f} m/s ({np.min(r.speed)*2.237:.1f} mph)") + print(f" Maximum: {np.max(r.speed):.2f} m/s ({mps_to_mph(np.max(r.speed)):.1f} mph)") + print(f" Minimum: {np.min(r.speed):.2f} m/s ({mps_to_mph(np.min(r.speed)):.1f} mph)") if r.lap_times: print("\nLap Times (minutes):") diff --git a/sim/simulator.py b/sim/simulator.py index d3faa53..889c206 100644 --- a/sim/simulator.py +++ b/sim/simulator.py @@ -2,6 +2,7 @@ from sim.physics import PhysicsEngine from sim.weather import WeatherService from sim.controllers import build_strategy +from sim.units import minutes_to_hours, minutes_to_seconds, mps_to_mph import numpy as np @@ -27,11 +28,11 @@ def run(self) -> SimulationResults: time_minutes, ghi_data, cloud_data = self.weather.generate_synthetic_data(self.race) dt_minutes = self.race.time_step_minutes - dt_hours = dt_minutes / 60.0 + dt_hours = minutes_to_hours(dt_minutes) self.strategy.prepare(self.physics, ghi_data, cloud_data, dt_hours) ideal_soc = self.strategy.ideal_soc - print(f" Optimal constant speed baseline: {self.strategy.optimal_speed:.2f} m/s ({self.strategy.optimal_speed*2.237:.1f} mph)") + print(f" Optimal constant speed baseline: {self.strategy.optimal_speed:.2f} m/s ({mps_to_mph(self.strategy.optimal_speed):.1f} mph)") n_steps = len(time_minutes) soc = self.race.start_soc @@ -77,7 +78,7 @@ def run(self) -> SimulationResults: else: soc = float(np.clip(next_soc, self.race.min_soc, 1.0)) - distance_step = speed * (dt_minutes * 60) * step_fraction + distance_step = speed * minutes_to_seconds(dt_minutes) * step_fraction step_start = time_minutes[i] step_duration = dt_minutes * step_fraction carry = current_lap_distance # distance already covered on the current lap diff --git a/sim/units.py b/sim/units.py new file mode 100644 index 0000000..1522d5e --- /dev/null +++ b/sim/units.py @@ -0,0 +1,36 @@ +"""Shared unit conversions. The simulator works in SI internally (m, m/s, s); +these helpers are for display and for converting user-facing inputs.""" + +MPH_PER_MPS = 2.237 +METERS_PER_MILE = 1609.34 +METERS_PER_KM = 1000.0 +SECONDS_PER_MINUTE = 60.0 +MINUTES_PER_HOUR = 60.0 + + +def mph_to_mps(mph): + return mph / MPH_PER_MPS + + +def mps_to_mph(mps): + return mps * MPH_PER_MPS + + +def meters_to_miles(meters): + return meters / METERS_PER_MILE + + +def meters_to_km(meters): + return meters / METERS_PER_KM + + +def km_to_meters(km): + return km * METERS_PER_KM + + +def minutes_to_hours(minutes): + return minutes / MINUTES_PER_HOUR + + +def minutes_to_seconds(minutes): + return minutes * SECONDS_PER_MINUTE diff --git a/tests/test_units.py b/tests/test_units.py new file mode 100644 index 0000000..c0a8452 --- /dev/null +++ b/tests/test_units.py @@ -0,0 +1,153 @@ +"""Tests for sim.units and for the code that now uses it (issue #45).""" +import math +import re +from pathlib import Path + +import numpy as np +import pytest + +from sim import units +from sim.config import SimulationResults, TrackConfig +from sim.planning.sweep import run_fixed_speed_sweep + +SIM_DIR = Path(__file__).resolve().parents[1] / "sim" + + +class TestKnownValues: + @pytest.mark.parametrize( + "func, arg, expected", + [ + (units.mph_to_mps, 0, 0.0), + (units.mph_to_mps, 2.237, 1.0), + (units.mph_to_mps, 22.37, 10.0), + (units.mps_to_mph, 0, 0.0), + (units.mps_to_mph, 1, 2.237), + (units.mps_to_mph, 10, 22.37), + (units.meters_to_miles, 0, 0.0), + (units.meters_to_miles, 1609.34, 1.0), + (units.meters_to_miles, 3218.68, 2.0), + (units.meters_to_km, 0, 0.0), + (units.meters_to_km, 1000, 1.0), + (units.meters_to_km, 604, 0.604), + (units.km_to_meters, 0, 0.0), + (units.km_to_meters, 1, 1000.0), + (units.km_to_meters, 4.989, 4989.0), + (units.minutes_to_hours, 0, 0.0), + (units.minutes_to_hours, 60, 1.0), + (units.minutes_to_hours, 1, 1 / 60), + (units.minutes_to_hours, 90, 1.5), + (units.minutes_to_seconds, 0, 0.0), + (units.minutes_to_seconds, 1, 60.0), + (units.minutes_to_seconds, 2.5, 150.0), + ], + ) + def test_conversion(self, func, arg, expected): + assert func(arg) == pytest.approx(expected) + + def test_negative_values_convert_linearly(self): + assert units.mps_to_mph(-5) == pytest.approx(-units.mps_to_mph(5)) + assert units.minutes_to_hours(-30) == pytest.approx(-0.5) + + +class TestRoundTrips: + @pytest.mark.parametrize("value", [0.0, 0.1, 1.0, 15.0, 33.6, 1234.5]) + def test_speed(self, value): + assert units.mps_to_mph(units.mph_to_mps(value)) == pytest.approx(value) + assert units.mph_to_mps(units.mps_to_mph(value)) == pytest.approx(value) + + @pytest.mark.parametrize("value", [0.0, 0.604, 1.77, 4.989, 250.0]) + def test_km_meters(self, value): + assert units.meters_to_km(units.km_to_meters(value)) == pytest.approx(value) + + +class TestInputKinds: + def test_numpy_arrays_convert_elementwise(self): + speeds = np.array([0.0, 10.0, 20.0]) + np.testing.assert_allclose(units.mps_to_mph(speeds), speeds * 2.237) + assert isinstance(units.mps_to_mph(speeds), np.ndarray) + + def test_ints_floats_and_numpy_scalars(self): + for value in (10, 10.0, np.float64(10.0), np.int64(10)): + assert units.mps_to_mph(value) == pytest.approx(22.37) + + def test_inputs_are_not_mutated(self): + speeds = np.array([1.0, 2.0]) + units.mps_to_mph(speeds) + np.testing.assert_array_equal(speeds, [1.0, 2.0]) + + def test_nan_and_inf_propagate(self): + assert math.isnan(units.mph_to_mps(float("nan"))) + assert math.isinf(units.meters_to_km(float("inf"))) + + +class TestConstants: + """Pin the constants so display values stay what they were before the refactor.""" + + def test_values(self): + assert units.MPH_PER_MPS == 2.237 + assert units.METERS_PER_MILE == 1609.34 + assert units.METERS_PER_KM == 1000.0 + assert units.SECONDS_PER_MINUTE == 60.0 + assert units.MINUTES_PER_HOUR == 60.0 + + def test_mph_and_mps_are_inverses_of_the_same_constant(self): + assert units.mph_to_mps(units.MPH_PER_MPS) == pytest.approx(1.0) + + +class TestCallersUseTheHelpers: + def _results(self, speed, distance_m): + n = len(speed) + zeros = np.zeros(n) + return SimulationResults( + time_minutes=np.arange(n, dtype=float), soc=np.linspace(1, 0.5, n), + speed=np.asarray(speed, dtype=float), ghi=zeros, cloud_cover=zeros, + lap_times=[], total_laps=0, total_distance_m=distance_m, bdr=zeros, + ideal_soc=zeros, completed_full_window=True, + reached_min_soc_time_minutes=None, laps_at_min_soc=None, + ) + + def test_results_distance_and_speed_properties(self): + r = self._results([10.0, 20.0, 30.0], 16093.4) + assert r.total_distance_km == pytest.approx(16.0934) + assert r.total_distance_miles == pytest.approx(10.0) + assert r.avg_speed_mph == pytest.approx(20.0 * 2.237) + assert r.max_speed_mph == pytest.approx(30.0 * 2.237) + assert r.min_speed_mph == pytest.approx(10.0 * 2.237) + + def test_track_lap_distance_km(self): + track = TrackConfig( + name="t", file_path_name="t", location="x", latitude=0, longitude=0, + lap_distance_m=1770.0, timezone="UTC", + ) + assert track.lap_distance_km == pytest.approx(1.77) + + def test_sweep_converts_mph_to_commanded_mps(self, monkeypatch): + seen = [] + + class FakeSim: + def __init__(self, track, car, race, use_api_weather=True): + seen.append(race.fixed_speed_mps) + + def run(self): + raise StopIteration + + monkeypatch.setattr("sim.planning.sweep.LapsRaceSimulator", FakeSim) + from sim.config import RaceConfig + with pytest.raises(StopIteration): + run_fixed_speed_sweep( + track=None, car=None, base_race=RaceConfig(), speeds_mph=[22], use_api_weather=False + ) + assert seen == [pytest.approx(22 / 2.237)] + + +class TestNoDuplicatedLiterals: + """Acceptance criterion: repeated unit constants live only in sim/units.py.""" + + @pytest.mark.parametrize("literal", [r"\b2\.237\b", r"\b1609\.34\b"]) + def test_literal_only_in_units_module(self, literal): + offenders = [ + str(p.relative_to(SIM_DIR.parent)) + for p in SIM_DIR.rglob("*.py") + if p.name != "units.py" and re.search(literal, p.read_text()) + ] + assert offenders == []