Skip to content
Open
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ Vehicle parameters are loaded from:
car_params.json
```

Typical parameters include mass, battery capacity, solar panel area, solar panel
Typical parameters include mass (`mass_kg`), battery capacity (`battery_capacity_wh`), solar panel area, solar panel
efficiency, drag, rolling resistance inputs, and regenerative braking
efficiency.

Expand Down
12 changes: 6 additions & 6 deletions car_params.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@
"electrical_efficiency": 0.99,
"solar_panel_efficiency": 0.23,
"wheels": 4,
"mass": 337,
"battery_capacity": 5000,
"mass_kg": 337,
"battery_capacity_wh": 5000,
"battery_voltage": "inf",
"solar_panel_area": 4,
"C_dA": 0.73809,
"rho": 1.192,
"solar_panel_area_m2": 4,
"cda_m2": 0.73809,
"air_density_kg_per_m3": 1.192,
"v_starting": 90,
"tire_pressure": 5
"tire_pressure_bar": 5
}
12 changes: 6 additions & 6 deletions docs/parameters_needed.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,15 @@ How to update: edit table cell, change `source` from `unknown` when confirmed.

| Param | Value now | Unit | Owner | Source | Effect |
|---|---|---|---|---|---|
| `mass` | 337 | kg | Mechanical | unknown — confirm weigh-in | Heavier = more rolling + regen energy |
| `battery_capacity` | 5000 | Wh | Electrical | unknown — confirm pack spec | Bigger = more laps, slower SoC drop |
| `solar_panel_area` | 4 | m² | Electrical | unknown — confirm array size | Bigger = more solar power |
| `mass_kg` | 337 | kg | Mechanical | unknown — confirm weigh-in | Heavier = more rolling + regen energy |
| `battery_capacity_wh` | 5000 | Wh | Electrical | unknown — confirm pack spec | Bigger = more laps, slower SoC drop |
| `solar_panel_area_m2` | 4 | m² | Electrical | unknown — confirm array size | Bigger = more solar power |
| `solar_panel_efficiency` | 0.23 | constant (NA)| Electrical | unknown — confirm datasheet | Higher = more solar power |
| `electrical_efficiency` | 0.99 | constant (NA) | Electrical | unknown — confirm MPPT/motor | BUG? (`physics.py:21`) multiplies, should divide |
| `C_dA` | 0.73809 | m² | Mechanical | unknown — confirm aero test/CFD | Higher = more drag, slower optimal speed |
| `tire_pressure` | 5 | bar | Mechanical | unknown — confirm actual pressure | Higher = less rolling resistance in current formula |
| `cda_m2` | 0.73809 | m² | Mechanical | unknown — confirm aero test/CFD | Higher = more drag, slower optimal speed |
| `tire_pressure_bar` | 5 | bar | Mechanical | unknown — confirm actual pressure | Higher = less rolling resistance in current formula |
| `regen_efficiency` | 0.5 | fraction | Electrical | unknown — confirm | Higher = more energy back on slowdown |
| `rho` | 1.192 | kg/m³ | Software | estimate — std air | Higher = more drag |
| `air_density_kg_per_m3` | 1.192 | kg/m³ | Software | estimate — std air | Higher = more drag |
| `g` | 9.80665 | m/s² | Software | measured — constant | Fixed, do not change |

## Ignored keys in `car_params.json` (not read by `CarConfig.from_json`)
Expand Down
28 changes: 22 additions & 6 deletions docs/scenario_inputs.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,17 +27,33 @@ Source: `car_params.json`

| Parameter | Units | Required | Affects |
|---|---:|---|---|
| `mass` | kg | Yes | Rolling resistance, Regen energy, total energy use |
| `battery_capacity` | Wh | Yes | Available battery energy, SOC changes |
| `solar_panel_area` | m² | Yes | Solar power collected |
| `mass_kg` | kg | Yes | Rolling resistance, Regen energy, total energy use |
| `battery_capacity_wh` | Wh | Yes | Available battery energy, SOC changes |
| `solar_panel_area_m2` | m² | Yes | Solar power collected |
| `solar_panel_efficiency` | fraction | Yes | Solar power collected |
| `electrical_efficiency` | fraction | Yes | Driving power consumption |
| `C_dA` | m² | Yes | Aerodynamic drag, energy use |
| `tire_pressure` | pressure units | Yes | Rolling resistance, energy use |
| `cda_m2` | m² | Yes | Aerodynamic drag, energy use |
| `tire_pressure_bar` | bar | Yes | Rolling resistance, energy use |
| `regen_efficiency` | fraction | Yes | Regen energy |
| `rho` | kg/m³ | Yes | Aerodynamic drag |
| `air_density_kg_per_m3` | kg/m³ | Yes | Aerodynamic drag |
| `g` | m/s² | Yes | Rolling resistance |

Tire pressure is in bar: the rolling-resistance formula in `sim/physics.py`
(`Crr = 0.005 + (1/P)(0.01 + 0.0095(v/100)²)`) expects bar.

**Migration:** parameters were renamed to include units. Old names are still
accepted when loading JSON files (`CarConfig.from_json` and the scenario
loader), but new files should use the new names:

| Old name | New name |
|---|---|
| `mass` | `mass_kg` |
| `battery_capacity` | `battery_capacity_wh` |
| `solar_panel_area` | `solar_panel_area_m2` |
| `C_dA` | `cda_m2` |
| `rho` | `air_density_kg_per_m3` |
| `tire_pressure` | `tire_pressure_bar` |

### Course Configuration

Course definitions are stored as separate JSON files in the repository's
Expand Down
4 changes: 2 additions & 2 deletions interactive_laps_sim.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ def project_remaining(self):
power_out = self.physics.power_drained(speed)

energy_delta = (power_in - power_out) * dt_hours
soc += energy_delta / self.car.battery_capacity
soc += energy_delta / self.car.battery_capacity_wh
soc = max(soc, self.race.min_soc)

dist_step = speed * (self.race.time_step_minutes * 60)
Expand All @@ -157,7 +157,7 @@ def project_remaining(self):
# Apply regenerative braking energy if decelerating
regen_wh = self.physics.regen_energy(prev_speed, speed)
if regen_wh > 0:
soc += regen_wh / self.car.battery_capacity
soc += regen_wh / self.car.battery_capacity_wh
soc = min(soc, 1.0) # Cap at 100%

speeds[i] = speed
Expand Down
59 changes: 43 additions & 16 deletions sim/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,30 +73,56 @@ def from_json(cls, filepath: str) -> "TrackConfig":
)


# Old parameter names -> current unit-suffixed names. Old names are still
# accepted when loading JSON files so existing parameter files keep working.
LEGACY_CAR_PARAM_NAMES = {
"mass": "mass_kg",
"battery_capacity": "battery_capacity_wh",
"solar_panel_area": "solar_panel_area_m2",
"C_dA": "cda_m2",
"rho": "air_density_kg_per_m3",
"tire_pressure": "tire_pressure_bar",
}


def migrate_legacy_car_params(params: dict) -> dict:
"""Return a copy of params with legacy keys renamed to the new names.

If both the old and new name are present, the new name wins.
"""
migrated = {}
for key, value in params.items():
new_key = LEGACY_CAR_PARAM_NAMES.get(key, key)
if new_key != key and new_key in params:
continue
migrated[new_key] = value
return migrated


@dataclass
class CarConfig:
mass: float = 337
battery_capacity: float = 5000
solar_panel_area: float = 4
mass_kg: float = 337
battery_capacity_wh: float = 5000
solar_panel_area_m2: float = 4
solar_panel_efficiency: float = 0.23
electrical_efficiency: float = 0.99
C_dA: float = 0.73809
tire_pressure: float = 5
cda_m2: float = 0.73809
tire_pressure_bar: float = 5
regen_efficiency: float = 0.5
rho: float = 1.192
air_density_kg_per_m3: float = 1.192
g: float = 9.80665

def __post_init__(self):
self.validate()

def validate(self):
if self.mass <= 0:
if self.mass_kg <= 0:
raise ValueError("Mass must be greater than 0.")
if self.tire_pressure <= 0:
if self.tire_pressure_bar <= 0:
raise ValueError("Tire pressure must be greater than 0.")
if self.battery_capacity <= 0:
if self.battery_capacity_wh <= 0:
raise ValueError("Battery capacity must be greater than 0.")
if self.solar_panel_area < 0:
if self.solar_panel_area_m2 < 0:
raise ValueError("Solar panel area must be non-negative.")
if not (0 <= self.solar_panel_efficiency <= 1):
raise ValueError("Solar panel efficiency must be between 0 and 1.")
Expand All @@ -110,20 +136,21 @@ def from_json(cls, filepath: str) -> "CarConfig":
with open(filepath, "r") as f:
params = json.load(f)

params = migrate_legacy_car_params(params)
for key, value in params.items():
if value == "inf":
params[key] = math.inf

return cls(
mass=params.get("mass", 337),
battery_capacity=params.get("battery_capacity", 5000),
solar_panel_area=params.get("solar_panel_area", 4),
mass_kg=params.get("mass_kg", 337),
battery_capacity_wh=params.get("battery_capacity_wh", 5000),
solar_panel_area_m2=params.get("solar_panel_area_m2", 4),
solar_panel_efficiency=params.get("solar_panel_efficiency", 0.23),
electrical_efficiency=params.get("electrical_efficiency", 0.99),
C_dA=params.get("C_dA", 0.73809),
tire_pressure=params.get("tire_pressure", 5),
cda_m2=params.get("cda_m2", 0.73809),
tire_pressure_bar=params.get("tire_pressure_bar", 5),
regen_efficiency=params.get("regen_efficiency", 0.5),
rho=params.get("rho", 1.192),
air_density_kg_per_m3=params.get("air_density_kg_per_m3", 1.192),
g=params.get("g", 9.80665),
)

Expand Down
4 changes: 2 additions & 2 deletions sim/controllers.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def compute_ideal_soc_curve(cloud_data: np.ndarray, race_config, alpha: float =
# Find a constant speed that consumes the total available race energy budget.
# Used as baseline speed for SOC feedback strategies to adjust around.
def solve_optimal_constant_speed(physics, race_config: RaceConfig, ghi_data: np.ndarray, dt_hours: float) -> float:
cap = physics.car.battery_capacity
cap = physics.car.battery_capacity_wh
usable_energy = (race_config.start_soc - race_config.target_soc) * cap
total_solar = np.sum(physics.solar_power(ghi_data)) * dt_hours
total_available = usable_energy + total_solar
Expand Down Expand Up @@ -136,7 +136,7 @@ def __init__(self, race_config, interval_minutes: int = 5):

# Remaining budget = usable battery above target SOC + expected solar input.
def _solve_remaining_speed(self, current_soc: float, physics, ghi_remaining: np.ndarray, dt_hours: float) -> float:
cap = physics.car.battery_capacity
cap = physics.car.battery_capacity_wh
usable_energy = max(0.0, (current_soc - self.config.target_soc) * cap)
solar_energy = np.sum(physics.solar_power(ghi_remaining)) * dt_hours
total_available = usable_energy + solar_energy
Expand Down
12 changes: 6 additions & 6 deletions sim/physics.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,29 +7,29 @@ def __init__(self, car):

def get_crr(self, v: float) -> float:
v_kmh = v * 3.6
return 0.005 + (1 / self.car.tire_pressure) * (0.01 + 0.0095 * (v_kmh / 100) ** 2)
return 0.005 + (1 / self.car.tire_pressure_bar) * (0.01 + 0.0095 * (v_kmh / 100) ** 2)

def force_drag(self, v: float) -> float:
return 0.5 * self.car.C_dA * self.car.rho * v ** 2
return 0.5 * self.car.cda_m2 * self.car.air_density_kg_per_m3 * v ** 2

def force_rolling_resistance(self, v: float) -> float:
return self.car.mass * self.car.g * self.get_crr(v)
return self.car.mass_kg * self.car.g * self.get_crr(v)

def power_drained(self, v: float) -> float:
f_d = self.force_drag(v)
f_r = self.force_rolling_resistance(v)
return (f_d + f_r) * v * self.car.electrical_efficiency

def solar_power(self, ghi: float) -> float:
return self.car.solar_panel_area * ghi * self.car.solar_panel_efficiency
return self.car.solar_panel_area_m2 * ghi * self.car.solar_panel_efficiency

def regen_energy(self, v_old: float, v_new: float) -> float:
if v_new >= v_old:
return 0.0
delta_ke = 0.5 * self.car.mass * (v_old ** 2 - v_new ** 2)
delta_ke = 0.5 * self.car.mass_kg * (v_old ** 2 - v_new ** 2)
return (delta_ke / 3600.0) * self.car.regen_efficiency

def battery_drain_rate(self, v: float, ghi: float) -> float:
power_out = self.power_drained(v)
power_in = self.solar_power(ghi)
return (power_out - power_in) / self.car.battery_capacity
return (power_out - power_in) / self.car.battery_capacity_wh
6 changes: 3 additions & 3 deletions sim/planning/comparison.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ def build_comparison_row(
"min_soc_pct": results.min_soc_pct,
"target_soc_pct": race.target_soc * 100.0,
"soc_margin_pct": results.final_soc_pct - (race.target_soc * 100.0),
"target_battery_energy_wh": car.battery_capacity * race.target_soc,
"final_battery_energy_wh": car.battery_capacity * results.final_soc_pct / 100.0,
"energy_margin_wh": (results.final_soc_pct / 100.0 - race.target_soc) * car.battery_capacity,
"target_battery_energy_wh": car.battery_capacity_wh * race.target_soc,
"final_battery_energy_wh": car.battery_capacity_wh * results.final_soc_pct / 100.0,
"energy_margin_wh": (results.final_soc_pct / 100.0 - race.target_soc) * car.battery_capacity_wh,
"avg_speed_mph": results.avg_speed_mph,
"max_speed_mph": results.max_speed_mph,
"min_speed_mph": results.min_speed_mph,
Expand Down
4 changes: 2 additions & 2 deletions sim/planning/report.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ def print_planning_report(
print()
print(f"Track: {track.name}")
print(f"Location: {track.location}")
print(f"Battery capacity: {car_config.battery_capacity} Wh")
print(f"Target final battery energy: {car_config.battery_capacity * race_config.target_soc} Wh")
print(f"Battery capacity: {car_config.battery_capacity_wh} Wh")
print(f"Target final battery energy: {car_config.battery_capacity_wh * race_config.target_soc} Wh")
print(f"Target final SoC: {race_config.target_soc * 100:.1f}%")

print("Best Fixed Speed:")
Expand Down
15 changes: 8 additions & 7 deletions sim/scenarios.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from dataclasses import fields
from typing import Dict

from sim.config import CarConfig
from sim.config import CarConfig, migrate_legacy_car_params

CONSERVATIVE = "conservative"
BASE = "base"
Expand All @@ -18,14 +18,14 @@
# -1: conservative = value - uncertainty (bigger is better for performance)
# Optimistic is always the opposite. Parameters not listed (e.g. g) are held fixed.
CONSERVATIVE_DIRECTION: Dict[str, int] = {
"mass": +1, # heavier -> more rolling loss, more energy to accelerate
"C_dA": +1, # more drag
"rho": +1, # denser air -> more drag
"battery_capacity": -1, # less usable energy
"solar_panel_area": -1, # less solar power
"mass_kg": +1, # heavier -> more rolling loss, more energy to accelerate
"cda_m2": +1, # more drag
"air_density_kg_per_m3": +1, # denser air -> more drag
"battery_capacity_wh": -1, # less usable energy
"solar_panel_area_m2": -1, # less solar power
"solar_panel_efficiency": -1, # less solar power
"electrical_efficiency": -1, # more losses (see note below)
"tire_pressure": -1, # lower pressure -> higher Crr
"tire_pressure_bar": -1, # lower pressure -> higher Crr
"regen_efficiency": -1, # less energy recovered
}
# NOTE: physics.py currently multiplies drain by electrical_efficiency, so a lower
Expand All @@ -51,6 +51,7 @@ def make_scenario(params: Dict[str, dict], scenario: str) -> CarConfig:
if scenario not in SCENARIOS:
raise ValueError(f"unknown scenario {scenario!r}; expected one of {SCENARIOS}")
sign = {CONSERVATIVE: +1, BASE: 0, OPTIMISTIC: -1}[scenario]
params = migrate_legacy_car_params(params) # accept pre-unit-suffix names

kwargs = {}
for f in fields(CarConfig):
Expand Down
4 changes: 2 additions & 2 deletions sim/simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def run(self) -> SimulationResults:

prev_soc = soc
energy_delta = (power_in - power_out) * step_hours
next_soc = prev_soc + energy_delta / self.car.battery_capacity
next_soc = prev_soc + energy_delta / self.car.battery_capacity_wh

step_fraction = 1.0
hit_min_soc = prev_soc > self.race.min_soc and next_soc <= self.race.min_soc
Expand Down Expand Up @@ -113,7 +113,7 @@ def run(self) -> SimulationResults:

regen_wh = self.physics.regen_energy(prev_speed, speed)
if regen_wh > 0:
soc += regen_wh / self.car.battery_capacity
soc += regen_wh / self.car.battery_capacity_wh
soc = min(soc, 1.0)

time_arr.append(time_minutes[i] + step_minutes * step_fraction)
Expand Down
8 changes: 4 additions & 4 deletions tests/planning/test_comparison.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

class TestComparison(unittest.TestCase):
def test_battery_energy_calculations(self):
car = CarConfig(battery_capacity=5000)
car = CarConfig(battery_capacity_wh=5000)
race = RaceConfig(target_soc=0.4)
results = SimpleNamespace(
total_laps=1,
Expand All @@ -27,7 +27,7 @@ def test_battery_energy_calculations(self):
self.assertAlmostEqual(row["energy_margin_wh"], 1000.0) # (0.6-0.4) * 5000 = 1000

def test_positive_margin(self):
car = CarConfig(battery_capacity=5000)
car = CarConfig(battery_capacity_wh=5000)
race = RaceConfig(target_soc=0.4)
results = SimpleNamespace(
total_laps=1,
Expand All @@ -47,7 +47,7 @@ def test_positive_margin(self):
self.assertGreater(row["energy_margin_wh"], 0)

def test_negative_margin(self):
car = CarConfig(battery_capacity=5000)
car = CarConfig(battery_capacity_wh=5000)
race = RaceConfig(target_soc=0.4)
results = SimpleNamespace(
total_laps=1,
Expand All @@ -67,7 +67,7 @@ def test_negative_margin(self):
self.assertLess(row["energy_margin_wh"], 0)

def test_zero_margin(self):
car = CarConfig(battery_capacity=5000)
car = CarConfig(battery_capacity_wh=5000)
race = RaceConfig(target_soc=0.4)
results = SimpleNamespace(
total_laps=1,
Expand Down
Loading
Loading