Traffic_Network_Flow_Dynamics: Teaching a Neural Network to Write Traffic's Equations

A small research repo forces an autoencoder's hidden state to obey sparse, human-readable equations, then recovers a whole highway network from ten sensors.

9 min read • View on GitHub • More from wzh96

An aerial view of a multi-level highway interchange drawn in black ink crosshatching. Slender sensor masts stand at intervals along the roads, and from each mast a single fine line rises and curls into small floating pieces of mathematical notation. The illustration shows that a physical road network and its symbolic governing equations can be viewed as the same object seen two ways.
The thesis of the repository in one frame: physical traffic flow and readable mathematics are the same object, viewed two ways.
Key Takeaways

Most traffic machine learning gives you a number. A speed. A flow rate. A forecast for the next five minutes, and no reason to believe it beyond the fact that the test loss was acceptable. This repository gives you something stranger and more useful: a short differential equation you can read, argue with, and check against what you know about how cars move.

The Output Is an Equation, Not a Forecast

The project is called Traffic_Network_Flow_Dynamics, and its README contains exactly one line, the title of the paper it implements: "Discover Physically Analyzable Governing Nonlinearities of Traffic Network Flow Dynamics." That phrase, physically analyzable, is the whole point. The model is not graded on whether it predicts well in isolation. It is graded on whether the thing doing the predicting can be written down.

The form it produces is a SINDy-style system, a set of ordinary differential equations where the right-hand side is a sparse sum of candidate terms. Each latent coordinate moves according to a short combination of constants, powers, and cross terms, most of which are multiplied by coefficients the training pushes toward zero.

dz1/dt =  a1 * z1  +  a2 * z1*z2  +  a3 * z1^2   +  ...
dz2/dt =  b1 * z1  +  b2 * z2     +  b3 * z1*z2  +  ...
...
dzn/dt =  ...

most coefficients a_i, b_i are driven to zero by L1 sparsity,
leaving a short, readable governing system.

This is the trade the repo refuses. Deep sequence models forecast well but explain nothing. Classical equation discovery, plain SINDy or DMD, is readable but rigid, and it needs the full state to work with. The authors want all three at once: flexible, readable, and operating on a slice of the network rather than the whole thing.

Ten Sensors and a Whole Highway

The data comes from a cluster of highway sensors in the Los Angeles area, based on the coordinates in the repository's sensor-location file, which sit around 34.0 to 34.2 degrees north and 118.2 to 118.5 degrees west. The notebooks refer to Station #1 through Station #10. You cannot instrument every lane of a real highway, so you have partial measurements of a coupled dynamical system and a network you would like to explain.

The question the repository answers is narrow and hard: from a tenth of the network, can you discover governing equations for the rest of it? Not just interpolate the missing sensors, but write the dynamics that connect them.

Where a Black Box Meets a Textbook

The architecture has a split personality, and that split is the differentiator. An autoencoder compresses time-delay-embedded sensor data into a small latent vector. On its own, that latent space is just as opaque as any other neural representation. But here the latent space is not left alone. It is constrained to evolve according to a SINDy model, the readable, sparse, textbook side of the system.

The latent vector becomes a translator. It absorbs the messy, high-dimensional measurements on one end and emits clean symbolic structure on the other. The repository ships both a purely linear encoder and a nonlinear one with a selectable activation, and the archived model folders (Model1_Linear, Model2_sigmoid, Model3) show the authors ran that comparison deliberately rather than picking a default.

An extreme close-up of a narrow mechanical gate drawn in black ink crosshatching. A thick tangle of dozens of wires feeds in from the left, and only a handful of wires emerge on the right, each labeled with a small mathematical symbol. The few wires connect to a short equation written on a slip of paper. The image visualizes the latent bottleneck, where many measurements compress into a few interpretable coordinates.
The autoencoder's bottleneck, made physical: many tangled measurements in, a few labeled coordinates out, ending in a short equation.

How the Pipeline Actually Works

The pipeline runs left to right. Each station's series is turned into a time-delay embedding, a window of lagged values stacked into a small matrix. The encoder compresses that window into a latent row, z1 through zn. A SINDy library turns each latent coordinate into a bank of candidate terms (a constant, the coordinate itself, its square, cross products, sines). Sparse coefficients sit on top of those terms, and the surviving ones assemble into the final equation.

The trick that makes partial-sensor discovery possible is a pinning term the code calls z1_loss. The training loop walks through the measured stations and ties the first latent coordinates directly to the corresponding measured columns. Those coordinates are welded to real sensors. The remaining latent slots are left free to represent the hidden, unmeasured dynamics of the network. That is how ten sensors can speak for a whole highway.

The composite loss stacks several pressures on the model at once. Reconstruction keeps the autoencoder honest. A latent derivative match forces dz to follow the SINDy prediction. An observation-space derivative match checks the decoded dynamics against the true derivative. L1 sparsity shrinks the coefficients. The pinning term anchors the measured coordinates. And a multi-step consistency term rolls the latent state forward and compares it against the next delay in the embedding.

The pinning mechanism and the symbolic bottleneck. Ten measured sensors are welded to specific latent coordinates, the rest of the latent space carries hidden dynamics, and the whole thing is forced through a sparse SINDy library into a readable equation.

The Scars of a Working Method

The most human part of this repository is what it left commented out. There are clamp calls on the rollout state and on the consistency loss, both disabled. There is a negative_z penalty the authors wanted, a term that would have pushed latent coordinates to stay nonnegative, presumably because they are read as densities or flows. It is commented out too. These are the traces of a training process that diverged and got talked back from the edge.

The integrator tells the same story. The code keeps a fourth-order Runge-Kutta step directly above the one it actually uses, a plain forward Euler update it calls rk1_step.

def rk1_step(t, A, f, dt):
    k1 = dt * f(t, A)
    A_new = A + k1
    return A_new

# a commented-out RK4 implementation sits directly above this

The swap was likely for stability or memory, and the time step is set to one sample, so the discovered equations are effectively discretized at the data's native resolution. The consistency rollout is capped, and the code says so in a comment that reads like a note to a future self: "Here I am only able to integrate over 3 embedding dimension."

Two loss totals in the same function reveal the training schedule. loss_total includes the L1 sparsity term. loss_refinement omits it. Paired refinement logs in the results folder confirm a two-phase approach: discover sparsely first, then re-fit the surviving coefficients without shrinkage.

How It Compares

Inside the repository, the proposed method runs a bake-off against three baselines at the 5, 10, and 15 minute horizons: DMD, plain SINDy, and a derivative-based variant called Time_Derivative. The DMD baseline gives the comparison a factual anchor. Across ten stations, its RMSE ranges from 26.76 to 67.93, and its MAPE from 6.64 percent to 34.55 percent. Station #8 shows why both metrics matter: the largest RMSE at 67.93 but a moderate MAPE at 21.81 percent, which fits a station whose typical values are simply larger.

MethodInterpretable?Handles nonlinearity?Uses partial sensors?Multi-step?
DMD (baseline)Partially (modes)No (linear)Fit on measured columnsYes, via feedback
SINDy (baseline)YesYesNo, needs full stateLimited
Time_Derivative variantYesYesPartialLimited
Proposed (AE + SINDy)YesYesYes (z1 pinning)Yes (Euler rollout)

It is worth being clear about a different category of tool. Simulators like SUMO, CityFlow, and UXsim take rules and run traffic forward from them. This repository does the opposite: it takes observed traffic and tries to discover the rules. Those are complementary, not competing, and no source establishes any relationship between these projects and this one, so the comparison stops at the category line.

What This Repo Is Not

Set expectations before you clone it. There is no README beyond the paper title, no license, no requirements file, no tests, and no packaging. It is research code, a lab notebook with the lab notebook's rough edges intact.

There is also one correctness question worth flagging. In the consistency loop, the code wraps a tensor with torch.Tensor(z_new), a legacy constructor that can detach a tensor from the autograd graph depending on the PyTorch version. If it does, gradients from the multi-step consistency term would not flow through later steps, quietly weakening the loss whenever the rollout runs more than one step. Using z_new directly, or z_new.clone(), would be the modern pattern. This should be read as a review question, not a confirmed bug, since the behavior depends on the version.

None of that undercuts the idea. The point of a repository like this is to show that the interpretability argument, the one usually aimed at finance and medicine, applies just as well to infrastructure. If you can read the equation, you can audit the model, spot the physics, and defend the forecast. This is a small, honest, unfinished example of how to chase that, ten sensors at a time.