freeCodeCamp /
freeCodeCamp
freeCodeCamp.org's open-source codebase and curriculum. Learn math, programming, and computer science for free.
Loading repository data…
movsim / repository
Source code for javascript simulation of website
Source code for the interactive Javascript simulation at traffic-simulation.de
The simulations should be self-explaining and is also explained in the instruction boxes in most scenarios.
Besides simulating online, you can also use this simulator to generate vehicle trajectory files and virtual detector data files by using the blue download button (details further below).
Information on the used models and numerical integration schemes can be found in the links on the simulator page. In the following, I give some overview about the implementation.
This simulation uses JavaScript together with html5.
The master html file, for example onramp.html, starts the actual simulation by the canvas tag:
<canvas id="canvas_onramp" ... >some text for old browsers </canvas>
What to do with this canvas is specified in the init() procedure of onramp.js which starts the simulation and is assocoated with this canvas by the first command of the init procedure,
canvas = document.getElementById("canvas_onramp");
(for ring.html, the init procedure of ring.js would be associated with the canvas of that file, and so on). At the end of the initialization, init() starts the actual simulation thread by the command
return setInterval(main_loop, 1000/fps);
The canvas dimensions are set/reset depending on the actual browser's viewport size by additional controls in canvasresize.js implementing a responsive design.
If the simulation does not run, sometimes the cause is old code in cached javascript or css files. So, the first thing to do is empty the cache
Just download the whole project: go to the green Code button on the github project page, wait for the dropdown menu of Code to open and chose Download ZIP (if no green Code button is visible, first chose the black Code option at the top left of the page). After unpacking, load, e.g., index.html as a local file in your favourite browser.
The javascript code uses pseudo objects in appropriately named files, particularly
the top-level simulation code for the corresponding scenario called in ring.html, onramp.html etc. Initializes the road network elements needed for the corresponding scenario (e.g. mainroad and onramp for the onramp scenario), starts/stops the simulation, controls the simulation updates in each time step depending on the scenario, draws everything, and implements the user controls defined in ring_gui.js, onramp_gui.js etc.
Defines the user control. Each simulation scenario (such as ring, onramp, roadworks) has both a top-level simulation javascript file <scenario>.js, and an associated gui <scenario>_gui.js (and of course an html file <scenario>.html).
represents a directional logical road link as array element of the network variable defined in the top-level scenario files and organizes the vehicles on it. Contains an array of vehicles and methods to get the neighboring vehicles for a given vehicle, to update all vehicles for one time step, and to interact with/get information of neighboring road network elements.
The longitudinal (arclength) coordinate u runs from u=0 to u=roadLen
The lateral coordinate v increases to the right with v=0 at the road axis. The lane numbering also starts from the left.
It also has a unique roadID and provides methods to draw this network element and the vehicles on it. These drawing methods depend on the road geometry functions traj_x and traj_y giving the geo-located positions (x,y) as a function of the arclength u which are provided by the calling pseudoclasses <scenario>.js at construction time.
Further details for road.js and how to connect it with other roads are given further below.
each vehicle represents a vehicle-driver unit and has (i) properties such as length, width, type, (ii) dynamic variables such as position and speed, and (iii) a (deep copied) instance of the acceleration/lane changing methods from models.js. Optionally, a vehicle has also a route as a sequence of roadIDs to be traversed. This is only needed in scenarios with off-ramps or intersections.
Each vehicle also has a data element driverfactor set at construction time to model inter-driver variations (see below).
Besides regular vehicles, there are also special vehicle objects to be identified by their vehicle ID:
veh.id=1: ego vehicle (in future "ego-game" versions)veh.id=10..49: vehicles that are clicked (and disturbed)veh.id=50..99: user-moveable obstacles (desired speed zero, no stochasticity)veh.id=100..149 obstacles representing red traffic lightsveh.id >=200: normal vehicles and fixed obstaclesa collection of pseudo-classes for the longitudinal models (presently, the IDM and an extension from it, the ACC model), and lane-changing decision models (presently, MOBIL), see the references section for details. In addition to the pure models, following features are implemented.
White acceleration noise of intensity QnoiseAccel that is also uncorrelated between vehicles. This leads to a random walk in speed with average speed difference sqrt(QnoiseAccel*dt). Since the longitudinal model is also used for lane changes (MOBIL) and decisions at intersections, a deterministic version of the acceleration is also provided.
Inter-driver variations driverfactor with a uniform distribution around 1. Both the desired speed and the desired acceleration are multiplied by driverfactor. Since model parameters are often changed due to user interaction, speed limits, bottlenecks etc and the driverfactor should survive that, it is taken from the vehicle's driverfactor after each model change
speedlimits. These override all user-set desired speeds and also the driverfactor but not the acceleration noise
This is now described at the beginning of models.js. Basically, the steps are
Define the constructor and implement all methods that are also present in the old models (e.g., ACC) in models.js
set the model templates to the new model; if needed, also introduce new gui-sliders in control_gui.js and the .html files
redefine the slider interactions and model update in control_gui.js and road.js
To help in implementing, I defined the global flag testNewModel in control_gui.js. If set to true, a new skeleton "CACC" model will be used which is essentially the IDM. To check if this really works, I set the desired speed for the truck template to 3 m/s (you will see slow trucks if this works as intended). So you need just change all locations where testNewModel is used and you are done for all simulations.
a set of traffic-related objects that can be dragged by the user
from a "depot" to a network link (road) and back.
The main data element of this class is an array trafficObj
of the traffic objects. At present, any array element
traffObj=trafficObj[i] can
represent one of three types of traffic objects:
traffObj.type=='obstacle'traffObj.type=='trafficLight'traffObj.type=='speedLimit'Any object has one of two states at any time specified by the object's
data element isActive:
traffObj.isActive=true: The object is on the road:
traffObj.isActive=false: the object is either in the "depot", or
dragged, or zooming back to the depot
The traffic light and speed limit objects also have values:
traffObj.value="red" or "green" (if traffObj.type==='trafficLight')traffObj.value=limit_kmh (if traffObj.type==='speedLimit')traffObj.value="null" (if traffObj.type==='obstacle')The main unique component of the objects is its traffObj.id.
In case of active traffic light or obstacle objects,
the id of the generated vehicle objects on the road are the same
as that of the traffObj and in the range 50-199 (all special
vehicles have ids < 200). The complete list of traffObj and vehicle
id ranges is
as follows:
veh.id=1: ego vehicleveh.id=10..49: vehicles that are disturbed by clickstraffObj.id=`veh.id=50..99: objects and generated vehicles
of type obstacletraffObj.id=`veh.id=100..149 objects of type trafficLight and
generated vehicles (one per lane) of type obstacletraffObj.id=150..199 speed limits ( no generated virtual
vehicles)veh.id >=200: normal vehicles and fixed (non-depot) obstaclesHelper-class providing some speed and type-dependent color maps to draw the vehicles.
callback (implementation) of the buttons for the different scenarios on the <scenario>.html simulation pages
The underlying car-following model for the longitudinal dynamics providing the accelerations (Intelligent-Driver Model, IDM, or extensions thereof) is time-continuous, so a numerical update scheme is necessary to get the speeds and positions of the vehicles as approximate integrals over the accelerations. For our purposes, it turned out that following ballistic scheme is most efficient in terms of computation load for a given precision. Its pseudo-code for an update of the speeds speed and positions pos over a fixed time interval dt reads
speed(t+dt)=speed(t)+acc(t)*dt,
pos(t+dt)=pos(t)+speed(t)dt+1/2acc(t)*dt^2,
where acc(t) is the acceleration calculated by the car-following model at the (old) time t.
Lane-changing is modelled by the discrete model MOBIL, so no
integration is needed there. In order to reuse the accelerations
needed by MOBIL (Minimizing Obstructions By Intelligent
Lane-changes") for calculating the lane-changing decisions, lane
changing is performed after evaluating all
accelerations. Furthermore, since MOBIL anticipates the future
situation, the actual speed and positional update is performed after
the lane changing. Hence the central update sequence performed for all
road instances of the simulated network is given by
roadInstance.calcAccelerations();
roadInstance.changeLanes();
roadInstance.updateSpeedPositions();
in the main simulation file of the given scenario (ring.js,
onramp.js etc). The main method is either updateRing() (ring
road), or updateU() (the other scenarios).
Notice that the update is in parallel, i.e., updating all accelerations on a given road, then all lanes, all speeds, and all positions sequentially (if there are interdependencies between the road elements of the network, this sequentiality should also be traversed over all road instances which, presently, is not done).
The central update step is prepended by updating the model parameters as a response to user interaction, if vehicles reach special zones such as the uphill region, or if they reach mandatory lane-changing regions before lane closing and offramps.
For closed links (ring road), the central update step is prepended by changing the vehicle population (overall density, truck percentage) as a response to user interaction.
For open links, the central method is appended by applying the boundary conditions ```roadInstance.up
Selected from shared topics, language and repository description—not editorial ratings.
freeCodeCamp /
freeCodeCamp.org's open-source codebase and curriculum. Learn math, programming, and computer science for free.
adobe /
An open source code editor for the web, written in JavaScript, HTML and CSS.
semgrep /
Lightweight static analysis for many languages. Find bug variants with patterns that look like source code.
apitable /
🚀🎉📚 APITable, an API-oriented low-code platform for building collaborative apps and better than all other Airtable open-source alternatives.
gabrielecirulli /
The source code for 2048
firebase /
FirebaseUI is an open-source JavaScript library for Web that provides simple, customizable UI bindings on top of Firebase SDKs to eliminate boilerplate code and promote best practices.