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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,7 @@ plots/laps_modular/*
!plots/laps_modular/.gitkeep
lap_sim_plots/*
plots/*
csv/*

.idea
venv.
Expand Down
11 changes: 10 additions & 1 deletion sim/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
run_fixed_speed_sweep,
run_strategy_sweep,
)
from sim.planning.report import print_planning_report
from sim.planning.report import print_planning_report, export_planning_report_to_csv
from sim.simulator import LapsRaceSimulator
from sim.reporting import ResultsReporter
from sim.plotting import SimulationPlotter, save_all_plots
Expand Down Expand Up @@ -115,6 +115,9 @@ def fmt_elapsed(minute_of_day: float, start_time_hour: float) -> str:
f" {row['laps']:>4} | {row['distance_miles']:>13.1f} | {cutoff:>22} | {'Yes' if row['feasibility'] else 'No'}"
)

output_path = os.path.join(os.getcwd(), "csv/")
export_planning_report_to_csv(rows=rows, output_dir=output_path)

def print_speed_sweep_summary(rows):
print("\nSpeed sweep results:")

Expand Down Expand Up @@ -205,6 +208,12 @@ def main():
race_config=base_race,
car_config=car
)

output_path = os.path.join(os.getcwd(), "csv/")
export_planning_report_to_csv(
rows=fixed_speed_rows + strategy_rows,
output_dir=output_path,
)
return

if args.speed_sweep:
Expand Down
24 changes: 24 additions & 0 deletions sim/planning/report.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,3 +77,27 @@ def print_planning_report(
f" Expected result: {best_row['laps']} laps, "
f"{best_row['final_soc_pct']:.1f}% final SoC."
)

def export_planning_report_to_csv(
*,
rows: list[dict],
output_dir: str,
file_name: str = "planning_report.csv",
) -> None:

import csv
import os.path

if not rows:
return

os.makedirs(output_dir, exist_ok=True)

fieldnames = rows[0].keys()
with open(os.path.join(output_dir, file_name), mode='w', newline='') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for row in rows:
writer.writerow(row)

print(f"Planning report CSV exported to {output_dir}")
132 changes: 132 additions & 0 deletions tests/csv_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import csv
import os
import tempfile
import unittest
from types import SimpleNamespace
from unittest.mock import patch

from sim.config import CarConfig, TrackConfig
from sim.main import main as run_main, run_speed_sweep


class TestCSV(unittest.TestCase):
def test_fixed_speed_sweep(self):
car = CarConfig()
track = TrackConfig(
name="Test Track",
file_path_name="test_track",
location="Test Location",
latitude=0.0,
longitude=0.0,
lap_distance_km=1.0,
timezone="UTC",
)
simulator_args = []

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

def run(self):
return SimpleNamespace(
total_laps=1,
total_distance_miles=1.0,
final_soc_pct=80.0,
min_soc_pct=75.0,
avg_speed_mph=20.0,
max_speed_mph=20.0,
min_speed_mph=20.0,
completed_full_window=True,
hit_min_soc=False,
reached_min_soc_time_minutes=480.0,
)

with tempfile.TemporaryDirectory() as output_dir:
with patch("sim.planning.sweep.LapsRaceSimulator", StubSimulator):
with patch("sim.main.os.getcwd", return_value=output_dir):
run_speed_sweep(track, car, None)

csv_path = os.path.join(output_dir, "csv", "planning_report.csv")
self.assertTrue(os.path.isfile(csv_path))

with open(csv_path, newline="") as csv_file:
rows = list(csv.DictReader(csv_file))

csv_columns = rows[0].keys()
self.assertIn("study", csv_columns)
self.assertIn("label", csv_columns)
self.assertIn("strategy", csv_columns)
self.assertIn("mph", csv_columns)
self.assertIn("laps", csv_columns)
self.assertIn("distance_miles", csv_columns)
self.assertIn("final_soc_pct", csv_columns)
self.assertIn("target_soc_pct", csv_columns)
self.assertIn("soc_margin_pct", csv_columns)
self.assertIn("energy_margin_wh", csv_columns)
self.assertIn("feasibility", csv_columns)
self.assertIn("avg_speed_mph", csv_columns)
self.assertTrue(len(rows) > 1)

def test_planning_report(self):
car = CarConfig()
track = TrackConfig(
name="Test Track",
file_path_name="test_track",
location="Test Location",
latitude=0.0,
longitude=0.0,
lap_distance_km=1.0,
timezone="UTC",
)

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

def run(self):
return SimpleNamespace(
total_laps=1,
total_distance_miles=1.0,
final_soc_pct=80.0,
min_soc_pct=75.0,
avg_speed_mph=20.0,
max_speed_mph=20.0,
min_speed_mph=20.0,
completed_full_window=True,
hit_min_soc=False,
reached_min_soc_time_minutes=480.0,
)

args = SimpleNamespace(
plan=True,
speed_sweep=False,
location=track.file_path_name,
)
with tempfile.TemporaryDirectory() as output_dir:
with patch("sim.main.parse_args", return_value=args):
with patch("sim.main.get_available_tracks", return_value=[track]):
with patch("sim.main.CarConfig.from_json", return_value=car):
with patch("sim.planning.sweep.LapsRaceSimulator", StubSimulator):
with patch("sim.main.os.getcwd", return_value=output_dir):
run_main()

csv_path = os.path.join(output_dir, "csv", "planning_report.csv")
self.assertTrue(os.path.isfile(csv_path))

with open(csv_path, newline="") as csv_file:
rows = list(csv.DictReader(csv_file))

csv_columns = rows[0].keys()
self.assertIn("study", csv_columns)
self.assertIn("label", csv_columns)
self.assertIn("strategy", csv_columns)
self.assertIn("mph", csv_columns)
self.assertIn("laps", csv_columns)
self.assertIn("distance_miles", csv_columns)
self.assertIn("final_soc_pct", csv_columns)
self.assertIn("target_soc_pct", csv_columns)
self.assertIn("soc_margin_pct", csv_columns)
self.assertIn("energy_margin_wh", csv_columns)
self.assertIn("feasibility", csv_columns)
self.assertIn("avg_speed_mph", csv_columns)
self.assertTrue(len(rows) > 1)