0% found this document useful (0 votes)
8 views8 pages

EV Routing Engine

The EV Routing Engine integrates Valhalla, FASTSim, and PostGIS to create a physics-accurate journey planner for electric vehicles. Valhalla provides geographic routing while FASTSim models the physics of energy consumption, working together to simulate battery state-of-charge throughout a journey. The system is designed for scalability and efficiency, utilizing a Node.js backend to orchestrate interactions between components and ensure safety during low battery scenarios.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views8 pages

EV Routing Engine

The EV Routing Engine integrates Valhalla, FASTSim, and PostGIS to create a physics-accurate journey planner for electric vehicles. Valhalla provides geographic routing while FASTSim models the physics of energy consumption, working together to simulate battery state-of-charge throughout a journey. The system is designed for scalability and efficiency, utilizing a Node.js backend to orchestrate interactions between components and ensure safety during low battery scenarios.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

EV Routing Engine

Merging Valhalla, FASTSim, and PostGIS into a production-grade, physics-accurate EV journey


planner — the same architecture powering industry leaders

ú The Master Navigator ² The Battery Mechanic


Valhalla — open-source routing engine FASTSim (NREL/U.S. DoE) — a physics
that sees the world as a 3D graph of roads, simulation engine that models
costs, and elevation changes. aerodynamic drag, rolling resistance, and
gravity forces on every segment.
The Two Co-Pilots
This engine is best understood as two deeply specialized expert systems operating in parallel — one knows the world, the other knows physics. Neither alone can
solve the problem. Together, they produce a simulation that is both geographically accurate and thermodynamically honest.

🧭 Valhalla — The Master Navigator ⚡ FASTSim — The Battery Mechanic


Valhalla sees the entire road network as a massive weighted directed graph. Developed by NREL (National Renewable Energy Laboratory) for the U.S.
Every intersection is a node, every road segment an edge — annotated with Department of Energy, FASTSim is a longitudinal vehicle dynamics simulator.
speed limits, turn penalties, surface type, and critically, 3D elevation data. Its It has no concept of maps or geography — it only understands physics. Feed it a
job is to calculate the "least-cost" path, where cost is a proxy for energy speed profile and an elevation profile, and it will tell you exactly how many
expenditure. It handles the where and the how fast. kWh a specific car will consume. It handles the how much energy.

Processes OpenStreetMap data (e.g., the 700MB [Link] dataset FASTSim models three invisible forces that dominate EV range:
from Geofabrik)
Aerodynamic Drag: Scales with the cube of speed — the single largest
Elevation-aware routing using 60-meter interval sampling
energy sink on highways
Exposes a REST API for route, matrix, and isochrone queries
Rolling Resistance: Constant tire-deformation friction proportional to
vehicle mass and speed
Gravitational Load: Climbing elevation drains the pack; descent enables
regenerative braking to recover energy
How the Engine Communicates
THE SIMULATION LOOP

The core innovation is the segment-by-segment simulation dialogue between Valhalla and FASTSim. Valhalla decomposes the full route into discrete physical
segments with elevation deltas sampled at a 60-meter interval, and FASTSim processes each segment sequentially — accumulating a precise, physics-validated
battery state-of-charge (SOC) throughout the journey.

Valhalla → "First 10 km: flat terrain, 120 km/h 1


speed limit"
FASTSim responds: "Pushing an ~1,800 kg EV at 120 km/h through air
for 10 km — aerodynamic drag dominates. Estimated draw: 3% SOC."
Drag force scales as v², power as v³ — high-speed highway segments
2 Valhalla → "Next segment: 5 km mountain
climb at 60 km/h"
are the harshest battery consumers.
FASTSim responds: "Sustained positive elevation gradient —
gravitational potential energy work dominates. Motor draws
Valhalla → "Descent segment: 4 km downhill 3 sustained high current from the pack. Estimated draw: 5% SOC."
grade"
FASTSim responds: "Regenerative braking active — kinetic energy
converted back to electrical energy via motor-as-generator. Estimated
recovery: +1.8% SOC." This is free energy the physics model captures 4 🚨 Emergency Safety Trigger: Battery SOC < 10%
precisely. The orchestration layer immediately pauses the simulation, queries
the Supabase RPC for the 5 nearest chargers within a configurable
radius, evaluates each via Valhalla's Matrix API for real drivable time-
cost, selects the fastest reachable option, draws a detour polyline,
and restarts the FASTSim loop from the charger waypoint. The user
sees a high-visibility emergency reroute alert on the frontend.
Phase 1 — Spatial Database Foundation
SUPABASE + POSTGIS

The spatial database layer is not a simple lookup table — it is a full geospatial computation engine. PostGIS transforms PostgreSQL into a system capable of sub-
millisecond geographic distance calculations across millions of coordinate pairs, using a dedicated spatial indexing structure (GIST) optimized for two-dimensional
geographic bounding box queries.

1 2 3

Enable PostGIS Extension Charger Schema — Emergency Search RPC —


Activate the PostGIS engine via the Supabase
geography(POINT, 4326) find_nearest_chargers
dashboard extensions panel. This unlocks the Store charger locations using the A custom PostgreSQL stored procedure
geography and geometry column types, all geography(POINT, 4326) data type — SRID exposed as a Supabase RPC. Accepts a GPS
ST_* spatial functions, and the ability to create 4326 is the WGS84 coordinate system used by coordinate and search radius (e.g., 50 km).
GIST spatial indexes. A single SQL command: GPS. This critically stores coordinates as true Internally executes
CREATE EXTENSION postgis; spherical geodetic points, not flat Cartesian ST_Distance([Link], input_point)
approximations, ensuring ST_Distance returns with an ORDER BY and LIMIT 5, returning the
accurate real-world meters, not distorted 5 closest chargers instantly — bypassing the
Euclidean distances. Add a GIST spatial index ORM for raw spatial math at maximum
to enable index-accelerated nearest-neighbor performance.
scans across millions of rows in milliseconds.
Phase 2 — The Routing Core
VALHALLA ON VPS

Running Valhalla self-hosted is the architectural decision that decouples cost from scale. Unlike Google Maps or HERE APIs that charge per request, a self-hosted
Valhalla instance on a 4-core, 8GB RAM DigitalOcean droplet handles unlimited routing queries at a flat infrastructure cost — critical for production systems with
high query volumes.

Step 1 — Local Map Build Steps 2 & 3 — VPS Deployment & Security
Download the 700MB [Link] extract from Geofabrik — a compressed Provision a Linux/Ubuntu VPS (DigitalOcean droplet: 4 vCPUs, 8 GB RAM) and
binary OSM data format. Run the Valhalla Docker image locally to ingest, upload the pre-built compressed routing tiles via SCP or rsync. Run the
process, and tile this dataset into Valhalla's proprietary compressed routing Valhalla Docker container bound to a local port (e.g., :8002). Configure Nginx
tile format. Building locally preserves cloud RAM and avoids expensive as a reverse proxy to expose Valhalla at a clean HTTPS endpoint, and
compute on the VPS during the initial tile generation phase, which can provision a TLS certificate via Let's Encrypt (Certbot) for end-to-end SSL. The
consume 6–12 GB of RAM depending on region size. The output compressed result is a private, secured, scalable Valhalla API endpoint accessible only to
tile set is typically 20–30% the size of the raw PBF input. the [Link] orchestration backend — not the public internet.

Valhalla's Matrix API — used during emergency rerouting — evaluates travel cost from one origin to N destinations simultaneously, making it ideal for
selecting the fastest reachable charger from among the 5 PostGIS candidates in a single API call.
Phase 3 — The Physics Brain
FASTSIM INTEGRATION

FASTSim is open-sourced by NREL as a Python library. For production integration into a [Link]/Express backend, the relevant physics logic — longitudinal vehicle
dynamics, polynomial efficiency curves, and force calculations — must be ported to TypeScript/JavaScript. This eliminates Python runtime overhead, subprocess
spawning, and cross-language serialization penalties, delivering physics simulation at native JS execution speed.

Step 1 — Port FASTSim to TypeScript Step 2 — Vehicle Profiles (JSON) Step 3 — The Physics Segment Loop
Translate NREL's Python physics math — including EV specs are stored as JSON configuration objects, A JavaScript for loop iterates over every route
polynomial motor efficiency curves (mapping enabling a scalable multi-vehicle library. Example — segment from Valhalla's 60-meter elevation-interval
torque/RPM to efficiency %) and the longitudinal Tesla Model 3: response. Per segment, it calculates: aerodynamic
dynamics equations (summing aerodynamic drag, mass: 1850 kg drag power (cubic function of speed), rolling
rolling resistance, and gravitational force vectors) — drag_coefficient (Cd): 0.23 resistance power (linear in mass × velocity), and
into a blazing-fast TypeScript utility module frontal_area: 2.22 m² gravitational power (mass × g × elevation_delta /
consumed directly by the Express backend. No battery_capacity: 60 kWh time). FASTSim polynomial efficiency curves convert
subprocess overhead, no inter-process serialization. These values feed directly into the drag force wheel power to exact kWh drawn from (or
formula: F_drag = ½ × ρ × Cd × A × v², where ρ is air returned to) the battery pack. Accumulated across
density at ~1.225 kg/m³. all segments, this yields a precise arrival SOC.
Phase 4 — Orchestration
THE [Link] MIDDLEMAN

The [Link]/Express backend is the central nervous system of the entire engine — it coordinates every subsystem, enforces the safety logic, and delivers a single,
unified, physics-validated routing response to the client. No subsystem communicates directly with another; all inter-service calls flow through this orchestration
layer.

1 2

Step 1 — Ingest Request Step 2 — Intercept & Simulate


POST /api/route receives: Origin coordinates, Destination coordinates, [Link] calls the VPS Valhalla API requesting a route with
EV Model ID (maps to vehicle JSON profile), and Current Battery %. Input is elevation_interval: 60 meters. The returned 3D polyline (lat/lng + elevation
validated and the vehicle profile is loaded from the JSON store. per node) is passed directly into the FASTSim TypeScript loop, which
produces a per-segment SOC drain array and cumulative battery arrival state.

3 4

Step 3 — Emergency Trigger Step 4 — Return Payload


If projected battery SOC drops below 10% at any segment, [Link] pauses Returns finalized physics-approved JSON to the client: encoded polyline,
simulation, calls the Supabase find_nearest_chargers RPC (5 candidates turn-by-turn maneuvers, per-waypoint battery arrival states, charger
within radius), evaluates them via Valhalla Matrix API, selects the minimum- waypoints (if inserted), and estimated kWh consumed per segment. The
cost charger, and inserts it as a forced waypoint. Simulation restarts from client receives a single response ready to render.
the charger with a recharged SOC.
System Architecture — End-to-End
FULL STACK OVERVIEW

The complete system spans five distinct infrastructure layers — each with a single clear responsibility. No layer bleeds into another's domain. This separation of
concerns is what makes the system debuggable, scalable, and extensible to new vehicle models, new geographic regions, and new routing constraints without re-
architecting the core.

60m 700MB
Elevation Interval [Link]
Valhalla samples elevation every 60 meters for high-fidelity physics input to Raw OpenStreetMap binary extract from Geofabrik for the entire Indian road
FASTSim network

1850kg 10%
Tesla Model 3 Mass SOC Safety Threshold
Vehicle mass used in all longitudinal dynamics force calculations within Battery state-of-charge level that triggers mandatory emergency reroute to
FASTSim nearest charger

You might also like