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
12 changes: 12 additions & 0 deletions courses/brainerd_international_raceway.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"course_name": "Brainerd International Raceway (Donnybrooke Course)",
"course_name_argument": "brainerd_international_raceway",
"lap_distance_m": 4989,
"total_laps": null,
"elevation": null,
"source": null,
"location": "Brainerd, Minnesota",
"latitude": 46.4176,
"longitude": -94.2853,
"timezone": "America/Chicago"
}
12 changes: 12 additions & 0 deletions courses/shenandoah_speedway.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"course_name": "Shenandoah Speedway",
"course_name_argument": "shenandoah_speedway",
"lap_distance_m": 604,
"total_laps": null,
"elevation": null,
"source": null,
"location": "Page County, Virginia",
"latitude": 38.511,
"longitude": -78.6359,
"timezone": "America/New_York"
}
12 changes: 12 additions & 0 deletions courses/virginia_international_raceway.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"course_name": "Virginia International Raceway (Patriot Course)",
"course_name_argument": "virginia_international_raceway",
"lap_distance_m": 1770,
"total_laps": null,
"elevation": null,
"source": null,
"location": "Alton, Virginia",
"latitude": 36.5666,
"longitude": -79.2058,
"timezone": "America/New_York"
}
57 changes: 57 additions & 0 deletions docs/course_format.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Course Definition File Format

Course definitions are JSON files stored in the repository's `courses/` directory. They describe the physical course and the location metadata needed to retrieve weather. Car parameters, weather assumptions, and race strategy settings remain separate inputs.

## File naming and loading

- Each course is stored in its own `.json` file.
- The simulator loads every JSON file in `courses/` through `get_available_tracks()`.
- `course_name_argument` is the value accepted by the `--location` command-line option.
- Course files are loaded in filename order for the interactive course list.
- The file name does not determine the command-line identifier; use
`course_name_argument` for that identifier.
- Missing required fields or a non-numeric `lap_distance_m` value causes the
course file to be rejected.

## Fields

| Field | Type | Required | Description |
|---|---|---:|---|
| `course_name` | string | Yes | Human-readable course or route name. |
| `course_name_argument` | string | Yes | Stable identifier used with `--location`. |
| `lap_distance_m` | number | Yes | One lap or route distance in meters. |
| `total_laps` | positive integer or `null` | No | Fixed number of laps when the event has one. Use `null` for time-window simulations; this is reserved for future fixed-lap support. |
| `elevation` | string or `null` | No | Elevation data or reference. Use `null` until elevation support is added. |
| `source` | string or `null` | No | Source for the course measurements or route data. Use `null` until source metadata is needed. |
| `location` | string | Yes | Human-readable location used in reports. |
| `latitude` | number | Yes | Latitude used for weather lookup, in degrees. |
| `longitude` | number | Yes | Longitude used for weather lookup, in degrees. |
| `timezone` | string | Yes | IANA timezone used for local race and weather times. |

`lap_distance_m` must be greater than zero. If `total_laps` is not `null`, it
must be greater than zero. The `total_laps`, `elevation`, and `source` fields
are currently future-capability placeholders and are stored as `null` in the
current course files. All distances are in meters.

At runtime, `TrackConfig.lap_distance_m` is the primary course-distance value.
`TrackConfig.lap_distance_km` is a derived property used only when kilometer
output is requested.

## Example

```json
{
"course_name": "Shenandoah Speedway",
"course_name_argument": "shenandoah_speedway",
"lap_distance_m": 604,
"total_laps": null,
"elevation": null,
"source": null,
"location": "Page County, Virginia",
"latitude": 38.511,
"longitude": -78.6359,
"timezone": "America/New_York"
}
```

`total_laps` is shown as `null` because the current simulator runs a race window and calculates completed laps from elapsed distance (future implementation for fixed-lap events). The `elevation` and `source` fields are also `null` because those are reserved for future capabilities.
38 changes: 28 additions & 10 deletions docs/scenario_inputs.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ This document separates inputs provided by a user from the configuration paramet
| User input | How it is provided | Maps to |
|---|---|---|
| Car parameters | `car_params.json` | `CarConfig` |
| Track | `--location` or prompt | `TrackConfig` |
| Course | `--location` or prompt | JSON file in `courses/`, loaded as `TrackConfig` |
| Strategy | `--strategy` or prompt | `RaceConfig.strategy` |
| Aggressiveness | `--aggressiveness` | `RaceConfig.aggressiveness` |
| Energy safety scale | Interactive prompt | `RaceConfig.energy_safety_scale` |
Expand Down Expand Up @@ -38,18 +38,36 @@ Source: `car_params.json`
| `rho` | kg/m³ | Yes | Aerodynamic drag |
| `g` | m/s² | Yes | Rolling resistance |

### Track Configuration

| Parameter | Units | Required | Affects |
|---|---:|---|---|
| `name` | text | Yes | Report and plot labels |
| `file_path_name` | text | Yes | Track identifier and output filenames |
| `location` | text | Yes | Human-readable location |
### Course Configuration

Course definitions are stored as separate JSON files in the repository's
`courses/` directory. The simulator loads every `.json` file in that directory
and uses `course_name_argument` as the value for `--location`. Course data is
kept separate from car parameters, weather assumptions, and race strategy
settings.

See [course_format.md](course_format.md) for the complete file format.

| JSON field | Units / type | Required | Affects |
|---|---|---|---|
| `course_name` | text | Yes | Report and plot labels |
| `course_name_argument` | text | Yes | `--location` identifier and output filenames |
| `lap_distance_m` | m | Yes | Internal distance and lap counting |
| `total_laps` | positive integer or `null` | No | Reserved for future fixed-lap events; currently defaults to `null` |
| `elevation` | text or `null` | No | Reserved for future elevation data |
| `source` | text or `null` | No | Reserved for future course-source metadata |
| `location` | text | Yes | Human-readable location in reports |
| `latitude`, `longitude` | degrees | Yes | Weather API location |
| `lap_distance_km` | km | Yes | Distance and lap count |
| `timezone` | IANA timezone | Yes | Local race and weather times |

Available track IDs: `shenandoah_speedway`, `virginia_international_raceway`, `brainerd_international_raceway`.
The simulator stores and calculates course distance in meters. A derived
`TrackConfig.lap_distance_km` property is available only for kilometer display.

Current course identifiers are:

- `shenandoah_speedway`
- `virginia_international_raceway`
- `brainerd_international_raceway`

### Race and Battery Conditions

Expand Down
109 changes: 74 additions & 35 deletions sim/config.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from dataclasses import dataclass, field
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, List, Optional
import json
import math
Expand All @@ -12,17 +13,62 @@ class TrackConfig:
location: str
latitude: float
longitude: float
lap_distance_km: float
lap_distance_m: float
timezone: str
lap_distance_m: float = field(init=False)
total_laps: Optional[int] = None
elevation: Optional[str] = None
source: Optional[str] = None

def __post_init__(self):
self.lap_distance_m = self.lap_distance_km * 1000.0
self.validate()

@property
def lap_distance_km(self) -> float:
return self.lap_distance_m / 1000.0

def validate(self):
if self.lap_distance_km <= 0:
if self.lap_distance_m <= 0:
raise ValueError("Lap distance must be greater than 0.")
if self.total_laps is not None and self.total_laps <= 0:
raise ValueError("Total laps must be greater than 0.")

@classmethod
def from_json(cls, filepath: str) -> "TrackConfig":
with open(filepath, "r") as f:
course = json.load(f)

required_fields = (
"course_name",
"course_name_argument",
"lap_distance_m",
"location",
"latitude",
"longitude",
"timezone",
)
missing_fields = [field for field in required_fields if field not in course]
if missing_fields:
raise ValueError(
f"Course file {filepath} is missing required fields: "
+ ", ".join(missing_fields)
)

lap_distance_m = course["lap_distance_m"]
if not isinstance(lap_distance_m, (int, float)) or isinstance(lap_distance_m, bool):
raise ValueError("lap_distance_m must be a number.")

return cls(
name=course["course_name"],
file_path_name=course["course_name_argument"],
location=course["location"],
latitude=course["latitude"],
longitude=course["longitude"],
lap_distance_m=float(lap_distance_m),
timezone=course["timezone"],
total_laps=course.get("total_laps"),
elevation=course.get("elevation"),
source=course.get("source"),
)


@dataclass
Expand Down Expand Up @@ -182,33 +228,26 @@ def max_speed_mph(self) -> float:
def min_speed_mph(self) -> float:
return float(np.min(self.speed)) * 2.237

def get_available_tracks() -> List[TrackConfig]:
return [
TrackConfig(
name="Shenandoah Speedway",
file_path_name="shenandoah_speedway",
location="Page County, Virginia",
latitude=38.5110,
longitude=-78.6359,
lap_distance_km=0.604,
timezone="America/New_York",
),
TrackConfig(
name= "Virginia International Raceway (Patriot Course)",
file_path_name="virginia_international_raceway",
location="Alton, Virginia",
latitude=36.5666,
longitude=-79.2058,
lap_distance_km=1.77,
timezone="America/New_York"
),
TrackConfig(
name= "Brainerd International Raceway (Donnybrooke Course)",
file_path_name="brainerd_international_raceway",
location="Brainerd, Minnesota",
latitude=46.4176,
longitude=-94.2853,
lap_distance_km=4.989,
timezone="America/Chicago"
)
]
def get_available_tracks(courses_dir: Optional[str] = None) -> List[TrackConfig]:
course_directory = (
Path(courses_dir)
if courses_dir is not None
else Path(__file__).resolve().parents[1] / "courses"
)
course_files = sorted(course_directory.glob("*.json"))
if not course_files:
raise FileNotFoundError(f"No course JSON files found in {course_directory}")

return [TrackConfig.from_json(str(course_file)) for course_file in course_files]


def get_track_by_argument(
course_name_argument: str, courses_dir: Optional[str] = None
) -> TrackConfig:
tracks = get_available_tracks(courses_dir)
for track in tracks:
if track.file_path_name == course_name_argument:
return track

available = ", ".join(track.file_path_name for track in tracks)
raise ValueError(f"Unknown course '{course_name_argument}'. Available courses: {available}")
24 changes: 19 additions & 5 deletions sim/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from sim.config import CarConfig, RaceConfig, get_available_tracks
from sim.config import (
CarConfig,
RaceConfig,
get_available_tracks,
get_track_by_argument,
)
from sim.planning.sweep import (
DEFAULT_AGGRESSIVENESS,
SPEED_SWEEP_MPH,
Expand All @@ -22,11 +27,18 @@

def parse_args():
parser = argparse.ArgumentParser(description="Modular laps race simulator")
try:
location_choices = [
track.file_path_name for track in get_available_tracks()
]
except (FileNotFoundError, ValueError) as exc:
parser.error(f"Unable to load courses: {exc}")

parser.add_argument(
"--location",
choices=["shenandoah_speedway", "virginia_international_raceway", "brainerd_international_raceway"],
choices=location_choices,
default=None,
help="Race location selection (currently only Shenandoah)",
help="Course identifier from the courses directory",
)
parser.add_argument(
"--strategy",
Expand Down Expand Up @@ -153,8 +165,10 @@ def main():
print("Using default car parameters")

if args.location is not None:
track = next(track for track in tracks
if track.file_path_name == args.location)
try:
track = get_track_by_argument(args.location)
except (FileNotFoundError, ValueError) as exc:
raise SystemExit(f"Unable to select course: {exc}") from exc
else:
print("Choose a track to test on:")
for i, available_track in enumerate(tracks, start=1):
Expand Down
2 changes: 1 addition & 1 deletion sim/reporting.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,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_km/1.609:.2f} miles)")
print(f" Lap Distance: {self.track.lap_distance_km:.3f} km ({self.track.lap_distance_m/1609.34:.2f} miles)")

print("\nRace Results:")
print(f" Total Laps Completed: {r.total_laps}")
Expand Down
2 changes: 1 addition & 1 deletion tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,6 @@ def test_invalid_track_config():
location="test",
latitude=0,
longitude=0,
lap_distance_km=0,
lap_distance_m=0,
timezone="UTC",
)
Loading