Add unit tests, refactor simulation code, improve Makefile, and add documentation

This commit is contained in:
Ahmed Kallala
2026-05-12 22:16:46 +02:00
committed by salijagic
parent ae1c64af05
commit 5713ad7e19
16 changed files with 2486 additions and 825 deletions
+116 -243
View File
@@ -1,15 +1,18 @@
#include "board.hpp"
#include "constants.hpp"
#include "forces.hpp"
#include "math.h"
#include "pedestrian.hpp"
#include "vector2d.hpp"
#include <fstream>
#include <iostream>
#include <random>
#include <tuple>
#include "social_force.hpp"
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <vector>
#ifndef BENCHMARK
// Benchmarking is disabled by default.
#define BENCHMARK 0
#endif
#ifdef __x86_64__
#include "tsc_x86.h"
#endif
@@ -18,98 +21,25 @@
#include "kperf.h"
#endif
#define SEED 42
#define BOARD_WIDTH 10.0
#define BOARD_LENGTH 50.0
#define BOARD_LENGTH_MINUS_ONE BOARD_LENGTH - 1
#define BOARD_LENGTH_MINUS_ONE_POINT_FIVE BOARD_LENGTH - 1.5
#define WALL_EPS 1e-3
#define BOARD_WIDTH_MINUS_WALL_EPS BOARD_WIDTH - WALL_EPS
#define BOARD_LENGTH_HALF BOARD_LENGTH / 2
#define BOARD_LENGTH_MINUS_TWO BOARD_LENGTH - 2
#define BOARD_WIDTH_MINUS_ZERO_POINT_THREE BOARD_WIDTH - 0.3
#define BOARD_LENGTH_PLUS_THIRTY BOARD_LENGTH + 30
using namespace std;
Pedestrian *init_pedestrians(int n_p) {
Pedestrian *P = new Pedestrian[n_p];
// Platform-specific non-deterministic random number generator (if available)
// random_device rd;
// mt19937 gen(rd()); // Use rd for true randomness
mt19937 gen(SEED); // Use fixed seed for reproducibility
normal_distribution<double> velocity_gen(V0_MEAN, V0_STD_DEV);
uniform_real_distribution<double> x_gen_left(2, BOARD_LENGTH_HALF);
uniform_real_distribution<double> x_gen_right(BOARD_LENGTH_HALF, BOARD_LENGTH_MINUS_TWO);
uniform_real_distribution<double> y_gen(0.3, BOARD_WIDTH_MINUS_ZERO_POINT_THREE);
const int n_p_half = n_p / 2;
for (int i = 0; i < n_p_half; i++) {
double x = x_gen_left(gen);
double y = y_gen(gen);
Vector2d start_pos = Vector2d(x, y);
Vector2d destination = Vector2d(BOARD_LENGTH_PLUS_THIRTY, y);
Vector2d init_e = destination - start_pos;
double init_e_norm = init_e.norm();
Vector2d init_e_unit = init_e / init_e_norm;
double desired_v0;
// Avoid values are too small since they would make the pedestrians walk backwards
do {
desired_v0 = velocity_gen(gen);
} while (desired_v0 <= 0.1);
double v_max = 1.3 * desired_v0;
P[i] = Pedestrian(WHITE, Vector2d(), start_pos, init_e_unit, v_max, desired_v0, destination, Vector2d());
}
for (int i = n_p_half; i < n_p; i++) {
double x = x_gen_right(gen);
double y = y_gen(gen);
Vector2d start_pos = Vector2d(x, y);
Vector2d destination = Vector2d(-30, y);
Vector2d init_e = destination - start_pos;
double init_e_norm = init_e.norm();
Vector2d init_e_unit = init_e / init_e_norm;
double desired_v0;
do {
desired_v0 = velocity_gen(gen);
} while (desired_v0 <= 0.1);
double v_max = 1.3 * desired_v0;
P[i] = Pedestrian(BLACK, Vector2d(), start_pos, init_e_unit, v_max, desired_v0, destination, Vector2d());
}
return P;
}
#define N_OBSTACLES 2
#define WARMUP_ITERS 5
#define NUM_REPS 11
int main(int argc, const char *argv[]) {
// Ensure that arguments are passed
// Check that the correct number of arguments has been passed.
//
// Expected usage:
//
// ./main <number_of_pedestrians> <number_of_iterations> [csv_output_path]
//
// The optional third argument enables CSV dumping for visualization.
if (argc < 3) {
printf("Usage: ./sim <number_of_pedestrians> <number_of_iterations>\n");
printf("Each iteration takes %.2f seconds in the simulation.\n", DT);
printf("Usage: ./main <number_of_pedestrians> <number_of_iterations> [csv_output_path]\n");
printf("Each iteration takes %.2f seconds in the simulation.\n", dt);
return 1;
}
// Parse command-line arguments
// Parse command-line arguments.
int n_p = atoi(argv[1]);
int n_iter = atoi(argv[2]);
@@ -123,167 +53,118 @@ int main(int argc, const char *argv[]) {
return 1;
}
Obstacle obs[] = {};
Board board = Board(BOARD_LENGTH, BOARD_WIDTH, 0, obs);
// Logic for importing/exporting the simulation data
const int dump_interval = 1;
// If provided, dump_path is used to write simulation states to CSV.
// In benchmark mode, this path is intentionally ignored to avoid measuring
// file I/O overhead.
const char *dump_path = (argc >= 4) ? argv[3] : nullptr;
vector<tuple<int, int, double, double, double, double, int>> samples; // t, id, x, y, e.x, e.y, color
if (dump_path) {
samples.reserve((size_t)n_iter / dump_interval * n_p);
}
Pedestrian *pedestrians = init_pedestrians(n_p);
#ifdef __x86_64__
uint64_t start = start_tsc();
#endif
#if BENCHMARK
#ifdef __aarch64__
// Initialize ARM performance counters.
kperf_init();
struct performance_counters startperf, endperf;
startperf = kperf_get_counters();
#endif
for (int t = 0; t < n_iter; t++) {
// Warmup runs are not measured.
// Each run gets a fresh initialized state because run_simulation mutates the
// pedestrians and board state.
for (int i = 0; i < WARMUP_ITERS; i++) {
Pedestrian *P = init_pedestrians(n_p);
Board board = init_board_without_obstacles();
// Pass 1: Conmpute all the forces given the current state
for (int i = 0; i < n_p; i++) {
run_simulation(P, board, n_p, n_iter, nullptr);
Pedestrian &p = pedestrians[i];
p.f_i.reset();
// # 4 ADDs, 4 MULTs
//
// $\vec{F}_\alpha(\vec{v}_\alpha, v^0_\alpha \vec{e}_\alpha) = \frac{1}{\tau_\alpha}(v^0_\alpha \vec{e}_\alpha - \vec{v}_\alpha)$
//
add_acceleration_term(&p);
// # (n_p - 1) * (14 ADDs, 23 MULTs, 1 DIV, 4 SQRTs, 1 EXP)
//
// $\sum_{\beta} \vec{F}_{\alpha\beta}(\vec{e}_{\alpha}, \vec{r}_{\alpha} - \vec{r}_{\beta})$
//
add_repulsive_effects_from_pedestrians(pedestrians, &p, n_p);
// # board.n_obstacles * (12 ADDs, 18 MULTs, 1 DIV, 2 SQRTs, 1 EXP)
//
// $\sum_{B} \vec{F}_{\alpha B}(\vec{e}_{\alpha}, \vec{r}_{\alpha} - \vec{r}_{B})$
//
add_repulsive_effects_from_borders(board, &p);
}
// Pass 2: Integrate the forces and update the current state
for (int i = 0; i < n_p; i++) {
Pedestrian &p = pedestrians[i];
// # 2 ADDs
//
// $\frac{d\vec{w_\alpha}}{dt} = \vec{F}_{\alpha}(t)$
//
//
p.w = p.w + p.f_i;
// # 1 ADD, 2 MULTs, 1 SQRT
double w_norm = p.w.norm();
p.curr_vel = p.w;
// # Assumption for calculating W(n): The "if" statement always evaluates to true.
// # This is not true in practice, but we assume the worst-case scenario for the flop count calculation.
if (w_norm > p.v_max) {
// # 2 MULTs, 1 DIV
p.curr_vel = p.curr_vel * (p.v_max / w_norm);
}
// # 2 ADDs, 2 MULTs
//
// $\vec{r}_i^{t+1} = \vec{r}^t_i + v^t_idt$
//
p.curr_pos = p.curr_pos + p.curr_vel * DT;
// When a pedestrian reaches the end of the hallway we simply "teleport" the person back to the beginning.
// This way, we have a constant flow of pedestrians, and it is easier to see lanes forming.
if (p.color == WHITE && p.curr_pos.x > BOARD_LENGTH_MINUS_ONE_POINT_FIVE) {
// keep y, reset x
p.curr_pos.x = 1.0;
p.destination.y = p.curr_pos.y;
p.w = Vector2d(p.desired_v0, 0);
p.curr_vel = p.w;
}
if (p.color == BLACK && p.curr_pos.x < 1.5) {
p.curr_pos.x = BOARD_LENGTH_MINUS_ONE;
p.destination.y = p.curr_pos.y;
p.w = Vector2d(-p.desired_v0, 0);
p.curr_vel = p.w;
}
if (p.curr_pos.y <= 0.0) {
p.curr_pos.y = WALL_EPS;
if (p.curr_vel.y < 0)
p.curr_vel.y = 0;
if (p.w.y < 0)
p.w.y = 0;
}
if (p.curr_pos.y >= BOARD_WIDTH) {
p.curr_pos.y = BOARD_WIDTH_MINUS_WALL_EPS;
if (p.curr_vel.y > 0)
p.curr_vel.y = 0;
if (p.w.y > 0)
p.w.y = 0;
}
// # 2 ADDs
Vector2d e = p.destination - p.curr_pos;
// # 1 ADD, 2 MULTs, 1 DIV, 1 SQRT
double e_norm_inv = 1.0 / e.norm();
// # 2 MULTs
p.e = e * e_norm_inv;
// # 1 ADD, 3 MULTs, 1 SQRT
double s_b = p.curr_vel.norm() * DELTA_T;
// # 2 MULTs
p.s_b_e_b = p.e * s_b;
// # 1 MULT
p.s_b_sq = s_b * s_b;
// Save the data for visualization
if (dump_path && (t % dump_interval == 0)) {
samples.emplace_back(t, i, p.curr_pos.x, p.curr_pos.y, p.e.x, p.e.y, p.color);
}
}
delete[] P;
}
// Store the cycle count of each measured repetition.
// The median is then used as the final timing result.
std::vector<long double> cycles_v;
cycles_v.reserve(NUM_REPS);
for (int i = 0; i < NUM_REPS; i++) {
Pedestrian *P = init_pedestrians(n_p);
Board board = init_board_without_obstacles();
#ifdef __x86_64__
long double T = stop_tsc(start);
myInt64 start = start_tsc();
#endif
#ifdef __aarch64__
endperf = kperf_get_counters();
long double T = endperf.cycles - startperf.cycles;
startperf = kperf_get_counters();
#endif
long long add_count_per_iter = n_p * (4 + 14 * (n_p - 1) + 12 * board.n_obstacles) + n_p * 9;
long long mult_count_per_iter = n_p * (4 + 23 * (n_p - 1) + 18 * board.n_obstacles) + n_p * 16;
long long div_count_per_iter = n_p * (n_p - 1 + board.n_obstacles) + n_p * 2;
long long sqrt_count_per_iter = n_p * (4 * (n_p - 1) + 2 * board.n_obstacles) + n_p * 3;
long long exp_count_per_iter = n_p * (n_p - 1 + board.n_obstacles);
// Disable CSV dumping during benchmarking to avoid measuring file I/O
// overhead. Initialization is also excluded from the measured region.
run_simulation(P, board, n_p, n_iter, nullptr);
long double W_per_iter = add_count_per_iter * COST_ADD + mult_count_per_iter * COST_MULT + div_count_per_iter * COST_DIV + sqrt_count_per_iter * COST_SQRT + exp_count_per_iter * COST_EXP;
long long Q_per_iter = sizeof(Pedestrian) * n_p + sizeof(Obstacle) * board.n_obstacles; // TODO: Refine this
#ifdef __x86_64__
long double cycles = stop_tsc(start);
#endif
#ifdef __aarch64__
endperf = kperf_get_counters();
long double cycles = endperf.cycles - startperf.cycles;
#endif
delete[] P;
cycles_v.push_back(cycles);
}
// Use the median cycle count to reduce the effect of noisy measurements.
std::sort(cycles_v.begin(), cycles_v.end());
long double T = cycles_v[NUM_REPS / 2];
#else
// Normal execution mode. If dump_path is provided, the simulation writes a CSV
// file that can later be used to generate a video of the simulation.
Pedestrian *P = init_pedestrians(n_p);
Board board = init_board_without_obstacles();
run_simulation(P, board, n_p, n_iter, dump_path);
delete[] P;
#endif
#if BENCHMARK
// Flop-count per simulation iteration.
//
// The total work W(n) is estimated from the number of additions,
// multiplications, divisions, square roots, and exponentials performed by the
// simulation kernels.
long long add_count_per_iter = n_p * (4 + (n_p - 1) * 14 + N_OBSTACLES * 12) + n_p * 7;
long long mult_count_per_iter = n_p * (4 + (n_p - 1) * 23 + N_OBSTACLES * 18) + n_p * 16;
long long div_count_per_iter = n_p * ((n_p - 1) * 1 + N_OBSTACLES * 1) + n_p * 2;
long long sqrt_count_per_iter = n_p * ((n_p - 1) * 4 + N_OBSTACLES * 2) + n_p * 3;
long long exp_count_per_iter = n_p * ((n_p - 1) * 1 + N_OBSTACLES * 1);
long double W_per_iter = add_count_per_iter * cost_add + mult_count_per_iter * cost_mult + div_count_per_iter * cost_div + sqrt_count_per_iter * cost_sqrt + exp_count_per_iter * cost_exp;
// Estimated memory traffic per iteration.
// TODO: refine this model to account for actual memory accesses, cache reuse,
// and the full interaction loop.
long long Q_per_iter = sizeof(Pedestrian) * n_p + sizeof(Obstacle) * N_OBSTACLES;
// Operational intensity:
//
// I(n) = W(n) / Q(n)
//
// where W is estimated work in flops and Q is estimated memory traffic in
// bytes.
long double I = W_per_iter / Q_per_iter;
// Total estimated work over all iterations.
long double W = W_per_iter * n_iter;
// Performance in estimated flops per cycle.
long double P = W / T;
printf("W(n) per iteration: %.2Lf flops\n", W_per_iter);
@@ -293,15 +174,7 @@ int main(int argc, const char *argv[]) {
printf("T(n): %.2Lf cycles\n", T);
printf("P(n): %.2Lf flops/cycle\n", P);
// Export the data to a .csv file
if (dump_path) {
ofstream out(dump_path);
out << "time,id,x,y,p.e.x,p.e.y,color\n";
for (auto &[t, id, x, y, e_x, e_y, c] : samples) {
out << t << ',' << id << ',' << x << ',' << y << ',' << e_x << ',' << e_y << ',' << c << '\n';
}
}
#endif
delete[] pedestrians;
return 0;
}
}