From 5b4a191d1cf310a3d7a99351e716a1a60004be69 Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Wed, 11 Nov 2026 09:32:30 +0300 Subject: publish --- src/bez7.c | 283 +++++++++++++++++++ src/cma-es.c | 854 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/cma-es.h | 126 +++++++++ src/main.c | 593 +++++++++++++++++++++++++++++++++++++++ src/retiming.c | 427 +++++++++++++++++++++++++++++ src/retiming.h | 102 +++++++ 6 files changed, 2385 insertions(+) create mode 100644 src/bez7.c create mode 100644 src/cma-es.c create mode 100644 src/cma-es.h create mode 100644 src/main.c create mode 100644 src/retiming.c create mode 100644 src/retiming.h (limited to 'src') diff --git a/src/bez7.c b/src/bez7.c new file mode 100644 index 0000000..d63014c --- /dev/null +++ b/src/bez7.c @@ -0,0 +1,283 @@ +#include +#include +#include +#include +#include +#include + +typedef Vector2 bezier7[8]; + +struct input { + Vector2 r_beg; + Vector2 r_end; + Vector2 v_beg; + Vector2 v_end; + float v_max; + float a_max; + float j_max; +}; + +#define RGBA(HEX) (Color) { \ + (HEX) >> 3*8 & 0xFF, \ + (HEX) >> 2*8 & 0xFF, \ + (HEX) >> 1*8 & 0xFF, \ + (HEX) >> 0*8 & 0xFF, \ + } + +// #define LABEL_WIDTH 140 +#define LABEL_WIDTH 300 +#define SLIDER_WIDTH 40 +#define ITEM_WIDTH (LABEL_WIDTH + SLIDER_WIDTH) +#define ITEM_HEIGHT 15 +#define ITEM_MARGIN 5 +#define PANEL_WIDTH (ITEM_WIDTH + 2*ITEM_MARGIN) +#define PANEL_HEIGHT(N) (RAYGUI_WINDOWBOX_STATUSBAR_HEIGHT + (N)*(ITEM_HEIGHT + ITEM_MARGIN) + ITEM_MARGIN) + +#ifdef DARK +#define BACKGROUND RGBA (0x000000FF) +#else +#define BACKGROUND RGBA (0xFFFFFFFF) +#endif + +#define ARROW_THICKNESS 2.5 +#define ARROW_LENGTH 15 +#define ARROW_ANGLE 10 + +#define CONTROL_POINT_RADIUS 5 +#define CONTROL_POINT_RADIUS_FOCUSED 10 + + +void +draw_arrow (Vector2 beg, Vector2 end, float thick, Color c) +{ + Vector2 off = Vector2Scale (Vector2Normalize (Vector2Subtract (end, beg)), + ARROW_LENGTH); + Vector2 ahl = Vector2Add (end, Vector2Rotate (off, +ARROW_ANGLE)); + Vector2 ahr = Vector2Add (end, Vector2Rotate (off, -ARROW_ANGLE)); + + DrawLineEx (beg, end, thick, c); + DrawLineEx (end, ahl, thick, c); + DrawLineEx (end, ahr, thick, c); + + DrawCircleV (beg, thick/2., c); + DrawCircleV (end, thick/2., c); + DrawCircleV (ahl, thick/2., c); + DrawCircleV (ahr, thick/2., c); +} + +Vector2 +sample_bezier7 (const bezier7 pts, float t) +{ + float u = 1.0f - t; + + float t2 = t * t; + float t3 = t2 * t; + float t4 = t3 * t; + float t5 = t4 * t; + float t6 = t5 * t; + float t7 = t6 * t; + + /* Precompute powers of u (1 - t) */ + float u2 = u * u; + float u3 = u2 * u; + float u4 = u3 * u; + float u5 = u4 * u; + float u6 = u5 * u; + float u7 = u6 * u; + + /* Bernstein basis polynomials for degree 7 */ + float b0 = u7; + float b1 = 7.0f * u6 * t; + float b2 = 21.0f * u5 * t2; + float b3 = 35.0f * u4 * t3; + float b4 = 35.0f * u3 * t4; + float b5 = 21.0f * u2 * t5; + float b6 = 7.0f * u * t6; + float b7 = t7; + + Vector2 result; + + /* Calculate final x and y by blending control points with basis weights */ + result.x = (b0 * pts[0].x) + (b1 * pts[1].x) + (b2 * pts[2].x) + (b3 * pts[3].x) + + (b4 * pts[4].x) + (b5 * pts[5].x) + (b6 * pts[6].x) + (b7 * pts[7].x); + + result.y = (b0 * pts[0].y) + (b1 * pts[1].y) + (b2 * pts[2].y) + (b3 * pts[3].y) + + (b4 * pts[4].y) + (b5 * pts[5].y) + (b6 * pts[6].y) + (b7 * pts[7].y); + + return result; +} + +void +draw_bezier7 (bezier7 cp) +{ + char text[] = "P0"; + DrawLineStrip (cp, 8, BLUE); + for (int i = 0; i < 8; ++i) { + DrawCircleLinesV (cp[i], 4, BLUE); + text[1] = '0' + i; + DrawText (text, cp[i].x - 5, cp[i].y + 7, 14, BLACK); + } + + for (float t = 0; t <= 1; t += 0.01) { + DrawCircleV (sample_bezier7 (cp, t), 2, BLACK); + } +} + +int +main (int argc, char *argv[]) +{ + srand (time (NULL)); + + SetConfigFlags (FLAG_MSAA_4X_HINT); + SetConfigFlags (FLAG_WINDOW_RESIZABLE); + InitWindow (800, 450, "GA"); + SetTargetFPS (60); + + Camera2D camera = { + .zoom = 1.0f, + }; + + Vector2 screen = { + .x = GetScreenWidth (), + .y = GetScreenHeight (), + }; + + struct input in = { + .r_beg = { 100, 100 }, + // .r_end = { 100, 100 }, + .r_end = { 300, 300 }, + .v_beg = { 100, 10 }, + .v_end = { 100, 10 }, + .v_max = 250, + .a_max = 500, + .j_max = 16, + }; + + bezier7 cp; + + float arrow_thickness = ARROW_THICKNESS; + float spline_thickness = ARROW_THICKNESS; + bool move_r_beg = false; + bool move_r_end = false; + bool move_v_beg = false; + bool move_v_end = false; + bool recompute = true; + bool show_fps = true; + bool show_menu = true; + bool show_graph = true; + bool draw_cp = true; + bool animate_sample_offset = false; + float animation_speed = 20; + int panel_item = 0; + bool resizing_graph = false; + int graph_height = screen.y/3; + float T = 10; + while (!WindowShouldClose ()) { + screen = (Vector2) { + .x = GetScreenWidth (), + .y = GetScreenHeight (), + }; + float t = GetTime (); + float dt = GetFrameTime (); + + if (IsMouseButtonDown (MOUSE_BUTTON_RIGHT)) { + Vector2 delta = GetMouseDelta (); + delta = Vector2Scale (delta, -1.0f/camera.zoom); + camera.target = Vector2Add (camera.target, delta); + } + + if (IsKeyPressed (KEY_F)) show_fps = !show_fps; + + if (IsKeyDown (KEY_LEFT )) T -= .1; + if (IsKeyDown (KEY_RIGHT)) T += .1; + + + if (1 || recompute) { + // chromosome_to_control_points (cp, in, ch); + cp[0] = in.r_beg; + cp[1] = Vector2Add (in.r_beg, Vector2Scale (in.v_beg, +1*T/7)); + cp[2] = Vector2Add (in.r_beg, Vector2Scale (in.v_beg, +2*T/7)); + cp[3] = Vector2Add (in.r_beg, Vector2Scale (in.v_beg, +3*T/7)); + cp[4] = Vector2Add (in.r_end, Vector2Scale (in.v_end, -3*T/7)); + cp[5] = Vector2Add (in.r_end, Vector2Scale (in.v_end, -2*T/7)); + cp[6] = Vector2Add (in.r_end, Vector2Scale (in.v_end, -1*T/7)); + cp[7] = in.r_end; + recompute = false; + } + + float wheel = GetMouseWheelMove(); + if (wheel != 0) { + Vector2 offset = GetMousePosition (); + camera.target = GetScreenToWorld2D (offset, camera); + camera.offset = offset; + camera.zoom = Clamp (expf (logf (camera.zoom) + .2*wheel), .125, 64); + } + + Vector2 mouse_hud = GetMousePosition (); + Vector2 mouse = GetScreenToWorld2D (mouse_hud, camera); + + BeginDrawing (); + ClearBackground (BACKGROUND); + BeginMode2D (camera); + + if (CheckCollisionPointCircle (mouse, in.r_beg, 10)) { + DrawCircleLinesV (in.r_beg, 10, BLUE); + if (!move_v_beg && IsMouseButtonDown (MOUSE_BUTTON_LEFT)) + move_r_beg = true; + } else if (CheckCollisionPointCircle (mouse, in.r_end, 10)) { + DrawCircleLinesV (in.r_end, 10, BLUE); + if (!move_v_end && IsMouseButtonDown (MOUSE_BUTTON_LEFT)) + move_r_end = true; + } else if (CheckCollisionPointCircle (mouse, Vector2Add (in.r_beg, in.v_beg), 10)) { + DrawCircleLinesV (Vector2Add (in.r_beg, in.v_beg), 10, BLUE); + if (!move_r_beg && IsMouseButtonDown (MOUSE_BUTTON_LEFT)) + move_v_beg = true; + } else if (CheckCollisionPointCircle (mouse, Vector2Add (in.r_end, in.v_end), 10)) { + DrawCircleLinesV (Vector2Add (in.r_end, in.v_end), 10, BLUE); + if (!move_r_end && IsMouseButtonDown (MOUSE_BUTTON_LEFT)) + move_v_end = true; + } + + if (move_r_beg) { + in.r_beg = mouse; + if (IsMouseButtonReleased (MOUSE_BUTTON_LEFT)) + move_r_beg = false; + } + if (move_r_end) { + in.r_end = mouse; + if (IsMouseButtonReleased (MOUSE_BUTTON_LEFT)) + move_r_end = false; + } + if (move_v_beg) { + in.v_beg = Vector2Subtract (mouse, in.r_beg); + if (IsMouseButtonReleased (MOUSE_BUTTON_LEFT)) + move_v_beg = false; + } + if (move_v_end) { + in.v_end = Vector2Subtract (mouse, in.r_end); + if (IsMouseButtonReleased (MOUSE_BUTTON_LEFT)) + move_v_end = false; + } + + draw_bezier7 (cp); + draw_arrow (in.r_beg, Vector2Add (in.r_beg, in.v_beg), arrow_thickness, GREEN); + draw_arrow (in.r_end, Vector2Add (in.r_end, in.v_end), arrow_thickness, RED); + + EndMode2D (); + + if (move_r_beg || + move_r_end || + move_v_beg || + move_v_end) { + recompute = true; + } + + if (show_fps) + DrawFPS (screen.x - 75, 0); + EndDrawing (); + } + + CloseWindow (); + + return EXIT_SUCCESS; +} diff --git a/src/cma-es.c b/src/cma-es.c new file mode 100644 index 0000000..bf8dcad --- /dev/null +++ b/src/cma-es.c @@ -0,0 +1,854 @@ +#include +#include +#include +#include +#include + +#include "retiming.h" +#include "cma-es.h" + +#ifndef EPS +#define EPS 1e-6f +#endif + +#ifndef CMA_PI +#define CMA_PI 3.14159265358979323846 +#endif + +/* ----------------------------- + Basic vector helpers + ----------------------------- */ + +static inline Vector2 +v2_add (Vector2 a, Vector2 b) +{ + Vector2 r = { a.x + b.x, a.y + b.y }; + return r; +} + +static inline Vector2 +v2_sub (Vector2 a, Vector2 b) +{ + Vector2 r = { a.x - b.x, a.y - b.y }; + return r; +} + +static inline Vector2 +v2_scale (Vector2 a, float s) +{ + Vector2 r = { a.x * s, a.y * s }; + return r; +} + +static inline float +v2_dot (Vector2 a, Vector2 b) +{ + return a.x*b.x + a.y*b.y; +} + +static inline float +v2_len (Vector2 a) +{ + return sqrtf (fmaxf (0.0f, v2_dot (a, a))); +} + +static inline Vector2 +v2_perp_left (Vector2 a) +{ + Vector2 r = { -a.y, +a.x }; + return r; +} + +static inline Vector2 +v2_normalize_safe (Vector2 a, Vector2 fallback) +{ + float la = v2_len (a); + if (la > EPS) + return v2_scale (a, 1.0f / la); + + float lf = v2_len (fallback); + if (lf > EPS) + return v2_scale (fallback, 1.0f / lf); + + { + Vector2 ex = { 1.0f, 0.0f }; + return ex; + } +} + +// void +// chromosome_to_control_points (bezier5 cp, struct input in, struct chromosome ch) +// { +// Vector2 chord = v2_sub (in.r_end, in.r_beg); +// Vector2 e_ref = v2_normalize_safe (chord, (Vector2){ 1.0f, 0.0f }); +// +// Vector2 e_beg = v2_normalize_safe (in.v_beg, e_ref); +// Vector2 e_end = v2_normalize_safe (in.v_end, e_ref); +// +// Vector2 n_beg = v2_perp_left (e_beg); +// Vector2 n_end = v2_perp_left (e_end); +// +// cp[0] = in.r_beg; +// cp[1] = v2_add (in.r_beg, v2_scale (e_beg, +ch.rho * ch.tau_1)); +// cp[2] = v2_add (in.r_beg, +// v2_scale (v2_add (v2_scale (e_beg, ch.alp_2), +// v2_scale (n_beg, ch.bet_2)), +// +ch.rho)); +// cp[3] = v2_add (in.r_end, +// v2_scale (v2_add (v2_scale (e_end, ch.alp_3), +// v2_scale (n_end, ch.bet_3)), +// -ch.rho)); +// cp[4] = v2_add (in.r_end, v2_scale (e_end, -ch.rho * ch.tau_4)); +// cp[5] = in.r_end; +// } + +/* ----------------------------- + CMA-side chromosome transform + Search in latent z \in R^7, + decode to valid chromosome. + ----------------------------- */ + +static inline struct chromosome_cma_config +chromosome_cma_default_config (void) +{ + struct chromosome_cma_config c; + c.rho_min_rel = 0.05f; + c.rho_max_rel = 5.00f; + c.tau_min = 0.05f; + c.alp_limit = 5.00f; + c.bet_limit = 5.00f; + return c; +} + +static inline float +clampf (float x, float lo, float hi) +{ + return x < lo ? lo : (x > hi ? hi : x); +} + +static inline float +sigmoidf (float x) +{ + if (x >= 0.0f) { + float e = expf (-x); + return 1.0f / (1.0f + e); + } else { + float e = expf (x); + return e / (1.0f + e); + } +} + +static inline float +logitf (float p) +{ + p = clampf (p, 1e-6f, 1.0f - 1e-6f); + return logf (p / (1.0f - p)); +} + +static inline float +atanh_safe (float x) +{ + x = clampf (x, -0.999999f, 0.999999f); + return 0.5f * logf ((1.0f + x) / (1.0f - x)); +} + +static inline float +map01 (float s, float lo, float hi) +{ + return lo + (hi - lo) * s; +} + +void +cma_decode_chromosome (struct chromosome *ch, + const float z[CMA_DIM], + const struct input *in, + const struct chromosome_cma_config *cfg) +{ + float D = v2_len (v2_sub (in->r_end, in->r_beg)); + if (D < EPS) D = fmaxf (v2_len (in->v_beg), v2_len (in->v_end)); + + { + float s_rho = sigmoidf (z[0]); + ch->rho = D * map01 (s_rho, cfg->rho_min_rel, cfg->rho_max_rel); + } + + { + float s1 = sigmoidf (z[1]); + float tau1_max = 1.0f - cfg->tau_min; + tau1_max = fmaxf (tau1_max, cfg->tau_min + 1e-3f); + ch->tau_1 = map01 (s1, cfg->tau_min, tau1_max); + + float s6 = sigmoidf (z[6]); + float tau4_max = 1.0f - cfg->tau_min; + tau1_max = fmaxf (tau4_max, cfg->tau_min + 1e-3f); + ch->tau_4 = map01 (s6, cfg->tau_min, tau4_max); + } + + ch->alp_2 = cfg->alp_limit * tanhf (z[2]); + ch->bet_2 = cfg->bet_limit * tanhf (z[3]); + ch->alp_3 = cfg->alp_limit * tanhf (z[4]); + ch->bet_3 = cfg->bet_limit * tanhf (z[5]); +} + +void +cma_encode_chromosome (float z[CMA_DIM], + const struct chromosome *ch_in, + const struct input *in, + const struct chromosome_cma_config *cfg) +{ + struct chromosome ch = *ch_in; + float D = v2_len (v2_sub (in->r_end, in->r_beg)); + if (D < EPS) D = fmaxf (v2_len (in->v_beg), v2_len (in->v_end)); + + { + float rho_rel = ch.rho / D; + float s = (rho_rel - cfg->rho_min_rel) / + fmaxf (cfg->rho_max_rel - cfg->rho_min_rel, EPS); + z[0] = logitf (s); + } + + { + float tau1_max = 1.0f - cfg->tau_min; + tau1_max = fmaxf (tau1_max, cfg->tau_min + 1e-3f); + ch.tau_1 = clampf (ch.tau_1, cfg->tau_min, tau1_max); + + { + float s1 = (ch.tau_1 - cfg->tau_min) / + fmaxf (tau1_max - cfg->tau_min, EPS); + z[1] = logitf (s1); + } + + float tau4_max = 1.0f - cfg->tau_min; + tau4_max = fmaxf (tau1_max, cfg->tau_min + 1e-3f); + ch.tau_4 = clampf (ch.tau_4, cfg->tau_min, tau4_max); + + { + float s6 = (ch.tau_4 - cfg->tau_min) / + fmaxf (tau4_max - cfg->tau_min, EPS); + z[6] = logitf (s6); + } + } + + z[2] = atanh_safe (clampf (ch.alp_2 / fmaxf (cfg->alp_limit, EPS), -0.999999f, 0.999999f)); + z[3] = atanh_safe (clampf (ch.bet_2 / fmaxf (cfg->bet_limit, EPS), -0.999999f, 0.999999f)); + z[4] = atanh_safe (clampf (ch.alp_3 / fmaxf (cfg->alp_limit, EPS), -0.999999f, 0.999999f)); + z[5] = atanh_safe (clampf (ch.bet_3 / fmaxf (cfg->bet_limit, EPS), -0.999999f, 0.999999f)); +} + +static inline uint64_t +cma_rng_next_u64 (struct cma_rng *r) +{ + uint64_t x = r->state; + x ^= x >> 12; + x ^= x << 25; + x ^= x >> 27; + r->state = x; + return x * UINT64_C(2685821657736338717); +} + +static inline void +cma_rng_seed (struct cma_rng *r, uint64_t seed) +{ + if (seed == 0) seed = UINT64_C(0x9e3779b97f4a7c15); + r->state = seed; + if (r->state == 0) r->state = UINT64_C(0x123456789abcdef); + r->has_spare = 0; + r->spare = 0.0f; +} + +static inline float +cma_rng_uniform01 (struct cma_rng *r) +{ + uint64_t x = cma_rng_next_u64 (r); + return (float)((x >> 11) * (1.0 / 9007199254740992.0)); +} + +static inline float +cma_rng_normal (struct cma_rng *r) +{ + if (r->has_spare) { + r->has_spare = 0; + return r->spare; + } + + for (;;) { + float u1 = cma_rng_uniform01 (r); + float u2 = cma_rng_uniform01 (r); + + if (u1 > 1e-12f) { + float mag = sqrtf (-2.0f * logf (u1)); + float ang = 2.0f * (float)CMA_PI * u2; + + r->spare = mag * sinf (ang); + r->has_spare = 1; + return mag * cosf (ang); + } + } +} + +#define MIDX(i,j,n) ((i)*(n) + (j)) + +static void +mat_identity (float *A, int n) +{ + memset (A, 0, (size_t)n * (size_t)n * sizeof (*A)); + for (int i = 0; i < n; ++i) + A[MIDX(i,i,n)] = 1.0f; +} + +static void +mat_copy (float *dst, const float *src, int n) +{ + memcpy (dst, src, (size_t)n * (size_t)n * sizeof (*dst)); +} + +static void +vec_copy (float *dst, const float *src, int n) +{ + memcpy (dst, src, (size_t)n * sizeof (*dst)); +} + +static void +vec_set_zero (float *x, int n) +{ + memset (x, 0, (size_t)n * sizeof (*x)); +} + +static float +vec_dot (const float *a, const float *b, int n) +{ + float s = 0.0f; + for (int i = 0; i < n; ++i) + s += a[i] * b[i]; + return s; +} + +static float +vec_norm (const float *a, int n) +{ + return sqrtf (fmaxf (0.0f, vec_dot (a, a, n))); +} + +static void +mat_vec_mul (float *y, const float *A, const float *x, int n) +{ + for (int i = 0; i < n; ++i) { + float s = 0.0f; + for (int j = 0; j < n; ++j) + s += A[MIDX(i,j,n)] * x[j]; + y[i] = s; + } +} + +static void +symmetrize (float *A, int n) +{ + for (int i = 0; i < n; ++i) { + for (int j = i + 1; j < n; ++j) { + float s = 0.5f * (A[MIDX(i,j,n)] + A[MIDX(j,i,n)]); + A[MIDX(i,j,n)] = s; + A[MIDX(j,i,n)] = s; + } + } +} + +/* Jacobi eigendecomposition for symmetric A. + On output: + - eval[i] are eigenvalues + - V(:,i) is eigenvector i +*/ +static void +jacobi_eigen_symmetric (float *A, float *V, float *eval, int n) +{ + mat_identity (V, n); + + for (int sweep = 0; sweep < 64 * n * n; ++sweep) { + int p = 0, q = 1; + float max_off = fabsf (A[MIDX(0,1,n)]); + + for (int i = 0; i < n; ++i) { + for (int j = i + 1; j < n; ++j) { + float aij = fabsf (A[MIDX(i,j,n)]); + if (aij > max_off) { + max_off = aij; + p = i; + q = j; + } + } + } + + if (max_off < 1e-12f) + break; + + { + float app = A[MIDX(p,p,n)]; + float aqq = A[MIDX(q,q,n)]; + float apq = A[MIDX(p,q,n)]; + + float phi = 0.5f * atan2f (2.0f * apq, aqq - app); + float c = cosf (phi); + float s = sinf (phi); + + for (int k = 0; k < n; ++k) { + float aik = A[MIDX(p,k,n)]; + float aqk = A[MIDX(q,k,n)]; + A[MIDX(p,k,n)] = c*aik - s*aqk; + A[MIDX(q,k,n)] = s*aik + c*aqk; + } + + for (int k = 0; k < n; ++k) { + float akp = A[MIDX(k,p,n)]; + float akq = A[MIDX(k,q,n)]; + A[MIDX(k,p,n)] = c*akp - s*akq; + A[MIDX(k,q,n)] = s*akp + c*akq; + } + + for (int k = 0; k < n; ++k) { + float vkp = V[MIDX(k,p,n)]; + float vkq = V[MIDX(k,q,n)]; + V[MIDX(k,p,n)] = c*vkp - s*vkq; + V[MIDX(k,q,n)] = s*vkp + c*vkq; + } + } + } + + for (int i = 0; i < n; ++i) + eval[i] = A[MIDX(i,i,n)]; + + /* sort ascending eigenvalues */ + for (int i = 0; i < n - 1; ++i) { + int best = i; + for (int j = i + 1; j < n; ++j) + if (eval[j] < eval[best]) best = j; + + if (best != i) { + float tmp = eval[i]; + eval[i] = eval[best]; + eval[best] = tmp; + + for (int k = 0; k < n; ++k) { + float tv = V[MIDX(k,i,n)]; + V[MIDX(k,i,n)] = V[MIDX(k,best,n)]; + V[MIDX(k,best,n)] = tv; + } + } + } +} + +/* ----------------------------- + CMA-ES core + ----------------------------- */ + +int +cmaes_default_lambda (int n) +{ + return 4 + (int)floorf (3.0f * logf ((float)n)); +} + +float +cmaes_expected_norm (int n) +{ + float nf = (float)n; + return sqrtf (nf) * (1.0f - 1.0f/(4.0f*nf) + 1.0f/(21.0f*nf*nf)); +} + +int +cmaes_init (struct cmaes *es, + int n, + const float *mean0, + float sigma0, + int lambda, + uint64_t seed) +{ + memset (es, 0, sizeof (*es)); + + if (n <= 0) return 0; + if (sigma0 <= 0.0f) return 0; + + es->n = n; + es->lambda = (lambda > 0) ? lambda : cmaes_default_lambda (n); + es->mu = es->lambda / 2; + es->sigma = sigma0; + es->generation = 0; + es->evaluations = 0; + es->chi_n = cmaes_expected_norm (n); + + es->weights = (float*)calloc ((size_t)es->mu, sizeof (float)); + es->xmean = (float*)calloc ((size_t)n, sizeof (float)); + es->xold = (float*)calloc ((size_t)n, sizeof (float)); + es->pc = (float*)calloc ((size_t)n, sizeof (float)); + es->ps = (float*)calloc ((size_t)n, sizeof (float)); + es->C = (float*)calloc ((size_t)n*(size_t)n, sizeof (float)); + es->B = (float*)calloc ((size_t)n*(size_t)n, sizeof (float)); + es->D = (float*)calloc ((size_t)n, sizeof (float)); + es->BD = (float*)calloc ((size_t)n*(size_t)n, sizeof (float)); + es->invsqrtC= (float*)calloc ((size_t)n*(size_t)n, sizeof (float)); + es->ary = (float*)calloc ((size_t)es->lambda*(size_t)n, sizeof (float)); + es->arx = (float*)calloc ((size_t)es->lambda*(size_t)n, sizeof (float)); + es->fitness = (float*)calloc ((size_t)es->lambda, sizeof (float)); + es->index = (int*)calloc ((size_t)es->lambda, sizeof (int)); + + if (!es->weights || !es->xmean || !es->xold || !es->pc || !es->ps || + !es->C || !es->B || !es->D || !es->BD || !es->invsqrtC || + !es->ary || !es->arx || !es->fitness || !es->index) { + return 0; + } + + vec_copy (es->xmean, mean0, n); + vec_set_zero (es->xold, n); + vec_set_zero (es->pc, n); + vec_set_zero (es->ps, n); + + { + float wsum = 0.0f; + for (int i = 0; i < es->mu; ++i) { + es->weights[i] = logf ((float)es->mu + 0.5f) - logf ((float)(i + 1)); + wsum += es->weights[i]; + } + + es->mueff = 0.0f; + for (int i = 0; i < es->mu; ++i) { + es->weights[i] /= wsum; + es->mueff += es->weights[i] * es->weights[i]; + } + es->mueff = 1.0f / fmaxf (es->mueff, EPS); + } + + { + float nf = (float)n; + es->cc = (4.0f + es->mueff / nf) / (nf + 4.0f + 2.0f * es->mueff / nf); + es->cs = (es->mueff + 2.0f) / (nf + es->mueff + 5.0f); + es->c1 = 2.0f / (((nf + 1.3f)*(nf + 1.3f)) + es->mueff); + es->cmu = fminf (1.0f - es->c1, + 2.0f * (es->mueff - 2.0f + 1.0f/es->mueff) / + (((nf + 2.0f)*(nf + 2.0f)) + es->mueff)); + es->damps = 1.0f + 2.0f * fmaxf (0.0f, sqrtf ((es->mueff - 1.0f)/(nf + 1.0f)) - 1.0f) + + es->cs; + } + + mat_identity (es->C, n); + mat_identity (es->B, n); + mat_identity (es->BD, n); + mat_identity (es->invsqrtC, n); + for (int i = 0; i < n; ++i) + es->D[i] = 1.0f; + + cma_rng_seed (&es->rng, seed); + return 1; +} + +void +cmaes_free (struct cmaes *es) +{ + free (es->weights); + free (es->xmean); + free (es->xold); + free (es->pc); + free (es->ps); + free (es->C); + free (es->B); + free (es->D); + free (es->BD); + free (es->invsqrtC); + free (es->ary); + free (es->arx); + free (es->fitness); + free (es->index); + memset (es, 0, sizeof (*es)); +} + +static void +cmaes_update_eigensystem (struct cmaes *es) +{ + int n = es->n; + float *tmp = (float*)calloc ((size_t)n*(size_t)n, sizeof (float)); + float *eval = (float*)calloc ((size_t)n, sizeof (float)); + + if (!tmp || !eval) { + free (tmp); + free (eval); + return; + } + + symmetrize (es->C, n); + mat_copy (tmp, es->C, n); + jacobi_eigen_symmetric (tmp, es->B, eval, n); + + for (int i = 0; i < n; ++i) + es->D[i] = sqrtf (fmaxf (eval[i], 1e-20f)); + + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) + es->BD[MIDX(i,j,n)] = es->B[MIDX(i,j,n)] * es->D[j]; + } + + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + float s = 0.0f; + for (int k = 0; k < n; ++k) + s += es->B[MIDX(i,k,n)] * (1.0f / es->D[k]) * es->B[MIDX(j,k,n)]; + es->invsqrtC[MIDX(i,j,n)] = s; + } + } + + free (tmp); + free (eval); +} + +void +cmaes_ask (struct cmaes *es) +{ + int n = es->n; + + for (int k = 0; k < es->lambda; ++k) { + float z[CMA_DIM]; /* n=7 in your use-case */ + float *y = &es->ary[k*n]; + float *x = &es->arx[k*n]; + + for (int j = 0; j < n; ++j) + z[j] = cma_rng_normal (&es->rng); + + mat_vec_mul (y, es->BD, z, n); + + for (int j = 0; j < n; ++j) + x[j] = es->xmean[j] + es->sigma * y[j]; + } +} + +void +cmaes_sort_indices (struct cmaes *es) +{ + for (int i = 0; i < es->lambda; ++i) + es->index[i] = i; + + for (int i = 1; i < es->lambda; ++i) { + int key = es->index[i]; + float fkey = es->fitness[key]; + int j = i - 1; + + while (j >= 0 && es->fitness[es->index[j]] > fkey) { + es->index[j + 1] = es->index[j]; + --j; + } + es->index[j + 1] = key; + } +} + +void +cmaes_tell (struct cmaes *es, const float *fitness) +{ + int n = es->n; + memcpy (es->fitness, fitness, (size_t)es->lambda * sizeof (*fitness)); + cmaes_sort_indices (es); + + vec_copy (es->xold, es->xmean, n); + vec_set_zero (es->xmean, n); + + for (int i = 0; i < es->mu; ++i) { + const float *x = &es->arx[es->index[i] * n]; + float w = es->weights[i]; + for (int j = 0; j < n; ++j) + es->xmean[j] += w * x[j]; + } + + { + float y_w[CMA_DIM]; + float z_w[CMA_DIM]; + float coeff_ps = sqrtf (es->cs * (2.0f - es->cs) * es->mueff); + float coeff_pc = sqrtf (es->cc * (2.0f - es->cc) * es->mueff); + + for (int j = 0; j < n; ++j) + y_w[j] = (es->xmean[j] - es->xold[j]) / fmaxf (es->sigma, EPS); + + mat_vec_mul (z_w, es->invsqrtC, y_w, n); + + for (int j = 0; j < n; ++j) + es->ps[j] = (1.0f - es->cs) * es->ps[j] + coeff_ps * z_w[j]; + + { + float norm_ps = vec_norm (es->ps, n); + float denom = sqrtf (1.0f - powf (1.0f - es->cs, 2.0f * (es->generation + 1))); + float left = norm_ps / fmaxf (denom * es->chi_n, EPS); + int hsig = left < (1.4f + 2.0f / ((float)n + 1.0f)); + + for (int j = 0; j < n; ++j) + es->pc[j] = (1.0f - es->cc) * es->pc[j] + (hsig ? coeff_pc * y_w[j] : 0.0f); + + { + float alpha = 1.0f - es->c1 - es->cmu + + (hsig ? 0.0f : es->c1 * es->cc * (2.0f - es->cc)); + + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) + es->C[MIDX(i,j,n)] *= alpha; + } + + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) + es->C[MIDX(i,j,n)] += es->c1 * es->pc[i] * es->pc[j]; + } + + for (int a = 0; a < es->mu; ++a) { + const float *y = &es->ary[es->index[a] * n]; + float w = es->weights[a]; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) + es->C[MIDX(i,j,n)] += es->cmu * w * y[i] * y[j]; + } + } + + symmetrize (es->C, n); + + for (int i = 0; i < n; ++i) + es->C[MIDX(i,i,n)] = fmaxf (es->C[MIDX(i,i,n)], 1e-20f); + } + + es->sigma *= expf ((es->cs / es->damps) * (norm_ps / es->chi_n - 1.0f)); + } + } + + es->generation += 1; + es->evaluations += (uint64_t)es->lambda; + + cmaes_update_eigensystem (es); +} + +const float * +cmaes_candidate (const struct cmaes *es, int k) +{ + return &es->arx[k * es->n]; +} + +int +cmaes_should_stop (const struct cmaes *es) +{ + if (!isfinite (es->sigma) || es->sigma < 1e-10f) + return 1; + + for (int i = 0; i < es->n; ++i) { + if (!isfinite (es->D[i])) + return 1; + } + + return 0; +} + +struct cmaes_result +cmaes_run (struct cmaes *es, + int max_generations, + cma_objective_fn objective, + void *userdata) +{ + struct cmaes_result out; + out.best_f = FLT_MAX; + out.best_generation = -1; + for (int i = 0; i < es->n; ++i) out.best_x[i] = es->xmean[i]; + + for (int gen = 0; gen < max_generations; ++gen) { + cmaes_ask (es); + + for (int k = 0; k < es->lambda; ++k) { + const float *x = cmaes_candidate (es, k); + float f = objective (x, es->n, userdata); + if (!isfinite (f)) f = 1e30f; + es->fitness[k] = f; + + if (f < out.best_f) { + out.best_f = f; + out.best_generation = es->generation; + for (int j = 0; j < es->n; ++j) + out.best_x[j] = x[j]; + } + } + + cmaes_tell (es, es->fitness); + + if (cmaes_should_stop (es)) + break; + } + + return out; +} + +float +spline_cma_objective (const float *z, int n, void *userdata) +{ + (void)n; + + struct spline_objective_ctx *ctx = (struct spline_objective_ctx*)userdata; + struct chromosome ch; + bezier5 cp; + struct path_table p; + struct motion_profile m; + + cma_decode_chromosome (&ch, z, &ctx->in, &ctx->cfg); + chromosome_to_control_points (cp, ctx->in, ch); + + build_path_table (&p, cp); + + { + float v_beg = v2_len (ctx->in.v_beg); + float v_end = v2_len (ctx->in.v_end); + + int ok = build_motion_profile (&m, &p, + v_beg, v_end, + ctx->in.v_max, + ctx->in.a_max, + ctx->in.j_max); + + { + struct fitness_breakdown fb = + evaluate_motion_fitness (&p, &m, + v_beg, v_end, + ctx->in.v_max, + ctx->in.a_max, + ctx->in.j_max, + ctx->weights); + + if (!isfinite (fb.total_cost)) + return ctx->hard_fail_cost; + + return fb.total_cost; + } + } +} + +void +example_cmaes_usage (const struct input *in, + const struct chromosome *nominal_chromosome, + const struct fitness_weights *weights, + struct chromosome *best_chromosome_out, + float *best_cost_out) +{ + struct chromosome_cma_config cfg = chromosome_cma_default_config (); + float mean0[CMA_DIM]; + struct cmaes es; + struct spline_objective_ctx ctx; + struct cmaes_result result; + + cma_encode_chromosome (mean0, nominal_chromosome, in, &cfg); + + /* Good starting point for 7D */ + if (!cmaes_init (&es, + CMA_DIM, + mean0, + 1.20f, /* sigma0 */ + 12, /* lambda */ + 1234567u /* seed */ + )) { + /* handle allocation/init failure */ + return; + } + + ctx.in = *in; + ctx.cfg = cfg; + ctx.weights = weights; + ctx.hard_fail_cost = 1e9f; + + result = cmaes_run (&es, 100, spline_cma_objective, &ctx); + + cma_decode_chromosome (best_chromosome_out, result.best_x, in, &cfg); + if (best_cost_out) *best_cost_out = result.best_f; + + cmaes_free (&es); +} diff --git a/src/cma-es.h b/src/cma-es.h new file mode 100644 index 0000000..1e929e2 --- /dev/null +++ b/src/cma-es.h @@ -0,0 +1,126 @@ +#ifndef INCLUDED_CMA_ES_H +#define INCLUDED_CMA_ES_H + +#include + +#define CMA_DIM 7 + +struct input { + Vector2 r_beg; + Vector2 r_end; + Vector2 v_beg; + Vector2 v_end; + float v_max; + float a_max; + float j_max; +}; + +struct chromosome { + float rho; + float tau_1; + float alp_2; + float bet_2; + float alp_3; + float bet_3; + float tau_4; +}; + +struct cmaes_result { + float best_x[CMA_DIM]; + float best_f; + int best_generation; +}; + +struct chromosome_cma_config { + /* rho = D * [rho_min_rel, rho_max_rel] */ + float rho_min_rel; + float rho_max_rel; + + /* tau in [tau_min, 1 - tau_min] */ + float tau_min; + + /* alpha / beta bounds */ + float alp_limit; + float bet_limit; +}; + +struct spline_objective_ctx { + struct input in; + struct chromosome_cma_config cfg; + const struct fitness_weights *weights; + float hard_fail_cost; +}; + +typedef float (*cma_objective_fn) (const float *x, int n, void *userdata); + +struct cma_rng { + uint64_t state; + int has_spare; + float spare; +}; + +struct cmaes { + int n; + int lambda; + int mu; + + int generation; + uint64_t evaluations; + + float sigma; + float chi_n; + float mueff; + + float cc, cs, c1, cmu, damps; + + float *weights; /* mu */ + + float *xmean; /* n */ + float *xold; /* n */ + float *pc; /* n */ + float *ps; /* n */ + + float *C; /* n*n */ + float *B; /* n*n */ + float *D; /* n */ + float *BD; /* n*n */ + float *invsqrtC; /* n*n */ + + float *ary; /* lambda*n : y_k = B D z_k */ + float *arx; /* lambda*n : x_k = mean + sigma*y_k */ + + float *fitness; /* lambda */ + int *index; /* lambda */ + + struct cma_rng rng; +}; + +void chromosome_to_control_points (bezier5, struct input, struct chromosome); +void cma_decode_chromosome (struct chromosome *, + const float z[CMA_DIM], + const struct input *, + const struct chromosome_cma_config *); +void cma_encode_chromosome (float z[CMA_DIM], const struct chromosome *, + const struct input *, + const struct chromosome_cma_config *); + +int cmaes_default_lambda (int n); +float cmaes_expected_norm (int n); +int cmaes_init (struct cmaes *, int n, const float *mean0, float sigma0, + int lambda, uint64_t seed); +void cmaes_free (struct cmaes *); +void cmaes_ask (struct cmaes *); +void cmaes_sort_indices (struct cmaes *); +void cmaes_tell (struct cmaes *, const float *fitness); +const float *cmaes_candidate (const struct cmaes *es, int k); +int cmaes_should_stop (const struct cmaes *); +struct cmaes_result cmaes_run (struct cmaes *, int max_generations, + cma_objective_fn objective, void *userdata); +float spline_cma_objective (const float *z, int n, void *userdata); +void example_cmaes_usage (const struct input *, + const struct chromosome *nominal, + const struct fitness_weights *, + struct chromosome *best_chromosome_out, + float *best_cost_out); + +#endif // INCLUDED_CMA_ES_H diff --git a/src/main.c b/src/main.c new file mode 100644 index 0000000..7200ffe --- /dev/null +++ b/src/main.c @@ -0,0 +1,593 @@ +#include +#include +#include +#include +#include +#include + +#define RAYGUI_IMPLEMENTATION +#include + +#include "retiming.h" +#include "cma-es.h" + +#define RGBA(HEX) (Color) { \ + (HEX) >> 3*8 & 0xFF, \ + (HEX) >> 2*8 & 0xFF, \ + (HEX) >> 1*8 & 0xFF, \ + (HEX) >> 0*8 & 0xFF, \ + } + +// #define LABEL_WIDTH 140 +#define LABEL_WIDTH 300 +#define SLIDER_WIDTH 40 +#define ITEM_WIDTH (LABEL_WIDTH + SLIDER_WIDTH) +#define ITEM_HEIGHT 15 +#define ITEM_MARGIN 5 +#define PANEL_WIDTH (ITEM_WIDTH + 2*ITEM_MARGIN) +#define PANEL_HEIGHT(N) (RAYGUI_WINDOWBOX_STATUSBAR_HEIGHT + (N)*(ITEM_HEIGHT + ITEM_MARGIN) + ITEM_MARGIN) + +#ifdef DARK +#define BACKGROUND RGBA (0x000000FF) +#else +#define BACKGROUND RGBA (0xFFFFFFFF) +#endif + +#define ARROW_THICKNESS 2.5 +#define ARROW_LENGTH 15 +#define ARROW_ANGLE 10 + +#define CONTROL_POINT_RADIUS 5 +#define CONTROL_POINT_RADIUS_FOCUSED 10 + +enum menu { + MENU_VISUALIZATION, + MENU_INPUT, + MENU_CHROMOSOME, + MENU_METRICS, + MENU_WEIGHTS, + MENU_COUNT +} menu = MENU_VISUALIZATION; + +const char *menu_to_label[] = { + [MENU_VISUALIZATION] = "VISUALIZATION", + [MENU_INPUT] = "INPUT", + [MENU_CHROMOSOME] = "CHROMOSOME", + [MENU_METRICS] = "METRICS", + [MENU_WEIGHTS] = "WEIGHTS", +}; + +struct fitness_breakdown fb; +struct fitness_weights w = { + .time = 1.5, + .length = 1.5, + .max_abs_kappa = 30, + .max_abs_dkappa = 30, + .max_abs_a = 30, + .max_abs_j = 25, + .rms_kappa = 2, + .rms_dkappa = 4, + .rms_a = 3, + .rms_j = 0.35, + .violation_a = 3.5, + .violation_j = 0.2, + .terminal = 100, +}; + +void +draw_arrow (Vector2 beg, Vector2 end, float thick, Color c) +{ + Vector2 off = Vector2Scale (Vector2Normalize (Vector2Subtract (end, beg)), + ARROW_LENGTH); + Vector2 ahl = Vector2Add (end, Vector2Rotate (off, +ARROW_ANGLE)); + Vector2 ahr = Vector2Add (end, Vector2Rotate (off, -ARROW_ANGLE)); + + DrawLineEx (beg, end, thick, c); + DrawLineEx (end, ahl, thick, c); + DrawLineEx (end, ahr, thick, c); + + DrawCircleV (beg, thick/2., c); + DrawCircleV (end, thick/2., c); + DrawCircleV (ahl, thick/2., c); + DrawCircleV (ahr, thick/2., c); +} + +void +draw_bezier5 (bezier5 cp) +{ + char text[] = "P0"; + DrawLineStrip (cp, 6, BLUE); + for (int i = 0; i < 6; ++i) { + DrawCircleLinesV (cp[i], 4, BLUE); + text[1] = '0' + i; + DrawText (text, cp[i].x - 5, cp[i].y + 7, 14, BLACK); + } +} + +void +chromosome_to_control_points (bezier5 cp, struct input in, struct chromosome ch) +{ + Vector2 e_beg = Vector2Normalize (in.v_beg); + Vector2 e_end = Vector2Normalize (in.v_end); + Vector2 n_beg = { -e_beg.y, +e_beg.x }; + Vector2 n_end = { -e_end.y, +e_end.x }; + + cp[0] = in.r_beg; + cp[1] = Vector2Add (in.r_beg, Vector2Scale (e_beg, +ch.rho*ch.tau_1)); + cp[2] = Vector2Add (in.r_beg, Vector2Scale (Vector2Add (Vector2Scale (e_beg, ch.alp_2), Vector2Scale (n_beg, ch.bet_2)), +ch.rho)); + cp[3] = Vector2Add (in.r_end, Vector2Scale (Vector2Add (Vector2Scale (e_end, ch.alp_3), Vector2Scale (n_end, ch.bet_3)), -ch.rho)); + cp[4] = Vector2Add (in.r_end, Vector2Scale (e_end, -ch.rho*ch.tau_4)); + cp[5] = in.r_end; +} + +struct chromosome +rand_chromosome (void) +{ + return (struct chromosome) { + 10 + 50 * (rand () /(float) RAND_MAX), + .5 + 5 * (rand () /(float) RAND_MAX), + .5 + 5 * (rand () /(float) RAND_MAX), + .5 + 5 * (rand () /(float) RAND_MAX), + .5 + 5 * (rand () /(float) RAND_MAX), + .5 + 5 * (rand () /(float) RAND_MAX), + .5 + 5 * (rand () /(float) RAND_MAX), + }; +} + +float sample_offset = 10; +float sample_spacing = PATH_SAMPLE_COUNT/4; +bool sample_dr = true; +bool sample_ddr = true; + +Color +lerp_color (Color a, Color b, float t) +{ + Color c; + c.r = (unsigned char) (a.r + (b.r - a.r)*t); + c.g = (unsigned char) (a.g + (b.g - a.g)*t); + c.b = (unsigned char) (a.b + (b.b - a.b)*t); + c.a = (unsigned char) (a.a + (b.a - a.a)*t); + return c; +} + +float ease_out_cubic (float x) { return 1 - powf (1 - x, 3); } +float ease_out_quint (float x) { return 1 - powf (1 - x, 5); } +float ease_out_sin (float x) { return sinf (PI*x/2); } +float ease_inout_sin (float x) { return -(cosf (PI*x) - 1)/2; } + +void +compute_ribbon_join (const struct path_table *p, int i, float half, + Vector2 *l, Vector2 *r) +{ + Vector2 t; + + if (i == 0) { + t = Vector2Normalize (Vector2Subtract (p->r[1], p->r[0])); + } else if (i == PATH_SAMPLE_COUNT - 1) { + t = Vector2Normalize (Vector2Subtract (p->r[i], p->r[i - 1])); + } else { + t = Vector2Normalize (Vector2Subtract (p->r[i + 1], p->r[i - 1])); + } + + Vector2 n = { -t.y, t.x }; + + *l = Vector2Add (p->r[i], Vector2Scale (n, half)); + *r = Vector2Add (p->r[i], Vector2Scale (n, -half)); +} + +void +draw_path_gradient_ribbon (const struct path_table *p, + float thick, Color c0, Color c1) +{ + if (PATH_SAMPLE_COUNT < 2 || thick <= 0) return; + + float half = thick/2; + + Vector2 l0, r0, l1, r1; + compute_ribbon_join (p, 0, half, &l0, &r0); + + rlBegin (RL_TRIANGLES); + for (int i = 0; i < PATH_SAMPLE_COUNT - 1; ++i) { + compute_ribbon_join (p, i + 1, half, &l1, &r1); + + float u0 = ease_out_cubic (fabsf (p->kappa[i + 0])/p->max_abs_kappa); + float u1 = ease_out_cubic (fabsf (p->kappa[i + 1])/p->max_abs_kappa); + + Color col0 = lerp_color (c0, c1, u0); + Color col1 = lerp_color (c0, c1, u1); + + rlColor4ub (col0.r, col0.g, col0.b, col0.a); rlVertex2f (l0.x, l0.y); + rlColor4ub (col1.r, col1.g, col1.b, col1.a); rlVertex2f (l1.x, l1.y); + rlColor4ub (col0.r, col0.g, col0.b, col0.a); rlVertex2f (r0.x, r0.y); + + rlColor4ub (col0.r, col0.g, col0.b, col0.a); rlVertex2f (r0.x, r0.y); + rlColor4ub (col1.r, col1.g, col1.b, col1.a); rlVertex2f (l1.x, l1.y); + rlColor4ub (col1.r, col1.g, col1.b, col1.a); rlVertex2f (r1.x, r1.y); + + l0 = l1; + r0 = r1; + } rlEnd (); +} + +void +draw_path (const struct path_table *p, float thick) +{ + const int c = PATH_SAMPLE_COUNT; + // DrawCircleV (p->r[ 0], thick/2., BLUE); + // DrawCircleV (p->r[c - 1], thick/2., BLUE); + draw_path_gradient_ribbon (p, thick, BLUE, RED); + for (int i = sample_offset; i < c; i += sample_spacing) { + Vector2 r = p->r[i]; + if (sample_dr ) draw_arrow (r, Vector2Add (r, Vector2Scale (Vector2Normalize (p-> dr[i]), 30)), thick/2, MAGENTA); + if (sample_ddr) draw_arrow (r, Vector2Add (r, Vector2Scale (Vector2Normalize (p->ddr[i]), 30)), thick/2, PURPLE); + } +} + +void +plot_motion_profile (Rectangle bb, const struct motion_profile *mp, + float v_max, float a_max, float j_max) +{ + const int n = PATH_SAMPLE_COUNT; + static Vector2 line[PATH_SAMPLE_COUNT]; + + float t = mp->t[n - 1]; + for (int i = 0; i < n; ++i) + line[i].x = Lerp (bb.x, bb.x + bb.width, mp->t[i]/t); + + // axis + Vector2 origin = { bb.x, bb.y + bb.height /(float) 2 }; + DrawLineEx (origin, Vector2Add (origin, (Vector2) { bb.width, 0 }), 1, GRAY); + for (int i = 0; i < n; ++i) { + DrawLineEx ((Vector2) { line[i].x, origin.y + 5 }, + (Vector2) { line[i].x, origin.y - 5 }, 1, GRAY); + } + + // velocity + for (int i = 0; i < n; ++i) + line[i].y = Lerp (origin.y, bb.y + 2, mp->v[i]/fabsf (mp->v_max)); + DrawSplineBezierCubic (line, n, 1, BLUE); + + // acceleration + for (int i = 0; i < n; ++i) + line[i].y = Lerp (origin.y, bb.y + 2, mp->a[i]/fabsf (mp->a_max)); + DrawSplineBezierCubic (line, n, 1, ORANGE); + + // jerk + for (int i = 0; i < n; ++i) + line[i].y = Lerp (origin.y, bb.y + 2, mp->j[i]/fabsf (mp->j_max)); + DrawSplineBezierCubic (line, n, 1, RED); +} + +int +panel_slider (int x, int y, int c, const char *label, const char *fmt, float *var, float min, float max) +{ + GuiLabel ((Rectangle) { x + ITEM_MARGIN, y + c*(ITEM_HEIGHT + ITEM_MARGIN), LABEL_WIDTH, ITEM_HEIGHT }, TextFormat ("%s: %s", label, TextFormat (fmt, *var))); + return GuiSliderBar ((Rectangle) { x + ITEM_MARGIN + LABEL_WIDTH, y + c*(ITEM_HEIGHT + ITEM_MARGIN), SLIDER_WIDTH, ITEM_HEIGHT }, NULL, NULL, var, min, max); +} + +int +panel_var (int x, int y, int c, const char *label, const char *fmt, float *var) +{ + GuiLabel ((Rectangle) { x + ITEM_MARGIN, y + c*(ITEM_HEIGHT + ITEM_MARGIN), ITEM_WIDTH, ITEM_HEIGHT }, + TextFormat ("%s: %s", label, TextFormat (fmt, *var))); + return 0; +} + +int +panel_bool (int x, int y, int c, const char *label, bool *checked) +{ + return GuiCheckBox ((Rectangle) { + x + ITEM_MARGIN, y + c*(ITEM_HEIGHT + ITEM_MARGIN), + ITEM_HEIGHT, ITEM_HEIGHT + }, label, checked); +} + +int +main (int argc, char *argv[]) +{ + srand (time (NULL)); + + SetConfigFlags (FLAG_MSAA_4X_HINT); + SetConfigFlags (FLAG_WINDOW_RESIZABLE); + InitWindow (800, 450, "GA"); + SetTargetFPS (60); + + Camera2D camera = { + .zoom = 1.0f, + }; + + Vector2 screen = { + .x = GetScreenWidth (), + .y = GetScreenHeight (), + }; + + GuiSetStyle(DEFAULT, TEXT_SIZE, 20); + // GuiGetStyle (); + + struct input in = { + .r_beg = { 100, 100 }, + // .r_end = { 100, 100 }, + .r_end = { 300, 300 }, + .v_beg = { 100, 10 }, + .v_end = { 100, 10 }, + .v_max = 250, + .a_max = 500, + .j_max = 16, + }; + + bezier5 cp; + struct chromosome ch = rand_chromosome (); + struct path_table pt; + struct motion_profile mp; + + float arrow_thickness = ARROW_THICKNESS; + float spline_thickness = ARROW_THICKNESS; + bool move_r_beg = false; + bool move_r_end = false; + bool move_v_beg = false; + bool move_v_end = false; + bool recompute = true; + bool show_fps = true; + bool show_menu = true; + bool show_graph = true; + bool draw_cp = true; + bool animate_sample_offset = false; + float animation_speed = 20; + int panel_item = 0; + bool resizing_graph = false; + int graph_height = screen.y/3; + while (!WindowShouldClose ()) { + screen = (Vector2) { + .x = GetScreenWidth (), + .y = GetScreenHeight (), + }; + float t = GetTime (); + float dt = GetFrameTime (); + + if (IsMouseButtonDown (MOUSE_BUTTON_RIGHT)) { + Vector2 delta = GetMouseDelta (); + delta = Vector2Scale (delta, -1.0f/camera.zoom); + camera.target = Vector2Add (camera.target, delta); + } + + if (IsKeyPressed (KEY_LEFT )) menu = menu ? menu - 1 : MENU_COUNT - 1; + if (IsKeyPressed (KEY_RIGHT)) menu = menu < MENU_COUNT - 1 ? menu + 1 : 0; + + if (IsKeyPressed (KEY_R)) { + ch = rand_chromosome (); + recompute = true; + } + + if (IsKeyDown (KEY_O)) { + struct chromosome res; + float cost; + example_cmaes_usage (&in, &ch, &w, &res, &cost); + ch = res; + recompute = true; + } + + if (IsKeyPressed (KEY_M)) show_menu = !show_menu; + if (IsKeyPressed (KEY_G)) show_graph = !show_graph; + if (IsKeyPressed (KEY_F)) show_fps = !show_fps; + + if (recompute) { + chromosome_to_control_points (cp, in, ch); + build_path_table (&pt, cp); + build_motion_profile (&mp, &pt, + Vector2Length (in.v_beg), + Vector2Length (in.v_end), + in.v_max, in.a_max, in.j_max); + fb = evaluate_motion_fitness (&pt, &mp, + Vector2Length (in.v_beg), + Vector2Length (in.v_end), + in.v_max, in.a_max, in.j_max, &w); + + recompute = false; + } + + float wheel = GetMouseWheelMove(); + if (wheel != 0) { + Vector2 offset = GetMousePosition (); + camera.target = GetScreenToWorld2D (offset, camera); + camera.offset = offset; + camera.zoom = Clamp (expf (logf (camera.zoom) + .2*wheel), .125, 64); + } + + Vector2 mouse_hud = GetMousePosition (); + Vector2 mouse = GetScreenToWorld2D (mouse_hud, camera); + + if (IsMouseButtonDown (MOUSE_BUTTON_LEFT) + && mouse_hud.y > screen.y - graph_height + && mouse_hud.y < screen.y - graph_height + RAYGUI_WINDOWBOX_STATUSBAR_HEIGHT) { + resizing_graph = true; + } + + if (resizing_graph) { + graph_height = Clamp (RAYGUI_WINDOWBOX_STATUSBAR_HEIGHT + 2, screen.y - 4, + screen.y - mouse_hud.y + RAYGUI_WINDOWBOX_STATUSBAR_HEIGHT/2); + if (IsMouseButtonReleased (MOUSE_BUTTON_LEFT)) + resizing_graph = false; + } + + BeginDrawing (); + ClearBackground (BACKGROUND); + BeginMode2D (camera); + + if (CheckCollisionPointCircle (mouse, in.r_beg, 10)) { + DrawCircleLinesV (in.r_beg, 10, BLUE); + if (!move_v_beg && IsMouseButtonDown (MOUSE_BUTTON_LEFT)) + move_r_beg = true; + } else if (CheckCollisionPointCircle (mouse, in.r_end, 10)) { + DrawCircleLinesV (in.r_end, 10, BLUE); + if (!move_v_end && IsMouseButtonDown (MOUSE_BUTTON_LEFT)) + move_r_end = true; + } else if (CheckCollisionPointCircle (mouse, Vector2Add (in.r_beg, in.v_beg), 10)) { + DrawCircleLinesV (Vector2Add (in.r_beg, in.v_beg), 10, BLUE); + if (!move_r_beg && IsMouseButtonDown (MOUSE_BUTTON_LEFT)) + move_v_beg = true; + } else if (CheckCollisionPointCircle (mouse, Vector2Add (in.r_end, in.v_end), 10)) { + DrawCircleLinesV (Vector2Add (in.r_end, in.v_end), 10, BLUE); + if (!move_r_end && IsMouseButtonDown (MOUSE_BUTTON_LEFT)) + move_v_end = true; + } + + if (move_r_beg) { + in.r_beg = mouse; + if (IsMouseButtonReleased (MOUSE_BUTTON_LEFT)) + move_r_beg = false; + } + if (move_r_end) { + in.r_end = mouse; + if (IsMouseButtonReleased (MOUSE_BUTTON_LEFT)) + move_r_end = false; + } + if (move_v_beg) { + in.v_beg = Vector2Subtract (mouse, in.r_beg); + if (IsMouseButtonReleased (MOUSE_BUTTON_LEFT)) + move_v_beg = false; + } + if (move_v_end) { + in.v_end = Vector2Subtract (mouse, in.r_end); + if (IsMouseButtonReleased (MOUSE_BUTTON_LEFT)) + move_v_end = false; + } + + if (animate_sample_offset) + sample_offset = (int) (animation_speed*t) % (int) sample_spacing; + + // rlPushMatrix (); + // rlTranslatef (0, 25*50, 0); + // rlRotatef (90, 1, 0, 0); + // DrawGrid (100, 50); + // rlPopMatrix (); + + draw_path (&pt, spline_thickness); + if (draw_cp) draw_bezier5 (cp); + draw_arrow (in.r_beg, Vector2Add (in.r_beg, in.v_beg), arrow_thickness, GREEN); + draw_arrow (in.r_end, Vector2Add (in.r_end, in.v_end), arrow_thickness, RED); + + EndMode2D (); + + if (move_r_beg || + move_r_end || + move_v_beg || + move_v_end) { + GuiLock (); + recompute = true; + } + + if (show_menu) { + int x = 2; + int y = 2; + + GuiPanel ((Rectangle) { x, y, PANEL_WIDTH, PANEL_HEIGHT (panel_item) }, menu_to_label[menu]); + y += RAYGUI_WINDOWBOX_STATUSBAR_HEIGHT; + y += ITEM_MARGIN; + panel_item = 0; + switch (menu) { + case MENU_VISUALIZATION: + panel_slider (x, y, panel_item++, "Arrow", "%.2f", &arrow_thickness, 1, 10); + panel_slider (x, y, panel_item++, "Spline", "%.2f", &spline_thickness, 1, 10); + panel_slider (x, y, panel_item++, "Spacing", "%.0f", &sample_spacing, 2, PATH_SAMPLE_COUNT - 1); + panel_slider (x, y, panel_item++, "Offset", "%.0f", &sample_offset, 0, sample_spacing); + panel_slider (x, y, panel_item++, "Speed", "%.0f", &animation_speed, 0, 30); + panel_bool (x, y, panel_item++, "Animate offset", &animate_sample_offset); + panel_bool (x, y, panel_item++, "Draw dr", &sample_dr); + panel_bool (x, y, panel_item++, "Draw ddr", &sample_ddr); + panel_bool (x, y, panel_item++, "Draw cp", &draw_cp); + break; + + case MENU_INPUT: + recompute |= panel_slider (x, y, panel_item++, "v_lim", "%.2f", &in.v_max, fmaxf (Vector2Length (in.v_beg), Vector2Length (in.v_beg)), 500); + recompute |= panel_slider (x, y, panel_item++, "a_lim", "%.2f", &in.a_max, 1, 500); + recompute |= panel_slider (x, y, panel_item++, "j_lim", "%.2f", &in.j_max, 1, 100); + panel_var (x, y, panel_item++, "r_beg.x", "%.2f", &in.r_beg.x); + panel_var (x, y, panel_item++, "r_beg.y", "%.2f", &in.r_beg.y); + panel_var (x, y, panel_item++, "r_end.x", "%.2f", &in.r_end.x); + panel_var (x, y, panel_item++, "r_end.y", "%.2f", &in.r_end.y); + panel_var (x, y, panel_item++, "v_beg.x", "%.2f", &in.v_beg.x); + panel_var (x, y, panel_item++, "v_beg.y", "%.2f", &in.v_beg.y); + panel_var (x, y, panel_item++, "v_end.x", "%.2f", &in.v_end.x); + panel_var (x, y, panel_item++, "v_end.y", "%.2f", &in.v_end.y); + break; + + case MENU_CHROMOSOME: + recompute |= panel_slider (x, y, panel_item++, "rho", "%.2f", &ch.rho, 1, 1000); + recompute |= panel_slider (x, y, panel_item++, "tau_1", "%.2f", &ch.tau_1, 0, 10); + recompute |= panel_slider (x, y, panel_item++, "alpha_2", "%.2f", &ch.alp_2, 0, 10); + recompute |= panel_slider (x, y, panel_item++, "beta_2", "%+.2f", &ch.bet_2, -5, 5); + recompute |= panel_slider (x, y, panel_item++, "alpha_3", "%.2f", &ch.alp_3, 0, 10); + recompute |= panel_slider (x, y, panel_item++, "beta_3", "%+.2f", &ch.bet_3, -5, 5); + recompute |= panel_slider (x, y, panel_item++, "tau_4", "%.2f", &ch.tau_4, 0, 10); + break; + + case MENU_WEIGHTS: + recompute |= panel_slider (x, y, panel_item++, "w_time", "%.2f", &w.time, 0, 10); + recompute |= panel_slider (x, y, panel_item++, "w_length", "%.2f", &w.length, 0, 10); + recompute |= panel_slider (x, y, panel_item++, "w_max_kappa", "%.2f", &w.max_abs_kappa, 0, 100); + recompute |= panel_slider (x, y, panel_item++, "w_max_dkappa", "%.2f", &w.max_abs_dkappa, 0, 100); + recompute |= panel_slider (x, y, panel_item++, "w_max_a", "%.2f", &w.max_abs_a, 0, 100); + recompute |= panel_slider (x, y, panel_item++, "w_max_j", "%.2f", &w.max_abs_j, 0, 100); + recompute |= panel_slider (x, y, panel_item++, "w_rms_kappa", "%.2f", &w.rms_kappa, 0, 10); + recompute |= panel_slider (x, y, panel_item++, "w_rms_dkappa", "%.2f", &w.rms_dkappa, 0, 10); + recompute |= panel_slider (x, y, panel_item++, "w_rms_a", "%.2f", &w.rms_a, 0, 10); + recompute |= panel_slider (x, y, panel_item++, "w_rms_j", "%.2f", &w.rms_j, 0, 1); + recompute |= panel_slider (x, y, panel_item++, "w_violation_a", "%.2f", &w.violation_a, 0, 10); + recompute |= panel_slider (x, y, panel_item++, "w_violation_j", "%.2f", &w.violation_j, 0, 1); + recompute |= panel_slider (x, y, panel_item++, "w_terminal", "%.2f", &w.terminal, 0, 100); + break; + + case MENU_METRICS: + panel_var (x, y, panel_item++, "Length", "%.2f", &pt.s[PATH_SAMPLE_COUNT - 1]); + panel_var (x, y, panel_item++, "Duration", "%.2f", &mp.t[PATH_SAMPLE_COUNT - 1]); + panel_var (x, y, panel_item++, "Cost", "%.2f", &fb.total_cost); + + panel_var (x, y, panel_item++, "v_max", "%.2f", &mp.v_max); + panel_var (x, y, panel_item++, "a_max", "%.2f", &mp.a_max); + panel_var (x, y, panel_item++, "j_max", "%.2f", &mp.j_max); + + panel_var (x, y, panel_item++, "time_cost", "%.2f", &fb.time_cost); + panel_var (x, y, panel_item++, "length_cost", "%.2f", &fb.length_cost); + panel_var (x, y, panel_item++, "kappa_cost", "%.2f", &fb.kappa_cost); + panel_var (x, y, panel_item++, "dkappa_cost", "%.2f", &fb.dkappa_cost); + panel_var (x, y, panel_item++, "accel_rms_cost", "%.2f", &fb.accel_rms_cost); + panel_var (x, y, panel_item++, "jerk_rms_cost", "%.2f", &fb.jerk_rms_cost); + panel_var (x, y, panel_item++, "accel_violation_cost", "%.2f", &fb.accel_violation_cost); + panel_var (x, y, panel_item++, "jerk_violation_cost", "%.2f", &fb.jerk_violation_cost); + panel_var (x, y, panel_item++, "terminal_cost", "%.2f", &fb.terminal_cost); + panel_var (x, y, panel_item++, "failure_cost", "%.2f", &fb.failure_cost); + panel_var (x, y, panel_item++, "duration", "%.2f", &fb.duration); + panel_var (x, y, panel_item++, "length", "%.2f", &fb.length); + panel_var (x, y, panel_item++, "kappa_rms", "%.2f", &fb.kappa_rms); + panel_var (x, y, panel_item++, "dkappa_rms", "%.2f", &fb.dkappa_rms); + panel_var (x, y, panel_item++, "accel_rms", "%.2f", &fb.accel_rms); + panel_var (x, y, panel_item++, "jerk_rms", "%.2f", &fb.jerk_rms); + panel_var (x, y, panel_item++, "accel_violation", "%.2f", &fb.accel_violation); + panel_var (x, y, panel_item++, "jerk_violation", "%.2f", &fb.jerk_violation); + break; + default: break; + } + } + GuiUnlock (); + + if (show_graph) { + Rectangle bb; + bb.x = 2; + bb.width = screen.x - 4; + bb.height = graph_height; + bb.y = screen.y - 2 - bb.height; + GuiPanel (bb, "GRAPH"); + bb.y += RAYGUI_WINDOWBOX_STATUSBAR_HEIGHT; + bb.height -= RAYGUI_WINDOWBOX_STATUSBAR_HEIGHT; + plot_motion_profile (bb, &mp, in.v_max, in.a_max, in.j_max); + } + + if (show_fps) + DrawFPS (screen.x - 75, 0); + EndDrawing (); + } + + CloseWindow (); + + return EXIT_SUCCESS; +} diff --git a/src/retiming.c b/src/retiming.c new file mode 100644 index 0000000..c2ce159 --- /dev/null +++ b/src/retiming.c @@ -0,0 +1,427 @@ +#include "retiming.h" + +Vector2 +bezier5_point (const bezier5 cp, float u) +{ + float w = 1 - u; + + float b0 = w*w*w*w*w * 1; + float b1 = w*w*w*w*u * 5; + float b2 = w*w*w*u*u * 10; + float b3 = w*w*u*u*u * 10; + float b4 = w*u*u*u*u * 5; + float b5 = u*u*u*u*u * 1; + + return (Vector2) { + .x = b0 * cp[0].x + + b1 * cp[1].x + + b2 * cp[2].x + + b3 * cp[3].x + + b4 * cp[4].x + + b5 * cp[5].x, + .y = b0 * cp[0].y + + b1 * cp[1].y + + b2 * cp[2].y + + b3 * cp[3].y + + b4 * cp[4].y + + b5 * cp[5].y, + }; +} + +Vector2 +bezier5_deriv1 (const bezier5 cp, float u) +{ + float w = 1 - u; + + float b0 = w*w*w*w * 1; + float b1 = w*w*w*u * 4; + float b2 = w*w*u*u * 6; + float b3 = w*u*u*u * 4; + float b4 = u*u*u*u * 1; + + Vector2 q0 = Vector2Subtract (cp[1], cp[0]); + Vector2 q1 = Vector2Subtract (cp[2], cp[1]); + Vector2 q2 = Vector2Subtract (cp[3], cp[2]); + Vector2 q3 = Vector2Subtract (cp[4], cp[3]); + Vector2 q4 = Vector2Subtract (cp[5], cp[4]); + + return (Vector2) { + 5*(b0*q0.x + b1*q1.x + b2*q2.x + b3*q3.x + b4*q4.x), + 5*(b0*q0.y + b1*q1.y + b2*q2.y + b3*q3.y + b4*q4.y), + }; +} + +Vector2 +bezier5_deriv2(const bezier5 cp, float u) +{ + float w = 1 - u; + + float b0 = w*w*w * 1; + float b1 = w*w*u * 3; + float b2 = w*u*u * 3; + float b3 = u*u*u * 1; + + Vector2 r0 = Vector2Add (Vector2Subtract (cp[2], Vector2Scale (cp[1], 2)), cp[0]); + Vector2 r1 = Vector2Add (Vector2Subtract (cp[3], Vector2Scale (cp[2], 2)), cp[1]); + Vector2 r2 = Vector2Add (Vector2Subtract (cp[4], Vector2Scale (cp[3], 2)), cp[2]); + Vector2 r3 = Vector2Add (Vector2Subtract (cp[5], Vector2Scale (cp[4], 2)), cp[3]); + + return (Vector2) { + 20*(b0*r0.x + b1*r1.x + b2*r2.x + b3*r3.x), + 20*(b0*r0.y + b1*r1.y + b2*r2.y + b3*r3.y), + }; +} + +void +build_path_table (struct path_table *table, const bezier5 cp) +{ + int i, c = PATH_SAMPLE_COUNT; + for (i = 0; i < c; ++i) table->u [i] = i /(float) (PATH_SAMPLE_COUNT - 1); + for (i = 0; i < c; ++i) table->r [i] = bezier5_point (cp, table->u[i]); + for (i = 0; i < c; ++i) table->dr [i] = bezier5_deriv1 (cp, table->u[i]); + for (i = 0; i < c; ++i) table->ddr [i] = bezier5_deriv2 (cp, table->u[i]); + + table->s[0] = 0; + for (i = 1; i < c; ++i) { + table->s[i] = table->s[i - 1] + Vector2Length ( + Vector2Subtract (table->r[i], table->r[i - 1])); + } + + float max_abs_kappa = 0; + for (i = 0; i < c; ++i) { + Vector2 dr = table-> dr[i]; + Vector2 ddr = table->ddr[i]; + float l = Vector2Length (dr); + float kappa = (dr.x*ddr.y - dr.y*ddr.x)/l/l/l; + table->kappa[i] = kappa; + if (fabsf (kappa) > max_abs_kappa) + max_abs_kappa = fabsf (kappa); + } table->max_abs_kappa = max_abs_kappa; + + table->dkappa_ds[ 0] = (table->kappa[ 1] - table->kappa[ 0]) / + (table->s [ 1] - table->s [ 0]); + table->dkappa_ds[c - 1] = (table->kappa[c - 1] - table->kappa[c - 2]) / + (table->s [c - 1] - table->s [c - 2]); + for (i = 1; i < c - 1; ++i) { + table->dkappa_ds[i] = (table->kappa[i + 1] - table->kappa[i - 1]) / + (table->s [i + 1] - table->s [i - 1]); + } +} + +float +speed_limit (float kappa, float dkappa_ds, + float v_max, float a_max, float j_max) +{ + float v_lim = v_max; + float k = fabsf (kappa); + + if (k > EPS) { + float va = sqrtf (fmaxf (0, a_max/k)); + v_lim = fminf (v_lim, va); + } + + // float jerk_denom = k*k + fabsf (dkappa_ds); + // if (jerk_denom > EPS) { + // float vj = cbrtf (fmaxf (0, j_max/jerk_denom)); + // v_lim = fminf (v_lim, vj); + // } + + if (!isfinite (v_lim)) v_lim = 0; + return fmaxf (v_lim, 0); +} + +float +centered_differences_in_time (float *d, const float *v, const float *t, int n) +{ + d[ 0] = (v[ 1] - v[ 0]) / + (t[ 1] - t[ 0]); + d[n - 1] = (v[n - 1] - v[n - 2]) / + (t[n - 1] - t[n - 2]); + float max = fabsf (d[0]) > fabsf(d[n - 1]) ? d[0] : d[n - 1]; + for (int i = 1; i < n - 1; ++i) { + d[i] = (v[i + 1] - v[i - 1]) / + (t[i + 1] - t[i - 1]); + if (fabsf (d[i]) > fabsf (max)) + max = d[i]; + } + + return max; +} + +float +tangential_accel_cap (float kappa, float v, float a_max) +{ + float an = fabsf (kappa)*v*v; + float rem = a_max*a_max - an*an; + return (rem > 0) ? sqrtf (rem) : 0; +} + +int +build_motion_profile (struct motion_profile *m, const struct path_table *p, + float v_beg, float v_end, + float v_max, float a_max, float j_max) +{ + static float v_lim[PATH_SAMPLE_COUNT]; + static float v_fwd[PATH_SAMPLE_COUNT]; + static float v_bwd[PATH_SAMPLE_COUNT]; + static float a_fwd[PATH_SAMPLE_COUNT]; + static float a_bwd[PATH_SAMPLE_COUNT]; + + const float MIN_TIME_SPEED = 1e-3f; + const int n = PATH_SAMPLE_COUNT; + + int feasible = 1; + + // Local speed ceilings + for (int i = 0; i < n; ++i) { + v_lim[i] = speed_limit (p->kappa[i], p->dkappa_ds[i], v_max, a_max, j_max); + } + + if (v_beg > v_lim[ 0] + 1e-4f) feasible = 0; + if (v_end > v_lim[n - 1] + 1e-4f) feasible = 0; + + // Forward pass + v_fwd[0] = v_beg; + a_fwd[0] = 0; + for (int i = 0; i < n - 1; ++i) { + float ds = p->s[i + 1] - p->s[i]; + float v_cur = v_fwd[i]; + float v_for_dt = fmaxf (v_cur, .25*v_max); + float dt_est = ds/v_for_dt; + + float a_cap = tangential_accel_cap (p->kappa[i], v_cur, a_max); + float a_next = fminf (a_cap, a_fwd[i] + j_max*dt_est); + if (a_next < 0) a_next = 0; + + float v_reach_sq = v_cur*v_cur + 2*a_next*ds; + float v_reach = sqrtf (fmaxf (0, v_reach_sq)); + + v_fwd[i + 1] = fminf (v_lim[i + 1], v_reach); + a_fwd[i + 1] = a_next; + } + + // Backward pass + v_bwd[n - 1] = v_end; + a_bwd[n - 1] = 0; + for (int i = n - 1; i > 0; --i) { + float ds = p->s[i] - p->s[i - 1]; + float v_cur = v_bwd[i]; + float v_for_dt = fmaxf (v_cur, .25*v_max); + float dt_est = ds/v_for_dt; + + float a_cap = tangential_accel_cap (p->kappa[i], v_cur, a_max); + float a_prev = fminf (a_cap, a_bwd[i] + j_max*dt_est); + if (a_prev < 0) a_prev = 0; + + float v_reach_prev_sq = v_cur*v_cur + 2*a_prev*ds; + float v_reach_prev = sqrtf (fmaxf (0, v_reach_prev_sq)); + + v_bwd[i - 1] = fminf (v_lim[i - 1], v_reach_prev); + a_bwd[i - 1] = a_prev; + } + + // Combined profile + for (int i = 0; i < n; ++i) + m->v[i] = fminf (v_fwd[i], v_bwd[i]); + + // Build cumulative time + m->t[0] = 0; + for (int i = 1; i < n; ++i) { + float ds = p->s[i] - p->s[i - 1]; + float v_avg = .5*(m->v[i - 1] + m->v[i]); + float dt = v_avg > EPS ? ds/v_avg : ds/MIN_TIME_SPEED; + + if (!isfinite (dt) || dt < 0) { + dt = ds/MIN_TIME_SPEED; + feasible = 0; + } + + m->t[i] = m->t[i - 1] + dt; + } + + m->v_max = 0; + for (int i = 0; i < n; ++i) { + if (fabsf (m->v[i]) > fabsf (m->v_max)) + m->v_max = m->v[i]; + } + m->a_max = centered_differences_in_time (m->a, m->v, m->t, n); + m->j_max = centered_differences_in_time (m->j, m->a, m->t, n); + + return feasible; +} + +static inline float +trapz_step (float y0, float y1, float dx) +{ + return 0.5f * (y0 + y1) * dx; +} + +static inline float +total_accel_norm (float kappa, float v, float a_t) +{ + float a_n = v*v*kappa; + return hypotf (a_t, a_n); +} + +static inline float +total_jerk_norm (float kappa, float dkappa_ds, + float v, float a_t, float j_t) +{ + float j_t_cart = j_t - v*v*v*kappa*kappa; + float j_n_cart = 3.0f*v*a_t*kappa + v*v*v*dkappa_ds; + return hypotf (j_t_cart, j_n_cart); +} + +static inline float +safe_ratio_sq (float num, float den, float fallback) +{ + if (!isfinite (num)) + return fallback; + if (!isfinite (den) || fabsf (den) < EPS) + den = 1.0f; + + { + float x = num / den; + if (!isfinite (x)) + return fallback; + return x * x; + } +} + +struct fitness_breakdown +evaluate_motion_fitness (const struct path_table *p, + const struct motion_profile *m, + float v_beg_target, + float v_end_target, + float v_max, + float a_max, + float j_max, + const struct fitness_weights *w) +{ + struct fitness_breakdown out = {0}; + + const int n = PATH_SAMPLE_COUNT; + + out.duration = m->t[n - 1] - m->t[0]; + out.length = p->s[n - 1] - p->s[0]; + + float int_kappa2 = 0; + float int_dkappa2 = 0; + float int_a2_dt = 0; + float int_j2_dt = 0; + float int_a_violation_dt = 0; + float int_j_violation_dt = 0; + + float max_abs_kappa = 0; + float max_abs_dkappa = 0; + float max_abs_a = 0; + float max_abs_j = 0; + + for (int i = 0; i < n - 1; ++i) { + float ds = p->s[i + 1] - p->s[i]; + float dt = m->t[i + 1] - m->t[i]; + + // max + float abs_kappa = fabsf (p->kappa [i]); + float abs_dkappa = fabsf (p->dkappa_ds[i]); + float abs_a = fabsf (m->a [i]); + float abs_j = fabsf (m->j [i]); + if (abs_kappa > max_abs_kappa ) max_abs_kappa = abs_kappa; + if (abs_dkappa > max_abs_dkappa) max_abs_dkappa = abs_dkappa; + if (abs_a > max_abs_a ) max_abs_a = abs_a; + if (abs_j > max_abs_j ) max_abs_j = abs_j; + + /* geometry terms integrated over s */ + { + float k0 = p->kappa[i ]; + float k1 = p->kappa[i + 1]; + float dk0 = p->dkappa_ds[i ]; + float dk1 = p->dkappa_ds[i + 1]; + + int_kappa2 += trapz_step ( k0* k0, k1* k1, ds); + int_dkappa2 += trapz_step (dk0*dk0, dk1*dk1, ds); + } + + /* dynamic terms integrated over t */ + if (dt > EPS) { + float a0 = total_accel_norm (p->kappa[i ], m->v[i ], m->a[i ]); + float a1 = total_accel_norm (p->kappa[i + 1], m->v[i + 1], m->a[i + 1]); + + float j0 = total_jerk_norm (p->kappa[i ], p->dkappa_ds[i ], m->v[i ], m->a[i ], m->j[i ]); + float j1 = total_jerk_norm (p->kappa[i + 1], p->dkappa_ds[i + 1], m->v[i + 1], m->a[i + 1], m->j[i + 1]); + + int_a2_dt += trapz_step (a0*a0, j_max > 0 ? a1*a1 : a1*a1, dt); + int_j2_dt += trapz_step (j0*j0, j1*j1, dt); + + float av0 = fmaxf (0, (a0 - a_max) / fmaxf (a_max, EPS)); + float av1 = fmaxf (0, (a1 - a_max) / fmaxf (a_max, EPS)); + float jv0 = fmaxf (0, (j0 - j_max) / fmaxf (j_max, EPS)); + float jv1 = fmaxf (0, (j1 - j_max) / fmaxf (j_max, EPS)); + + int_a_violation_dt += trapz_step (av0*av0, av1*av1, dt); + int_j_violation_dt += trapz_step (jv0*jv0, jv1*jv1, dt); + } + } + + out.kappa_rms = sqrtf (int_kappa2 / fmaxf (out.length, EPS)); + out.dkappa_rms = sqrtf (int_dkappa2 / fmaxf (out.length, EPS)); + out.accel_rms = sqrtf (int_a2_dt / fmaxf (out.duration, EPS)); + out.jerk_rms = sqrtf (int_j2_dt / fmaxf (out.duration, EPS)); + + out.accel_violation = int_a_violation_dt / fmaxf (out.duration, EPS); + out.jerk_violation = int_j_violation_dt / fmaxf (out.duration, EPS); + + /* Weighted costs */ + out.time_cost = w->time * out.duration; + out.length_cost = w->length * out.length; + + out.max_abs_kappa_cost = w->max_abs_kappa * out.max_abs_kappa; + out.max_abs_dkappa_cost = w->max_abs_dkappa * out.max_abs_dkappa; + out.max_abs_a_cost = w->max_abs_a * out.max_abs_a; + out.max_abs_j_cost = w->max_abs_j * out.max_abs_j; + + out.kappa_cost = w->rms_kappa * out.kappa_rms; + out.dkappa_cost = w->rms_dkappa * out.dkappa_rms; + + out.accel_rms_cost = w->rms_a * (out.accel_rms / fmaxf (a_max, EPS)); + out.jerk_rms_cost = w->rms_j * (out.jerk_rms / fmaxf (j_max, EPS)); + + out.accel_violation_cost = w->violation_a * out.accel_violation; + out.jerk_violation_cost = w->violation_j * out.jerk_violation; + + { + float v0_err = m->v[0] - v_beg_target; + float vN_err = m->v[n - 1] - v_end_target; + float a0_err = m->a[0]; + float aN_err = m->a[n - 1]; + + float v0_den = fmaxf (1.0f, fabsf (v_beg_target)); + float vN_den = fmaxf (1.0f, fabsf (v_end_target)); + float a_den = fmaxf (a_max, EPS); + + float term = + safe_ratio_sq (v0_err, v0_den, 1e3f) + + safe_ratio_sq (vN_err, vN_den, 1e3f) + + safe_ratio_sq (a0_err, a_den, 1e3f) + + safe_ratio_sq (aN_err, a_den, 1e3f); + + out.terminal_cost = w->terminal * term; + } + + out.total_cost = + out.time_cost + + out.length_cost + + out.max_abs_kappa_cost + + out.max_abs_dkappa_cost + + out.max_abs_a_cost + + out.max_abs_j_cost + + out.kappa_cost + + out.dkappa_cost + + out.accel_rms_cost + + out.jerk_rms_cost + + out.accel_violation_cost + + out.jerk_violation_cost + + out.terminal_cost; + + return out; +} diff --git a/src/retiming.h b/src/retiming.h new file mode 100644 index 0000000..9a6e963 --- /dev/null +++ b/src/retiming.h @@ -0,0 +1,102 @@ +#ifndef INCLUDED_RETIMING_H +#define INCLUDED_RETIMING_H + +#include + +#define EPS 1e-8f + +#define PATH_SAMPLE_COUNT 100 + +typedef Vector2 bezier5[6]; + +struct path_table { + float max_abs_kappa; + // S = s[PATH_SAMPLE_COUNT - 1] + // T[i] = dr[i]/||dr[i]|| + // N[i] = { -T[i].y, T[i].x } + float u [PATH_SAMPLE_COUNT]; // Bezier parameter + Vector2 r [PATH_SAMPLE_COUNT]; // point on curve + Vector2 dr [PATH_SAMPLE_COUNT]; + Vector2 ddr [PATH_SAMPLE_COUNT]; + float s [PATH_SAMPLE_COUNT]; // arc length from start + float kappa [PATH_SAMPLE_COUNT]; // curvature + float dkappa_ds [PATH_SAMPLE_COUNT]; // curvature derivative +}; + +struct motion_profile { + float v_max; + float a_max; + float j_max; + float t[PATH_SAMPLE_COUNT]; // cumulative time at this node + float v[PATH_SAMPLE_COUNT]; // ds/dt + float a[PATH_SAMPLE_COUNT]; // d2s/dt2 + float j[PATH_SAMPLE_COUNT]; // d3s/dt3 +}; + +struct fitness_weights { + float time; + float length; + float max_abs_kappa; + float max_abs_dkappa; + float max_abs_a; + float max_abs_j; + float rms_kappa; + float rms_dkappa; + float rms_a; + float rms_j; + float violation_a; + float violation_j; + float terminal; +}; + +struct fitness_breakdown { + float total_cost; + + float time_cost; + float length_cost; + float max_abs_kappa_cost; + float max_abs_dkappa_cost; + float max_abs_a_cost; + float max_abs_j_cost; + float kappa_cost; + float dkappa_cost; + float accel_rms_cost; + float jerk_rms_cost; + float accel_violation_cost; + float jerk_violation_cost; + float terminal_cost; + float failure_cost; + + float duration; + float length; + float max_abs_kappa; + float max_abs_dkappa; + float max_abs_a; + float max_abs_j; + float kappa_rms; + float dkappa_rms; + float accel_rms; + float jerk_rms; + float accel_violation; + float jerk_violation; + + int feasible; +}; + +Vector2 bezier5_point (const bezier5, float u); +Vector2 bezier5_deriv1 (const bezier5, float u); +Vector2 bezier5_deriv2 (const bezier5, float u); +void build_path_table (struct path_table *, const bezier5); +int build_motion_profile (struct motion_profile *m, const struct path_table *p, + float v_beg, float v_end, + float v_max, float a_max, float j_max); +struct fitness_breakdown evaluate_motion_fitness ( + const struct path_table *, const struct motion_profile *, + float v_beg_target, + float v_end_target, + float v_max, + float a_max, + float j_max, + const struct fitness_weights *); + +#endif // INCLUDED_RETIMING_H -- cgit v1.3.1