Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions sim/planning/sweep.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
from dataclasses import replace

import numpy as np

from sim.planning.comparison import build_comparison_row
from sim.simulator import LapsRaceSimulator
from sim.units import mph_to_mps
Expand Down Expand Up @@ -41,8 +39,8 @@ def run_fixed_speed_sweep(
car=car,
race=race,
use_api_weather=use_api_weather,
synthetic_weather_seed=synthetic_weather_seed,
)
np.random.seed(synthetic_weather_seed)
results = simulator.run()

row = build_comparison_row(
Expand Down Expand Up @@ -85,8 +83,8 @@ def run_strategy_sweep(
car=car,
race=race,
use_api_weather=use_api_weather,
synthetic_weather_seed=synthetic_weather_seed,
)
np.random.seed(synthetic_weather_seed)
results = simulator.run()
rows.append(build_comparison_row(strategy, race, car, results, study="strategy"))

Expand Down
9 changes: 5 additions & 4 deletions sim/simulator.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
from sim.config import SimulationResults
from sim.physics import PhysicsEngine
from sim.weather import WeatherService
from sim.weather import DEFAULT_SYNTHETIC_SEED, WeatherService
from sim.controllers import build_strategy
from sim.units import minutes_to_hours, minutes_to_seconds, mps_to_mph
import numpy as np


class LapsRaceSimulator:
def __init__(self, track, car, race, use_api_weather=True):
def __init__(self, track, car, race, use_api_weather=True, synthetic_weather_seed=DEFAULT_SYNTHETIC_SEED):
self.track = track
self.car = car
self.race = race
self.use_api_weather = use_api_weather
self.synthetic_weather_seed = synthetic_weather_seed

self.physics = PhysicsEngine(self.car)
self.weather = WeatherService(self.track)
Expand All @@ -23,9 +24,9 @@ def run(self) -> SimulationResults:
time_minutes, ghi_data, cloud_data = self.weather.fetch_weather_data(self.race)
except Exception as e:
print(f"Warning: API fetch failed ({e}), using synthetic data")
time_minutes, ghi_data, cloud_data = self.weather.generate_synthetic_data(self.race)
time_minutes, ghi_data, cloud_data = self.weather.generate_synthetic_data(self.race, self.synthetic_weather_seed)
else:
time_minutes, ghi_data, cloud_data = self.weather.generate_synthetic_data(self.race)
time_minutes, ghi_data, cloud_data = self.weather.generate_synthetic_data(self.race, self.synthetic_weather_seed)

dt_minutes = self.race.time_step_minutes
dt_hours = minutes_to_hours(dt_minutes)
Expand Down
37 changes: 30 additions & 7 deletions sim/weather.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import openmeteo_requests
import requests_cache

DEFAULT_SYNTHETIC_SEED = 7


def resample_to_time_step(time_minutes, ghi_data, cloud_data, step_minutes: float):
"""Resample 1-minute weather arrays onto the simulator's time step.
Expand Down Expand Up @@ -119,23 +121,44 @@ def fetch_weather_data(self, race_config) -> Tuple[np.ndarray, np.ndarray, np.nd
time_minutes, ghi_data, cloud_data, race_config.time_step_minutes
)

def generate_synthetic_data(self, race_config) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
def generate_synthetic_data(
self, race_config, seed: int = DEFAULT_SYNTHETIC_SEED
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Offline weather profile. Deterministic: the same race window and seed give the same arrays."""
start_min = int(race_config.start_time_hour * 60)
end_min = int(race_config.end_time_hour * 60)
if end_min <= start_min:
raise ValueError(
f"Race window must contain at least one minute (start={start_min} min, end={end_min} min)"
)
time_minutes = np.arange(start_min, end_min)

# Local generator so the global np.random state is neither read nor modified.
rng = np.random.RandomState(seed)

t_peak = 13 * 60
peak_ghi = 900
a = peak_ghi / ((t_peak - start_min) ** 2)
half_width = abs(t_peak - start_min) or (end_min - start_min)
a = peak_ghi / (half_width**2)
ghi_data = np.maximum(0, -a * (time_minutes - t_peak) ** 2 + peak_ghi)

noise = np.clip(np.random.normal(1.0, 0.1, len(ghi_data)), 0.7, 1.2)
smooth_noise = np.convolve(noise, np.ones(15) / 15, mode="same")
ghi_data = ghi_data * smooth_noise
noise = np.clip(rng.normal(1.0, 0.1, len(ghi_data)), 0.7, 1.2)
ghi_data = ghi_data * _moving_average(noise, 15)

cloud_data = np.clip(0.3 + 0.3 * np.random.randn(len(time_minutes)), 0, 1)
cloud_data = np.convolve(cloud_data, np.ones(30) / 30, mode="same")
cloud_data = np.clip(0.3 + 0.3 * rng.randn(len(time_minutes)), 0, 1)
cloud_data = _moving_average(cloud_data, 30)

return resample_to_time_step(
time_minutes, ghi_data, cloud_data, race_config.time_step_minutes
)


def _moving_average(values: np.ndarray, window: int) -> np.ndarray:
"""Zero-padded moving average that always returns len(values) samples.

Equals np.convolve(values, ones(window)/window, mode="same") when len(values) >= window;
np.convolve returns max(len(values), window) samples, which breaks short race windows.
"""
full = np.convolve(values, np.ones(window) / window, mode="full")
offset = (window - 1) // 2
return full[offset : offset + len(values)]
4 changes: 2 additions & 2 deletions tests/planning/test_csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def test_fixed_speed_sweep(self):
simulator_args = []

class StubSimulator:
def __init__(self, *, track, car, race, use_api_weather):
def __init__(self, *, track, car, race, use_api_weather, synthetic_weather_seed=7):
simulator_args.append((track, car, use_api_weather))

def run(self):
Expand Down Expand Up @@ -84,7 +84,7 @@ def test_planning_report(self):
)

class StubSimulator:
def __init__(self, *, track, car, race, use_api_weather):
def __init__(self, *, track, car, race, use_api_weather, synthetic_weather_seed=7):
pass

def run(self):
Expand Down
3 changes: 2 additions & 1 deletion tests/test_simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def regen_energy(self, prev_speed, speed):


class FakeWeather:
def generate_synthetic_data(self, race):
def generate_synthetic_data(self, race, seed=None):
return (
np.array([0.0, 1.0]),
np.array([0.0, 0.0]),
Expand Down Expand Up @@ -54,6 +54,7 @@ def make_simulator(lap_distance_m=1000.0, time_step_minutes=1.0,
strategy="test",
)
simulator.use_api_weather = False
simulator.synthetic_weather_seed = 7
simulator.physics = FakePhysics()
simulator.weather = FakeWeather()
simulator.strategy = FakeStrategy(optimal_speed)
Expand Down
2 changes: 1 addition & 1 deletion tests/test_units.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ def test_sweep_converts_mph_to_commanded_mps(self, monkeypatch):
seen = []

class FakeSim:
def __init__(self, track, car, race, use_api_weather=True):
def __init__(self, track, car, race, use_api_weather=True, synthetic_weather_seed=None):
seen.append(race.fixed_speed_mps)

def run(self):
Expand Down
Loading