aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorLibravatar Martin Michalec <martin@michalec.dev>2026-11-11 06:32:30 +0000
committerLibravatar Martin Michalec <martin@michalec.dev>2026-11-11 06:46:30 +0000
commit5b4a191d1cf310a3d7a99351e716a1a60004be69 (patch)
tree4b8d1a82765946f323a90f35344526110e778a3f /src
downloadcoursework-master.tar.gz
publishHEADmaster
Diffstat (limited to 'src')
-rw-r--r--src/bez7.c283
-rw-r--r--src/cma-es.c854
-rw-r--r--src/cma-es.h126
-rw-r--r--src/main.c593
-rw-r--r--src/retiming.c427
-rw-r--r--src/retiming.h102
6 files changed, 2385 insertions, 0 deletions
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 @@
1#include <stdlib.h>
2#include <stdio.h>
3#include <time.h>
4#include <raylib.h>
5#include <rlgl.h>
6#include <raymath.h>
7
8typedef Vector2 bezier7[8];
9
10struct input {
11 Vector2 r_beg;
12 Vector2 r_end;
13 Vector2 v_beg;
14 Vector2 v_end;
15 float v_max;
16 float a_max;
17 float j_max;
18};
19
20#define RGBA(HEX) (Color) { \
21 (HEX) >> 3*8 & 0xFF, \
22 (HEX) >> 2*8 & 0xFF, \
23 (HEX) >> 1*8 & 0xFF, \
24 (HEX) >> 0*8 & 0xFF, \
25 }
26
27// #define LABEL_WIDTH 140
28#define LABEL_WIDTH 300
29#define SLIDER_WIDTH 40
30#define ITEM_WIDTH (LABEL_WIDTH + SLIDER_WIDTH)
31#define ITEM_HEIGHT 15
32#define ITEM_MARGIN 5
33#define PANEL_WIDTH (ITEM_WIDTH + 2*ITEM_MARGIN)
34#define PANEL_HEIGHT(N) (RAYGUI_WINDOWBOX_STATUSBAR_HEIGHT + (N)*(ITEM_HEIGHT + ITEM_MARGIN) + ITEM_MARGIN)
35
36#ifdef DARK
37#define BACKGROUND RGBA (0x000000FF)
38#else
39#define BACKGROUND RGBA (0xFFFFFFFF)
40#endif
41
42#define ARROW_THICKNESS 2.5
43#define ARROW_LENGTH 15
44#define ARROW_ANGLE 10
45
46#define CONTROL_POINT_RADIUS 5
47#define CONTROL_POINT_RADIUS_FOCUSED 10
48
49
50void
51draw_arrow (Vector2 beg, Vector2 end, float thick, Color c)
52{
53 Vector2 off = Vector2Scale (Vector2Normalize (Vector2Subtract (end, beg)),
54 ARROW_LENGTH);
55 Vector2 ahl = Vector2Add (end, Vector2Rotate (off, +ARROW_ANGLE));
56 Vector2 ahr = Vector2Add (end, Vector2Rotate (off, -ARROW_ANGLE));
57
58 DrawLineEx (beg, end, thick, c);
59 DrawLineEx (end, ahl, thick, c);
60 DrawLineEx (end, ahr, thick, c);
61
62 DrawCircleV (beg, thick/2., c);
63 DrawCircleV (end, thick/2., c);
64 DrawCircleV (ahl, thick/2., c);
65 DrawCircleV (ahr, thick/2., c);
66}
67
68Vector2
69sample_bezier7 (const bezier7 pts, float t)
70{
71 float u = 1.0f - t;
72
73 float t2 = t * t;
74 float t3 = t2 * t;
75 float t4 = t3 * t;
76 float t5 = t4 * t;
77 float t6 = t5 * t;
78 float t7 = t6 * t;
79
80 /* Precompute powers of u (1 - t) */
81 float u2 = u * u;
82 float u3 = u2 * u;
83 float u4 = u3 * u;
84 float u5 = u4 * u;
85 float u6 = u5 * u;
86 float u7 = u6 * u;
87
88 /* Bernstein basis polynomials for degree 7 */
89 float b0 = u7;
90 float b1 = 7.0f * u6 * t;
91 float b2 = 21.0f * u5 * t2;
92 float b3 = 35.0f * u4 * t3;
93 float b4 = 35.0f * u3 * t4;
94 float b5 = 21.0f * u2 * t5;
95 float b6 = 7.0f * u * t6;
96 float b7 = t7;
97
98 Vector2 result;
99
100 /* Calculate final x and y by blending control points with basis weights */
101 result.x = (b0 * pts[0].x) + (b1 * pts[1].x) + (b2 * pts[2].x) + (b3 * pts[3].x) +
102 (b4 * pts[4].x) + (b5 * pts[5].x) + (b6 * pts[6].x) + (b7 * pts[7].x);
103
104 result.y = (b0 * pts[0].y) + (b1 * pts[1].y) + (b2 * pts[2].y) + (b3 * pts[3].y) +
105 (b4 * pts[4].y) + (b5 * pts[5].y) + (b6 * pts[6].y) + (b7 * pts[7].y);
106
107 return result;
108}
109
110void
111draw_bezier7 (bezier7 cp)
112{
113 char text[] = "P0";
114 DrawLineStrip (cp, 8, BLUE);
115 for (int i = 0; i < 8; ++i) {
116 DrawCircleLinesV (cp[i], 4, BLUE);
117 text[1] = '0' + i;
118 DrawText (text, cp[i].x - 5, cp[i].y + 7, 14, BLACK);
119 }
120
121 for (float t = 0; t <= 1; t += 0.01) {
122 DrawCircleV (sample_bezier7 (cp, t), 2, BLACK);
123 }
124}
125
126int
127main (int argc, char *argv[])
128{
129 srand (time (NULL));
130
131 SetConfigFlags (FLAG_MSAA_4X_HINT);
132 SetConfigFlags (FLAG_WINDOW_RESIZABLE);
133 InitWindow (800, 450, "GA");
134 SetTargetFPS (60);
135
136 Camera2D camera = {
137 .zoom = 1.0f,
138 };
139
140 Vector2 screen = {
141 .x = GetScreenWidth (),
142 .y = GetScreenHeight (),
143 };
144
145 struct input in = {
146 .r_beg = { 100, 100 },
147 // .r_end = { 100, 100 },
148 .r_end = { 300, 300 },
149 .v_beg = { 100, 10 },
150 .v_end = { 100, 10 },
151 .v_max = 250,
152 .a_max = 500,
153 .j_max = 16,
154 };
155
156 bezier7 cp;
157
158 float arrow_thickness = ARROW_THICKNESS;
159 float spline_thickness = ARROW_THICKNESS;
160 bool move_r_beg = false;
161 bool move_r_end = false;
162 bool move_v_beg = false;
163 bool move_v_end = false;
164 bool recompute = true;
165 bool show_fps = true;
166 bool show_menu = true;
167 bool show_graph = true;
168 bool draw_cp = true;
169 bool animate_sample_offset = false;
170 float animation_speed = 20;
171 int panel_item = 0;
172 bool resizing_graph = false;
173 int graph_height = screen.y/3;
174 float T = 10;
175 while (!WindowShouldClose ()) {
176 screen = (Vector2) {
177 .x = GetScreenWidth (),
178 .y = GetScreenHeight (),
179 };
180 float t = GetTime ();
181 float dt = GetFrameTime ();
182
183 if (IsMouseButtonDown (MOUSE_BUTTON_RIGHT)) {
184 Vector2 delta = GetMouseDelta ();
185 delta = Vector2Scale (delta, -1.0f/camera.zoom);
186 camera.target = Vector2Add (camera.target, delta);
187 }
188
189 if (IsKeyPressed (KEY_F)) show_fps = !show_fps;
190
191 if (IsKeyDown (KEY_LEFT )) T -= .1;
192 if (IsKeyDown (KEY_RIGHT)) T += .1;
193
194
195 if (1 || recompute) {
196 // chromosome_to_control_points (cp, in, ch);
197 cp[0] = in.r_beg;
198 cp[1] = Vector2Add (in.r_beg, Vector2Scale (in.v_beg, +1*T/7));
199 cp[2] = Vector2Add (in.r_beg, Vector2Scale (in.v_beg, +2*T/7));
200 cp[3] = Vector2Add (in.r_beg, Vector2Scale (in.v_beg, +3*T/7));
201 cp[4] = Vector2Add (in.r_end, Vector2Scale (in.v_end, -3*T/7));
202 cp[5] = Vector2Add (in.r_end, Vector2Scale (in.v_end, -2*T/7));
203 cp[6] = Vector2Add (in.r_end, Vector2Scale (in.v_end, -1*T/7));
204 cp[7] = in.r_end;
205 recompute = false;
206 }
207
208 float wheel = GetMouseWheelMove();
209 if (wheel != 0) {
210 Vector2 offset = GetMousePosition ();
211 camera.target = GetScreenToWorld2D (offset, camera);
212 camera.offset = offset;
213 camera.zoom = Clamp (expf (logf (camera.zoom) + .2*wheel), .125, 64);
214 }
215
216 Vector2 mouse_hud = GetMousePosition ();
217 Vector2 mouse = GetScreenToWorld2D (mouse_hud, camera);
218
219 BeginDrawing ();
220 ClearBackground (BACKGROUND);
221 BeginMode2D (camera);
222
223 if (CheckCollisionPointCircle (mouse, in.r_beg, 10)) {
224 DrawCircleLinesV (in.r_beg, 10, BLUE);
225 if (!move_v_beg && IsMouseButtonDown (MOUSE_BUTTON_LEFT))
226 move_r_beg = true;
227 } else if (CheckCollisionPointCircle (mouse, in.r_end, 10)) {
228 DrawCircleLinesV (in.r_end, 10, BLUE);
229 if (!move_v_end && IsMouseButtonDown (MOUSE_BUTTON_LEFT))
230 move_r_end = true;
231 } else if (CheckCollisionPointCircle (mouse, Vector2Add (in.r_beg, in.v_beg), 10)) {
232 DrawCircleLinesV (Vector2Add (in.r_beg, in.v_beg), 10, BLUE);
233 if (!move_r_beg && IsMouseButtonDown (MOUSE_BUTTON_LEFT))
234 move_v_beg = true;
235 } else if (CheckCollisionPointCircle (mouse, Vector2Add (in.r_end, in.v_end), 10)) {
236 DrawCircleLinesV (Vector2Add (in.r_end, in.v_end), 10, BLUE);
237 if (!move_r_end && IsMouseButtonDown (MOUSE_BUTTON_LEFT))
238 move_v_end = true;
239 }
240
241 if (move_r_beg) {
242 in.r_beg = mouse;
243 if (IsMouseButtonReleased (MOUSE_BUTTON_LEFT))
244 move_r_beg = false;
245 }
246 if (move_r_end) {
247 in.r_end = mouse;
248 if (IsMouseButtonReleased (MOUSE_BUTTON_LEFT))
249 move_r_end = false;
250 }
251 if (move_v_beg) {
252 in.v_beg = Vector2Subtract (mouse, in.r_beg);
253 if (IsMouseButtonReleased (MOUSE_BUTTON_LEFT))
254 move_v_beg = false;
255 }
256 if (move_v_end) {
257 in.v_end = Vector2Subtract (mouse, in.r_end);
258 if (IsMouseButtonReleased (MOUSE_BUTTON_LEFT))
259 move_v_end = false;
260 }
261
262 draw_bezier7 (cp);
263 draw_arrow (in.r_beg, Vector2Add (in.r_beg, in.v_beg), arrow_thickness, GREEN);
264 draw_arrow (in.r_end, Vector2Add (in.r_end, in.v_end), arrow_thickness, RED);
265
266 EndMode2D ();
267
268 if (move_r_beg ||
269 move_r_end ||
270 move_v_beg ||
271 move_v_end) {
272 recompute = true;
273 }
274
275 if (show_fps)
276 DrawFPS (screen.x - 75, 0);
277 EndDrawing ();
278 }
279
280 CloseWindow ();
281
282 return EXIT_SUCCESS;
283}
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 @@
1#include <math.h>
2#include <float.h>
3#include <stdint.h>
4#include <stdlib.h>
5#include <string.h>
6
7#include "retiming.h"
8#include "cma-es.h"
9
10#ifndef EPS
11#define EPS 1e-6f
12#endif
13
14#ifndef CMA_PI
15#define CMA_PI 3.14159265358979323846
16#endif
17
18/* -----------------------------
19 Basic vector helpers
20 ----------------------------- */
21
22static inline Vector2
23v2_add (Vector2 a, Vector2 b)
24{
25 Vector2 r = { a.x + b.x, a.y + b.y };
26 return r;
27}
28
29static inline Vector2
30v2_sub (Vector2 a, Vector2 b)
31{
32 Vector2 r = { a.x - b.x, a.y - b.y };
33 return r;
34}
35
36static inline Vector2
37v2_scale (Vector2 a, float s)
38{
39 Vector2 r = { a.x * s, a.y * s };
40 return r;
41}
42
43static inline float
44v2_dot (Vector2 a, Vector2 b)
45{
46 return a.x*b.x + a.y*b.y;
47}
48
49static inline float
50v2_len (Vector2 a)
51{
52 return sqrtf (fmaxf (0.0f, v2_dot (a, a)));
53}
54
55static inline Vector2
56v2_perp_left (Vector2 a)
57{
58 Vector2 r = { -a.y, +a.x };
59 return r;
60}
61
62static inline Vector2
63v2_normalize_safe (Vector2 a, Vector2 fallback)
64{
65 float la = v2_len (a);
66 if (la > EPS)
67 return v2_scale (a, 1.0f / la);
68
69 float lf = v2_len (fallback);
70 if (lf > EPS)
71 return v2_scale (fallback, 1.0f / lf);
72
73 {
74 Vector2 ex = { 1.0f, 0.0f };
75 return ex;
76 }
77}
78
79// void
80// chromosome_to_control_points (bezier5 cp, struct input in, struct chromosome ch)
81// {
82// Vector2 chord = v2_sub (in.r_end, in.r_beg);
83// Vector2 e_ref = v2_normalize_safe (chord, (Vector2){ 1.0f, 0.0f });
84//
85// Vector2 e_beg = v2_normalize_safe (in.v_beg, e_ref);
86// Vector2 e_end = v2_normalize_safe (in.v_end, e_ref);
87//
88// Vector2 n_beg = v2_perp_left (e_beg);
89// Vector2 n_end = v2_perp_left (e_end);
90//
91// cp[0] = in.r_beg;
92// cp[1] = v2_add (in.r_beg, v2_scale (e_beg, +ch.rho * ch.tau_1));
93// cp[2] = v2_add (in.r_beg,
94// v2_scale (v2_add (v2_scale (e_beg, ch.alp_2),
95// v2_scale (n_beg, ch.bet_2)),
96// +ch.rho));
97// cp[3] = v2_add (in.r_end,
98// v2_scale (v2_add (v2_scale (e_end, ch.alp_3),
99// v2_scale (n_end, ch.bet_3)),
100// -ch.rho));
101// cp[4] = v2_add (in.r_end, v2_scale (e_end, -ch.rho * ch.tau_4));
102// cp[5] = in.r_end;
103// }
104
105/* -----------------------------
106 CMA-side chromosome transform
107 Search in latent z \in R^7,
108 decode to valid chromosome.
109 ----------------------------- */
110
111static inline struct chromosome_cma_config
112chromosome_cma_default_config (void)
113{
114 struct chromosome_cma_config c;
115 c.rho_min_rel = 0.05f;
116 c.rho_max_rel = 5.00f;
117 c.tau_min = 0.05f;
118 c.alp_limit = 5.00f;
119 c.bet_limit = 5.00f;
120 return c;
121}
122
123static inline float
124clampf (float x, float lo, float hi)
125{
126 return x < lo ? lo : (x > hi ? hi : x);
127}
128
129static inline float
130sigmoidf (float x)
131{
132 if (x >= 0.0f) {
133 float e = expf (-x);
134 return 1.0f / (1.0f + e);
135 } else {
136 float e = expf (x);
137 return e / (1.0f + e);
138 }
139}
140
141static inline float
142logitf (float p)
143{
144 p = clampf (p, 1e-6f, 1.0f - 1e-6f);
145 return logf (p / (1.0f - p));
146}
147
148static inline float
149atanh_safe (float x)
150{
151 x = clampf (x, -0.999999f, 0.999999f);
152 return 0.5f * logf ((1.0f + x) / (1.0f - x));
153}
154
155static inline float
156map01 (float s, float lo, float hi)
157{
158 return lo + (hi - lo) * s;
159}
160
161void
162cma_decode_chromosome (struct chromosome *ch,
163 const float z[CMA_DIM],
164 const struct input *in,
165 const struct chromosome_cma_config *cfg)
166{
167 float D = v2_len (v2_sub (in->r_end, in->r_beg));
168 if (D < EPS) D = fmaxf (v2_len (in->v_beg), v2_len (in->v_end));
169
170 {
171 float s_rho = sigmoidf (z[0]);
172 ch->rho = D * map01 (s_rho, cfg->rho_min_rel, cfg->rho_max_rel);
173 }
174
175 {
176 float s1 = sigmoidf (z[1]);
177 float tau1_max = 1.0f - cfg->tau_min;
178 tau1_max = fmaxf (tau1_max, cfg->tau_min + 1e-3f);
179 ch->tau_1 = map01 (s1, cfg->tau_min, tau1_max);
180
181 float s6 = sigmoidf (z[6]);
182 float tau4_max = 1.0f - cfg->tau_min;
183 tau1_max = fmaxf (tau4_max, cfg->tau_min + 1e-3f);
184 ch->tau_4 = map01 (s6, cfg->tau_min, tau4_max);
185 }
186
187 ch->alp_2 = cfg->alp_limit * tanhf (z[2]);
188 ch->bet_2 = cfg->bet_limit * tanhf (z[3]);
189 ch->alp_3 = cfg->alp_limit * tanhf (z[4]);
190 ch->bet_3 = cfg->bet_limit * tanhf (z[5]);
191}
192
193void
194cma_encode_chromosome (float z[CMA_DIM],
195 const struct chromosome *ch_in,
196 const struct input *in,
197 const struct chromosome_cma_config *cfg)
198{
199 struct chromosome ch = *ch_in;
200 float D = v2_len (v2_sub (in->r_end, in->r_beg));
201 if (D < EPS) D = fmaxf (v2_len (in->v_beg), v2_len (in->v_end));
202
203 {
204 float rho_rel = ch.rho / D;
205 float s = (rho_rel - cfg->rho_min_rel) /
206 fmaxf (cfg->rho_max_rel - cfg->rho_min_rel, EPS);
207 z[0] = logitf (s);
208 }
209
210 {
211 float tau1_max = 1.0f - cfg->tau_min;
212 tau1_max = fmaxf (tau1_max, cfg->tau_min + 1e-3f);
213 ch.tau_1 = clampf (ch.tau_1, cfg->tau_min, tau1_max);
214
215 {
216 float s1 = (ch.tau_1 - cfg->tau_min) /
217 fmaxf (tau1_max - cfg->tau_min, EPS);
218 z[1] = logitf (s1);
219 }
220
221 float tau4_max = 1.0f - cfg->tau_min;
222 tau4_max = fmaxf (tau1_max, cfg->tau_min + 1e-3f);
223 ch.tau_4 = clampf (ch.tau_4, cfg->tau_min, tau4_max);
224
225 {
226 float s6 = (ch.tau_4 - cfg->tau_min) /
227 fmaxf (tau4_max - cfg->tau_min, EPS);
228 z[6] = logitf (s6);
229 }
230 }
231
232 z[2] = atanh_safe (clampf (ch.alp_2 / fmaxf (cfg->alp_limit, EPS), -0.999999f, 0.999999f));
233 z[3] = atanh_safe (clampf (ch.bet_2 / fmaxf (cfg->bet_limit, EPS), -0.999999f, 0.999999f));
234 z[4] = atanh_safe (clampf (ch.alp_3 / fmaxf (cfg->alp_limit, EPS), -0.999999f, 0.999999f));
235 z[5] = atanh_safe (clampf (ch.bet_3 / fmaxf (cfg->bet_limit, EPS), -0.999999f, 0.999999f));
236}
237
238static inline uint64_t
239cma_rng_next_u64 (struct cma_rng *r)
240{
241 uint64_t x = r->state;
242 x ^= x >> 12;
243 x ^= x << 25;
244 x ^= x >> 27;
245 r->state = x;
246 return x * UINT64_C(2685821657736338717);
247}
248
249static inline void
250cma_rng_seed (struct cma_rng *r, uint64_t seed)
251{
252 if (seed == 0) seed = UINT64_C(0x9e3779b97f4a7c15);
253 r->state = seed;
254 if (r->state == 0) r->state = UINT64_C(0x123456789abcdef);
255 r->has_spare = 0;
256 r->spare = 0.0f;
257}
258
259static inline float
260cma_rng_uniform01 (struct cma_rng *r)
261{
262 uint64_t x = cma_rng_next_u64 (r);
263 return (float)((x >> 11) * (1.0 / 9007199254740992.0));
264}
265
266static inline float
267cma_rng_normal (struct cma_rng *r)
268{
269 if (r->has_spare) {
270 r->has_spare = 0;
271 return r->spare;
272 }
273
274 for (;;) {
275 float u1 = cma_rng_uniform01 (r);
276 float u2 = cma_rng_uniform01 (r);
277
278 if (u1 > 1e-12f) {
279 float mag = sqrtf (-2.0f * logf (u1));
280 float ang = 2.0f * (float)CMA_PI * u2;
281
282 r->spare = mag * sinf (ang);
283 r->has_spare = 1;
284 return mag * cosf (ang);
285 }
286 }
287}
288
289#define MIDX(i,j,n) ((i)*(n) + (j))
290
291static void
292mat_identity (float *A, int n)
293{
294 memset (A, 0, (size_t)n * (size_t)n * sizeof (*A));
295 for (int i = 0; i < n; ++i)
296 A[MIDX(i,i,n)] = 1.0f;
297}
298
299static void
300mat_copy (float *dst, const float *src, int n)
301{
302 memcpy (dst, src, (size_t)n * (size_t)n * sizeof (*dst));
303}
304
305static void
306vec_copy (float *dst, const float *src, int n)
307{
308 memcpy (dst, src, (size_t)n * sizeof (*dst));
309}
310
311static void
312vec_set_zero (float *x, int n)
313{
314 memset (x, 0, (size_t)n * sizeof (*x));
315}
316
317static float
318vec_dot (const float *a, const float *b, int n)
319{
320 float s = 0.0f;
321 for (int i = 0; i < n; ++i)
322 s += a[i] * b[i];
323 return s;
324}
325
326static float
327vec_norm (const float *a, int n)
328{
329 return sqrtf (fmaxf (0.0f, vec_dot (a, a, n)));
330}
331
332static void
333mat_vec_mul (float *y, const float *A, const float *x, int n)
334{
335 for (int i = 0; i < n; ++i) {
336 float s = 0.0f;
337 for (int j = 0; j < n; ++j)
338 s += A[MIDX(i,j,n)] * x[j];
339 y[i] = s;
340 }
341}
342
343static void
344symmetrize (float *A, int n)
345{
346 for (int i = 0; i < n; ++i) {
347 for (int j = i + 1; j < n; ++j) {
348 float s = 0.5f * (A[MIDX(i,j,n)] + A[MIDX(j,i,n)]);
349 A[MIDX(i,j,n)] = s;
350 A[MIDX(j,i,n)] = s;
351 }
352 }
353}
354
355/* Jacobi eigendecomposition for symmetric A.
356 On output:
357 - eval[i] are eigenvalues
358 - V(:,i) is eigenvector i
359*/
360static void
361jacobi_eigen_symmetric (float *A, float *V, float *eval, int n)
362{
363 mat_identity (V, n);
364
365 for (int sweep = 0; sweep < 64 * n * n; ++sweep) {
366 int p = 0, q = 1;
367 float max_off = fabsf (A[MIDX(0,1,n)]);
368
369 for (int i = 0; i < n; ++i) {
370 for (int j = i + 1; j < n; ++j) {
371 float aij = fabsf (A[MIDX(i,j,n)]);
372 if (aij > max_off) {
373 max_off = aij;
374 p = i;
375 q = j;
376 }
377 }
378 }
379
380 if (max_off < 1e-12f)
381 break;
382
383 {
384 float app = A[MIDX(p,p,n)];
385 float aqq = A[MIDX(q,q,n)];
386 float apq = A[MIDX(p,q,n)];
387
388 float phi = 0.5f * atan2f (2.0f * apq, aqq - app);
389 float c = cosf (phi);
390 float s = sinf (phi);
391
392 for (int k = 0; k < n; ++k) {
393 float aik = A[MIDX(p,k,n)];
394 float aqk = A[MIDX(q,k,n)];
395 A[MIDX(p,k,n)] = c*aik - s*aqk;
396 A[MIDX(q,k,n)] = s*aik + c*aqk;
397 }
398
399 for (int k = 0; k < n; ++k) {
400 float akp = A[MIDX(k,p,n)];
401 float akq = A[MIDX(k,q,n)];
402 A[MIDX(k,p,n)] = c*akp - s*akq;
403 A[MIDX(k,q,n)] = s*akp + c*akq;
404 }
405
406 for (int k = 0; k < n; ++k) {
407 float vkp = V[MIDX(k,p,n)];
408 float vkq = V[MIDX(k,q,n)];
409 V[MIDX(k,p,n)] = c*vkp - s*vkq;
410 V[MIDX(k,q,n)] = s*vkp + c*vkq;
411 }
412 }
413 }
414
415 for (int i = 0; i < n; ++i)
416 eval[i] = A[MIDX(i,i,n)];
417
418 /* sort ascending eigenvalues */
419 for (int i = 0; i < n - 1; ++i) {
420 int best = i;
421 for (int j = i + 1; j < n; ++j)
422 if (eval[j] < eval[best]) best = j;
423
424 if (best != i) {
425 float tmp = eval[i];
426 eval[i] = eval[best];
427 eval[best] = tmp;
428
429 for (int k = 0; k < n; ++k) {
430 float tv = V[MIDX(k,i,n)];
431 V[MIDX(k,i,n)] = V[MIDX(k,best,n)];
432 V[MIDX(k,best,n)] = tv;
433 }
434 }
435 }
436}
437
438/* -----------------------------
439 CMA-ES core
440 ----------------------------- */
441
442int
443cmaes_default_lambda (int n)
444{
445 return 4 + (int)floorf (3.0f * logf ((float)n));
446}
447
448float
449cmaes_expected_norm (int n)
450{
451 float nf = (float)n;
452 return sqrtf (nf) * (1.0f - 1.0f/(4.0f*nf) + 1.0f/(21.0f*nf*nf));
453}
454
455int
456cmaes_init (struct cmaes *es,
457 int n,
458 const float *mean0,
459 float sigma0,
460 int lambda,
461 uint64_t seed)
462{
463 memset (es, 0, sizeof (*es));
464
465 if (n <= 0) return 0;
466 if (sigma0 <= 0.0f) return 0;
467
468 es->n = n;
469 es->lambda = (lambda > 0) ? lambda : cmaes_default_lambda (n);
470 es->mu = es->lambda / 2;
471 es->sigma = sigma0;
472 es->generation = 0;
473 es->evaluations = 0;
474 es->chi_n = cmaes_expected_norm (n);
475
476 es->weights = (float*)calloc ((size_t)es->mu, sizeof (float));
477 es->xmean = (float*)calloc ((size_t)n, sizeof (float));
478 es->xold = (float*)calloc ((size_t)n, sizeof (float));
479 es->pc = (float*)calloc ((size_t)n, sizeof (float));
480 es->ps = (float*)calloc ((size_t)n, sizeof (float));
481 es->C = (float*)calloc ((size_t)n*(size_t)n, sizeof (float));
482 es->B = (float*)calloc ((size_t)n*(size_t)n, sizeof (float));
483 es->D = (float*)calloc ((size_t)n, sizeof (float));
484 es->BD = (float*)calloc ((size_t)n*(size_t)n, sizeof (float));
485 es->invsqrtC= (float*)calloc ((size_t)n*(size_t)n, sizeof (float));
486 es->ary = (float*)calloc ((size_t)es->lambda*(size_t)n, sizeof (float));
487 es->arx = (float*)calloc ((size_t)es->lambda*(size_t)n, sizeof (float));
488 es->fitness = (float*)calloc ((size_t)es->lambda, sizeof (float));
489 es->index = (int*)calloc ((size_t)es->lambda, sizeof (int));
490
491 if (!es->weights || !es->xmean || !es->xold || !es->pc || !es->ps ||
492 !es->C || !es->B || !es->D || !es->BD || !es->invsqrtC ||
493 !es->ary || !es->arx || !es->fitness || !es->index) {
494 return 0;
495 }
496
497 vec_copy (es->xmean, mean0, n);
498 vec_set_zero (es->xold, n);
499 vec_set_zero (es->pc, n);
500 vec_set_zero (es->ps, n);
501
502 {
503 float wsum = 0.0f;
504 for (int i = 0; i < es->mu; ++i) {
505 es->weights[i] = logf ((float)es->mu + 0.5f) - logf ((float)(i + 1));
506 wsum += es->weights[i];
507 }
508
509 es->mueff = 0.0f;
510 for (int i = 0; i < es->mu; ++i) {
511 es->weights[i] /= wsum;
512 es->mueff += es->weights[i] * es->weights[i];
513 }
514 es->mueff = 1.0f / fmaxf (es->mueff, EPS);
515 }
516
517 {
518 float nf = (float)n;
519 es->cc = (4.0f + es->mueff / nf) / (nf + 4.0f + 2.0f * es->mueff / nf);
520 es->cs = (es->mueff + 2.0f) / (nf + es->mueff + 5.0f);
521 es->c1 = 2.0f / (((nf + 1.3f)*(nf + 1.3f)) + es->mueff);
522 es->cmu = fminf (1.0f - es->c1,
523 2.0f * (es->mueff - 2.0f + 1.0f/es->mueff) /
524 (((nf + 2.0f)*(nf + 2.0f)) + es->mueff));
525 es->damps = 1.0f + 2.0f * fmaxf (0.0f, sqrtf ((es->mueff - 1.0f)/(nf + 1.0f)) - 1.0f)
526 + es->cs;
527 }
528
529 mat_identity (es->C, n);
530 mat_identity (es->B, n);
531 mat_identity (es->BD, n);
532 mat_identity (es->invsqrtC, n);
533 for (int i = 0; i < n; ++i)
534 es->D[i] = 1.0f;
535
536 cma_rng_seed (&es->rng, seed);
537 return 1;
538}
539
540void
541cmaes_free (struct cmaes *es)
542{
543 free (es->weights);
544 free (es->xmean);
545 free (es->xold);
546 free (es->pc);
547 free (es->ps);
548 free (es->C);
549 free (es->B);
550 free (es->D);
551 free (es->BD);
552 free (es->invsqrtC);
553 free (es->ary);
554 free (es->arx);
555 free (es->fitness);
556 free (es->index);
557 memset (es, 0, sizeof (*es));
558}
559
560static void
561cmaes_update_eigensystem (struct cmaes *es)
562{
563 int n = es->n;
564 float *tmp = (float*)calloc ((size_t)n*(size_t)n, sizeof (float));
565 float *eval = (float*)calloc ((size_t)n, sizeof (float));
566
567 if (!tmp || !eval) {
568 free (tmp);
569 free (eval);
570 return;
571 }
572
573 symmetrize (es->C, n);
574 mat_copy (tmp, es->C, n);
575 jacobi_eigen_symmetric (tmp, es->B, eval, n);
576
577 for (int i = 0; i < n; ++i)
578 es->D[i] = sqrtf (fmaxf (eval[i], 1e-20f));
579
580 for (int i = 0; i < n; ++i) {
581 for (int j = 0; j < n; ++j)
582 es->BD[MIDX(i,j,n)] = es->B[MIDX(i,j,n)] * es->D[j];
583 }
584
585 for (int i = 0; i < n; ++i) {
586 for (int j = 0; j < n; ++j) {
587 float s = 0.0f;
588 for (int k = 0; k < n; ++k)
589 s += es->B[MIDX(i,k,n)] * (1.0f / es->D[k]) * es->B[MIDX(j,k,n)];
590 es->invsqrtC[MIDX(i,j,n)] = s;
591 }
592 }
593
594 free (tmp);
595 free (eval);
596}
597
598void
599cmaes_ask (struct cmaes *es)
600{
601 int n = es->n;
602
603 for (int k = 0; k < es->lambda; ++k) {
604 float z[CMA_DIM]; /* n=7 in your use-case */
605 float *y = &es->ary[k*n];
606 float *x = &es->arx[k*n];
607
608 for (int j = 0; j < n; ++j)
609 z[j] = cma_rng_normal (&es->rng);
610
611 mat_vec_mul (y, es->BD, z, n);
612
613 for (int j = 0; j < n; ++j)
614 x[j] = es->xmean[j] + es->sigma * y[j];
615 }
616}
617
618void
619cmaes_sort_indices (struct cmaes *es)
620{
621 for (int i = 0; i < es->lambda; ++i)
622 es->index[i] = i;
623
624 for (int i = 1; i < es->lambda; ++i) {
625 int key = es->index[i];
626 float fkey = es->fitness[key];
627 int j = i - 1;
628
629 while (j >= 0 && es->fitness[es->index[j]] > fkey) {
630 es->index[j + 1] = es->index[j];
631 --j;
632 }
633 es->index[j + 1] = key;
634 }
635}
636
637void
638cmaes_tell (struct cmaes *es, const float *fitness)
639{
640 int n = es->n;
641 memcpy (es->fitness, fitness, (size_t)es->lambda * sizeof (*fitness));
642 cmaes_sort_indices (es);
643
644 vec_copy (es->xold, es->xmean, n);
645 vec_set_zero (es->xmean, n);
646
647 for (int i = 0; i < es->mu; ++i) {
648 const float *x = &es->arx[es->index[i] * n];
649 float w = es->weights[i];
650 for (int j = 0; j < n; ++j)
651 es->xmean[j] += w * x[j];
652 }
653
654 {
655 float y_w[CMA_DIM];
656 float z_w[CMA_DIM];
657 float coeff_ps = sqrtf (es->cs * (2.0f - es->cs) * es->mueff);
658 float coeff_pc = sqrtf (es->cc * (2.0f - es->cc) * es->mueff);
659
660 for (int j = 0; j < n; ++j)
661 y_w[j] = (es->xmean[j] - es->xold[j]) / fmaxf (es->sigma, EPS);
662
663 mat_vec_mul (z_w, es->invsqrtC, y_w, n);
664
665 for (int j = 0; j < n; ++j)
666 es->ps[j] = (1.0f - es->cs) * es->ps[j] + coeff_ps * z_w[j];
667
668 {
669 float norm_ps = vec_norm (es->ps, n);
670 float denom = sqrtf (1.0f - powf (1.0f - es->cs, 2.0f * (es->generation + 1)));
671 float left = norm_ps / fmaxf (denom * es->chi_n, EPS);
672 int hsig = left < (1.4f + 2.0f / ((float)n + 1.0f));
673
674 for (int j = 0; j < n; ++j)
675 es->pc[j] = (1.0f - es->cc) * es->pc[j] + (hsig ? coeff_pc * y_w[j] : 0.0f);
676
677 {
678 float alpha = 1.0f - es->c1 - es->cmu
679 + (hsig ? 0.0f : es->c1 * es->cc * (2.0f - es->cc));
680
681 for (int i = 0; i < n; ++i) {
682 for (int j = 0; j < n; ++j)
683 es->C[MIDX(i,j,n)] *= alpha;
684 }
685
686 for (int i = 0; i < n; ++i) {
687 for (int j = 0; j < n; ++j)
688 es->C[MIDX(i,j,n)] += es->c1 * es->pc[i] * es->pc[j];
689 }
690
691 for (int a = 0; a < es->mu; ++a) {
692 const float *y = &es->ary[es->index[a] * n];
693 float w = es->weights[a];
694 for (int i = 0; i < n; ++i) {
695 for (int j = 0; j < n; ++j)
696 es->C[MIDX(i,j,n)] += es->cmu * w * y[i] * y[j];
697 }
698 }
699
700 symmetrize (es->C, n);
701
702 for (int i = 0; i < n; ++i)
703 es->C[MIDX(i,i,n)] = fmaxf (es->C[MIDX(i,i,n)], 1e-20f);
704 }
705
706 es->sigma *= expf ((es->cs / es->damps) * (norm_ps / es->chi_n - 1.0f));
707 }
708 }
709
710 es->generation += 1;
711 es->evaluations += (uint64_t)es->lambda;
712
713 cmaes_update_eigensystem (es);
714}
715
716const float *
717cmaes_candidate (const struct cmaes *es, int k)
718{
719 return &es->arx[k * es->n];
720}
721
722int
723cmaes_should_stop (const struct cmaes *es)
724{
725 if (!isfinite (es->sigma) || es->sigma < 1e-10f)
726 return 1;
727
728 for (int i = 0; i < es->n; ++i) {
729 if (!isfinite (es->D[i]))
730 return 1;
731 }
732
733 return 0;
734}
735
736struct cmaes_result
737cmaes_run (struct cmaes *es,
738 int max_generations,
739 cma_objective_fn objective,
740 void *userdata)
741{
742 struct cmaes_result out;
743 out.best_f = FLT_MAX;
744 out.best_generation = -1;
745 for (int i = 0; i < es->n; ++i) out.best_x[i] = es->xmean[i];
746
747 for (int gen = 0; gen < max_generations; ++gen) {
748 cmaes_ask (es);
749
750 for (int k = 0; k < es->lambda; ++k) {
751 const float *x = cmaes_candidate (es, k);
752 float f = objective (x, es->n, userdata);
753 if (!isfinite (f)) f = 1e30f;
754 es->fitness[k] = f;
755
756 if (f < out.best_f) {
757 out.best_f = f;
758 out.best_generation = es->generation;
759 for (int j = 0; j < es->n; ++j)
760 out.best_x[j] = x[j];
761 }
762 }
763
764 cmaes_tell (es, es->fitness);
765
766 if (cmaes_should_stop (es))
767 break;
768 }
769
770 return out;
771}
772
773float
774spline_cma_objective (const float *z, int n, void *userdata)
775{
776 (void)n;
777
778 struct spline_objective_ctx *ctx = (struct spline_objective_ctx*)userdata;
779 struct chromosome ch;
780 bezier5 cp;
781 struct path_table p;
782 struct motion_profile m;
783
784 cma_decode_chromosome (&ch, z, &ctx->in, &ctx->cfg);
785 chromosome_to_control_points (cp, ctx->in, ch);
786
787 build_path_table (&p, cp);
788
789 {
790 float v_beg = v2_len (ctx->in.v_beg);
791 float v_end = v2_len (ctx->in.v_end);
792
793 int ok = build_motion_profile (&m, &p,
794 v_beg, v_end,
795 ctx->in.v_max,
796 ctx->in.a_max,
797 ctx->in.j_max);
798
799 {
800 struct fitness_breakdown fb =
801 evaluate_motion_fitness (&p, &m,
802 v_beg, v_end,
803 ctx->in.v_max,
804 ctx->in.a_max,
805 ctx->in.j_max,
806 ctx->weights);
807
808 if (!isfinite (fb.total_cost))
809 return ctx->hard_fail_cost;
810
811 return fb.total_cost;
812 }
813 }
814}
815
816void
817example_cmaes_usage (const struct input *in,
818 const struct chromosome *nominal_chromosome,
819 const struct fitness_weights *weights,
820 struct chromosome *best_chromosome_out,
821 float *best_cost_out)
822{
823 struct chromosome_cma_config cfg = chromosome_cma_default_config ();
824 float mean0[CMA_DIM];
825 struct cmaes es;
826 struct spline_objective_ctx ctx;
827 struct cmaes_result result;
828
829 cma_encode_chromosome (mean0, nominal_chromosome, in, &cfg);
830
831 /* Good starting point for 7D */
832 if (!cmaes_init (&es,
833 CMA_DIM,
834 mean0,
835 1.20f, /* sigma0 */
836 12, /* lambda */
837 1234567u /* seed */
838 )) {
839 /* handle allocation/init failure */
840 return;
841 }
842
843 ctx.in = *in;
844 ctx.cfg = cfg;
845 ctx.weights = weights;
846 ctx.hard_fail_cost = 1e9f;
847
848 result = cmaes_run (&es, 100, spline_cma_objective, &ctx);
849
850 cma_decode_chromosome (best_chromosome_out, result.best_x, in, &cfg);
851 if (best_cost_out) *best_cost_out = result.best_f;
852
853 cmaes_free (&es);
854}
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 @@
1#ifndef INCLUDED_CMA_ES_H
2#define INCLUDED_CMA_ES_H
3
4#include <stdint.h>
5
6#define CMA_DIM 7
7
8struct input {
9 Vector2 r_beg;
10 Vector2 r_end;
11 Vector2 v_beg;
12 Vector2 v_end;
13 float v_max;
14 float a_max;
15 float j_max;
16};
17
18struct chromosome {
19 float rho;
20 float tau_1;
21 float alp_2;
22 float bet_2;
23 float alp_3;
24 float bet_3;
25 float tau_4;
26};
27
28struct cmaes_result {
29 float best_x[CMA_DIM];
30 float best_f;
31 int best_generation;
32};
33
34struct chromosome_cma_config {
35 /* rho = D * [rho_min_rel, rho_max_rel] */
36 float rho_min_rel;
37 float rho_max_rel;
38
39 /* tau in [tau_min, 1 - tau_min] */
40 float tau_min;
41
42 /* alpha / beta bounds */
43 float alp_limit;
44 float bet_limit;
45};
46
47struct spline_objective_ctx {
48 struct input in;
49 struct chromosome_cma_config cfg;
50 const struct fitness_weights *weights;
51 float hard_fail_cost;
52};
53
54typedef float (*cma_objective_fn) (const float *x, int n, void *userdata);
55
56struct cma_rng {
57 uint64_t state;
58 int has_spare;
59 float spare;
60};
61
62struct cmaes {
63 int n;
64 int lambda;
65 int mu;
66
67 int generation;
68 uint64_t evaluations;
69
70 float sigma;
71 float chi_n;
72 float mueff;
73
74 float cc, cs, c1, cmu, damps;
75
76 float *weights; /* mu */
77
78 float *xmean; /* n */
79 float *xold; /* n */
80 float *pc; /* n */
81 float *ps; /* n */
82
83 float *C; /* n*n */
84 float *B; /* n*n */
85 float *D; /* n */
86 float *BD; /* n*n */
87 float *invsqrtC; /* n*n */
88
89 float *ary; /* lambda*n : y_k = B D z_k */
90 float *arx; /* lambda*n : x_k = mean + sigma*y_k */
91
92 float *fitness; /* lambda */
93 int *index; /* lambda */
94
95 struct cma_rng rng;
96};
97
98void chromosome_to_control_points (bezier5, struct input, struct chromosome);
99void cma_decode_chromosome (struct chromosome *,
100 const float z[CMA_DIM],
101 const struct input *,
102 const struct chromosome_cma_config *);
103void cma_encode_chromosome (float z[CMA_DIM], const struct chromosome *,
104 const struct input *,
105 const struct chromosome_cma_config *);
106
107int cmaes_default_lambda (int n);
108float cmaes_expected_norm (int n);
109int cmaes_init (struct cmaes *, int n, const float *mean0, float sigma0,
110 int lambda, uint64_t seed);
111void cmaes_free (struct cmaes *);
112void cmaes_ask (struct cmaes *);
113void cmaes_sort_indices (struct cmaes *);
114void cmaes_tell (struct cmaes *, const float *fitness);
115const float *cmaes_candidate (const struct cmaes *es, int k);
116int cmaes_should_stop (const struct cmaes *);
117struct cmaes_result cmaes_run (struct cmaes *, int max_generations,
118 cma_objective_fn objective, void *userdata);
119float spline_cma_objective (const float *z, int n, void *userdata);
120void example_cmaes_usage (const struct input *,
121 const struct chromosome *nominal,
122 const struct fitness_weights *,
123 struct chromosome *best_chromosome_out,
124 float *best_cost_out);
125
126#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 @@
1#include <stdlib.h>
2#include <stdio.h>
3#include <time.h>
4#include <raylib.h>
5#include <rlgl.h>
6#include <raymath.h>
7
8#define RAYGUI_IMPLEMENTATION
9#include <raygui.h>
10
11#include "retiming.h"
12#include "cma-es.h"
13
14#define RGBA(HEX) (Color) { \
15 (HEX) >> 3*8 & 0xFF, \
16 (HEX) >> 2*8 & 0xFF, \
17 (HEX) >> 1*8 & 0xFF, \
18 (HEX) >> 0*8 & 0xFF, \
19 }
20
21// #define LABEL_WIDTH 140
22#define LABEL_WIDTH 300
23#define SLIDER_WIDTH 40
24#define ITEM_WIDTH (LABEL_WIDTH + SLIDER_WIDTH)
25#define ITEM_HEIGHT 15
26#define ITEM_MARGIN 5
27#define PANEL_WIDTH (ITEM_WIDTH + 2*ITEM_MARGIN)
28#define PANEL_HEIGHT(N) (RAYGUI_WINDOWBOX_STATUSBAR_HEIGHT + (N)*(ITEM_HEIGHT + ITEM_MARGIN) + ITEM_MARGIN)
29
30#ifdef DARK
31#define BACKGROUND RGBA (0x000000FF)
32#else
33#define BACKGROUND RGBA (0xFFFFFFFF)
34#endif
35
36#define ARROW_THICKNESS 2.5
37#define ARROW_LENGTH 15
38#define ARROW_ANGLE 10
39
40#define CONTROL_POINT_RADIUS 5
41#define CONTROL_POINT_RADIUS_FOCUSED 10
42
43enum menu {
44 MENU_VISUALIZATION,
45 MENU_INPUT,
46 MENU_CHROMOSOME,
47 MENU_METRICS,
48 MENU_WEIGHTS,
49 MENU_COUNT
50} menu = MENU_VISUALIZATION;
51
52const char *menu_to_label[] = {
53 [MENU_VISUALIZATION] = "VISUALIZATION",
54 [MENU_INPUT] = "INPUT",
55 [MENU_CHROMOSOME] = "CHROMOSOME",
56 [MENU_METRICS] = "METRICS",
57 [MENU_WEIGHTS] = "WEIGHTS",
58};
59
60struct fitness_breakdown fb;
61struct fitness_weights w = {
62 .time = 1.5,
63 .length = 1.5,
64 .max_abs_kappa = 30,
65 .max_abs_dkappa = 30,
66 .max_abs_a = 30,
67 .max_abs_j = 25,
68 .rms_kappa = 2,
69 .rms_dkappa = 4,
70 .rms_a = 3,
71 .rms_j = 0.35,
72 .violation_a = 3.5,
73 .violation_j = 0.2,
74 .terminal = 100,
75};
76
77void
78draw_arrow (Vector2 beg, Vector2 end, float thick, Color c)
79{
80 Vector2 off = Vector2Scale (Vector2Normalize (Vector2Subtract (end, beg)),
81 ARROW_LENGTH);
82 Vector2 ahl = Vector2Add (end, Vector2Rotate (off, +ARROW_ANGLE));
83 Vector2 ahr = Vector2Add (end, Vector2Rotate (off, -ARROW_ANGLE));
84
85 DrawLineEx (beg, end, thick, c);
86 DrawLineEx (end, ahl, thick, c);
87 DrawLineEx (end, ahr, thick, c);
88
89 DrawCircleV (beg, thick/2., c);
90 DrawCircleV (end, thick/2., c);
91 DrawCircleV (ahl, thick/2., c);
92 DrawCircleV (ahr, thick/2., c);
93}
94
95void
96draw_bezier5 (bezier5 cp)
97{
98 char text[] = "P0";
99 DrawLineStrip (cp, 6, BLUE);
100 for (int i = 0; i < 6; ++i) {
101 DrawCircleLinesV (cp[i], 4, BLUE);
102 text[1] = '0' + i;
103 DrawText (text, cp[i].x - 5, cp[i].y + 7, 14, BLACK);
104 }
105}
106
107void
108chromosome_to_control_points (bezier5 cp, struct input in, struct chromosome ch)
109{
110 Vector2 e_beg = Vector2Normalize (in.v_beg);
111 Vector2 e_end = Vector2Normalize (in.v_end);
112 Vector2 n_beg = { -e_beg.y, +e_beg.x };
113 Vector2 n_end = { -e_end.y, +e_end.x };
114
115 cp[0] = in.r_beg;
116 cp[1] = Vector2Add (in.r_beg, Vector2Scale (e_beg, +ch.rho*ch.tau_1));
117 cp[2] = Vector2Add (in.r_beg, Vector2Scale (Vector2Add (Vector2Scale (e_beg, ch.alp_2), Vector2Scale (n_beg, ch.bet_2)), +ch.rho));
118 cp[3] = Vector2Add (in.r_end, Vector2Scale (Vector2Add (Vector2Scale (e_end, ch.alp_3), Vector2Scale (n_end, ch.bet_3)), -ch.rho));
119 cp[4] = Vector2Add (in.r_end, Vector2Scale (e_end, -ch.rho*ch.tau_4));
120 cp[5] = in.r_end;
121}
122
123struct chromosome
124rand_chromosome (void)
125{
126 return (struct chromosome) {
127 10 + 50 * (rand () /(float) RAND_MAX),
128 .5 + 5 * (rand () /(float) RAND_MAX),
129 .5 + 5 * (rand () /(float) RAND_MAX),
130 .5 + 5 * (rand () /(float) RAND_MAX),
131 .5 + 5 * (rand () /(float) RAND_MAX),
132 .5 + 5 * (rand () /(float) RAND_MAX),
133 .5 + 5 * (rand () /(float) RAND_MAX),
134 };
135}
136
137float sample_offset = 10;
138float sample_spacing = PATH_SAMPLE_COUNT/4;
139bool sample_dr = true;
140bool sample_ddr = true;
141
142Color
143lerp_color (Color a, Color b, float t)
144{
145 Color c;
146 c.r = (unsigned char) (a.r + (b.r - a.r)*t);
147 c.g = (unsigned char) (a.g + (b.g - a.g)*t);
148 c.b = (unsigned char) (a.b + (b.b - a.b)*t);
149 c.a = (unsigned char) (a.a + (b.a - a.a)*t);
150 return c;
151}
152
153float ease_out_cubic (float x) { return 1 - powf (1 - x, 3); }
154float ease_out_quint (float x) { return 1 - powf (1 - x, 5); }
155float ease_out_sin (float x) { return sinf (PI*x/2); }
156float ease_inout_sin (float x) { return -(cosf (PI*x) - 1)/2; }
157
158void
159compute_ribbon_join (const struct path_table *p, int i, float half,
160 Vector2 *l, Vector2 *r)
161{
162 Vector2 t;
163
164 if (i == 0) {
165 t = Vector2Normalize (Vector2Subtract (p->r[1], p->r[0]));
166 } else if (i == PATH_SAMPLE_COUNT - 1) {
167 t = Vector2Normalize (Vector2Subtract (p->r[i], p->r[i - 1]));
168 } else {
169 t = Vector2Normalize (Vector2Subtract (p->r[i + 1], p->r[i - 1]));
170 }
171
172 Vector2 n = { -t.y, t.x };
173
174 *l = Vector2Add (p->r[i], Vector2Scale (n, half));
175 *r = Vector2Add (p->r[i], Vector2Scale (n, -half));
176}
177
178void
179draw_path_gradient_ribbon (const struct path_table *p,
180 float thick, Color c0, Color c1)
181{
182 if (PATH_SAMPLE_COUNT < 2 || thick <= 0) return;
183
184 float half = thick/2;
185
186 Vector2 l0, r0, l1, r1;
187 compute_ribbon_join (p, 0, half, &l0, &r0);
188
189 rlBegin (RL_TRIANGLES);
190 for (int i = 0; i < PATH_SAMPLE_COUNT - 1; ++i) {
191 compute_ribbon_join (p, i + 1, half, &l1, &r1);
192
193 float u0 = ease_out_cubic (fabsf (p->kappa[i + 0])/p->max_abs_kappa);
194 float u1 = ease_out_cubic (fabsf (p->kappa[i + 1])/p->max_abs_kappa);
195
196 Color col0 = lerp_color (c0, c1, u0);
197 Color col1 = lerp_color (c0, c1, u1);
198
199 rlColor4ub (col0.r, col0.g, col0.b, col0.a); rlVertex2f (l0.x, l0.y);
200 rlColor4ub (col1.r, col1.g, col1.b, col1.a); rlVertex2f (l1.x, l1.y);
201 rlColor4ub (col0.r, col0.g, col0.b, col0.a); rlVertex2f (r0.x, r0.y);
202
203 rlColor4ub (col0.r, col0.g, col0.b, col0.a); rlVertex2f (r0.x, r0.y);
204 rlColor4ub (col1.r, col1.g, col1.b, col1.a); rlVertex2f (l1.x, l1.y);
205 rlColor4ub (col1.r, col1.g, col1.b, col1.a); rlVertex2f (r1.x, r1.y);
206
207 l0 = l1;
208 r0 = r1;
209 } rlEnd ();
210}
211
212void
213draw_path (const struct path_table *p, float thick)
214{
215 const int c = PATH_SAMPLE_COUNT;
216 // DrawCircleV (p->r[ 0], thick/2., BLUE);
217 // DrawCircleV (p->r[c - 1], thick/2., BLUE);
218 draw_path_gradient_ribbon (p, thick, BLUE, RED);
219 for (int i = sample_offset; i < c; i += sample_spacing) {
220 Vector2 r = p->r[i];
221 if (sample_dr ) draw_arrow (r, Vector2Add (r, Vector2Scale (Vector2Normalize (p-> dr[i]), 30)), thick/2, MAGENTA);
222 if (sample_ddr) draw_arrow (r, Vector2Add (r, Vector2Scale (Vector2Normalize (p->ddr[i]), 30)), thick/2, PURPLE);
223 }
224}
225
226void
227plot_motion_profile (Rectangle bb, const struct motion_profile *mp,
228 float v_max, float a_max, float j_max)
229{
230 const int n = PATH_SAMPLE_COUNT;
231 static Vector2 line[PATH_SAMPLE_COUNT];
232
233 float t = mp->t[n - 1];
234 for (int i = 0; i < n; ++i)
235 line[i].x = Lerp (bb.x, bb.x + bb.width, mp->t[i]/t);
236
237 // axis
238 Vector2 origin = { bb.x, bb.y + bb.height /(float) 2 };
239 DrawLineEx (origin, Vector2Add (origin, (Vector2) { bb.width, 0 }), 1, GRAY);
240 for (int i = 0; i < n; ++i) {
241 DrawLineEx ((Vector2) { line[i].x, origin.y + 5 },
242 (Vector2) { line[i].x, origin.y - 5 }, 1, GRAY);
243 }
244
245 // velocity
246 for (int i = 0; i < n; ++i)
247 line[i].y = Lerp (origin.y, bb.y + 2, mp->v[i]/fabsf (mp->v_max));
248 DrawSplineBezierCubic (line, n, 1, BLUE);
249
250 // acceleration
251 for (int i = 0; i < n; ++i)
252 line[i].y = Lerp (origin.y, bb.y + 2, mp->a[i]/fabsf (mp->a_max));
253 DrawSplineBezierCubic (line, n, 1, ORANGE);
254
255 // jerk
256 for (int i = 0; i < n; ++i)
257 line[i].y = Lerp (origin.y, bb.y + 2, mp->j[i]/fabsf (mp->j_max));
258 DrawSplineBezierCubic (line, n, 1, RED);
259}
260
261int
262panel_slider (int x, int y, int c, const char *label, const char *fmt, float *var, float min, float max)
263{
264 GuiLabel ((Rectangle) { x + ITEM_MARGIN, y + c*(ITEM_HEIGHT + ITEM_MARGIN), LABEL_WIDTH, ITEM_HEIGHT }, TextFormat ("%s: %s", label, TextFormat (fmt, *var)));
265 return GuiSliderBar ((Rectangle) { x + ITEM_MARGIN + LABEL_WIDTH, y + c*(ITEM_HEIGHT + ITEM_MARGIN), SLIDER_WIDTH, ITEM_HEIGHT }, NULL, NULL, var, min, max);
266}
267
268int
269panel_var (int x, int y, int c, const char *label, const char *fmt, float *var)
270{
271 GuiLabel ((Rectangle) { x + ITEM_MARGIN, y + c*(ITEM_HEIGHT + ITEM_MARGIN), ITEM_WIDTH, ITEM_HEIGHT },
272 TextFormat ("%s: %s", label, TextFormat (fmt, *var)));
273 return 0;
274}
275
276int
277panel_bool (int x, int y, int c, const char *label, bool *checked)
278{
279 return GuiCheckBox ((Rectangle) {
280 x + ITEM_MARGIN, y + c*(ITEM_HEIGHT + ITEM_MARGIN),
281 ITEM_HEIGHT, ITEM_HEIGHT
282 }, label, checked);
283}
284
285int
286main (int argc, char *argv[])
287{
288 srand (time (NULL));
289
290 SetConfigFlags (FLAG_MSAA_4X_HINT);
291 SetConfigFlags (FLAG_WINDOW_RESIZABLE);
292 InitWindow (800, 450, "GA");
293 SetTargetFPS (60);
294
295 Camera2D camera = {
296 .zoom = 1.0f,
297 };
298
299 Vector2 screen = {
300 .x = GetScreenWidth (),
301 .y = GetScreenHeight (),
302 };
303
304 GuiSetStyle(DEFAULT, TEXT_SIZE, 20);
305 // GuiGetStyle ();
306
307 struct input in = {
308 .r_beg = { 100, 100 },
309 // .r_end = { 100, 100 },
310 .r_end = { 300, 300 },
311 .v_beg = { 100, 10 },
312 .v_end = { 100, 10 },
313 .v_max = 250,
314 .a_max = 500,
315 .j_max = 16,
316 };
317
318 bezier5 cp;
319 struct chromosome ch = rand_chromosome ();
320 struct path_table pt;
321 struct motion_profile mp;
322
323 float arrow_thickness = ARROW_THICKNESS;
324 float spline_thickness = ARROW_THICKNESS;
325 bool move_r_beg = false;
326 bool move_r_end = false;
327 bool move_v_beg = false;
328 bool move_v_end = false;
329 bool recompute = true;
330 bool show_fps = true;
331 bool show_menu = true;
332 bool show_graph = true;
333 bool draw_cp = true;
334 bool animate_sample_offset = false;
335 float animation_speed = 20;
336 int panel_item = 0;
337 bool resizing_graph = false;
338 int graph_height = screen.y/3;
339 while (!WindowShouldClose ()) {
340 screen = (Vector2) {
341 .x = GetScreenWidth (),
342 .y = GetScreenHeight (),
343 };
344 float t = GetTime ();
345 float dt = GetFrameTime ();
346
347 if (IsMouseButtonDown (MOUSE_BUTTON_RIGHT)) {
348 Vector2 delta = GetMouseDelta ();
349 delta = Vector2Scale (delta, -1.0f/camera.zoom);
350 camera.target = Vector2Add (camera.target, delta);
351 }
352
353 if (IsKeyPressed (KEY_LEFT )) menu = menu ? menu - 1 : MENU_COUNT - 1;
354 if (IsKeyPressed (KEY_RIGHT)) menu = menu < MENU_COUNT - 1 ? menu + 1 : 0;
355
356 if (IsKeyPressed (KEY_R)) {
357 ch = rand_chromosome ();
358 recompute = true;
359 }
360
361 if (IsKeyDown (KEY_O)) {
362 struct chromosome res;
363 float cost;
364 example_cmaes_usage (&in, &ch, &w, &res, &cost);
365 ch = res;
366 recompute = true;
367 }
368
369 if (IsKeyPressed (KEY_M)) show_menu = !show_menu;
370 if (IsKeyPressed (KEY_G)) show_graph = !show_graph;
371 if (IsKeyPressed (KEY_F)) show_fps = !show_fps;
372
373 if (recompute) {
374 chromosome_to_control_points (cp, in, ch);
375 build_path_table (&pt, cp);
376 build_motion_profile (&mp, &pt,
377 Vector2Length (in.v_beg),
378 Vector2Length (in.v_end),
379 in.v_max, in.a_max, in.j_max);
380 fb = evaluate_motion_fitness (&pt, &mp,
381 Vector2Length (in.v_beg),
382 Vector2Length (in.v_end),
383 in.v_max, in.a_max, in.j_max, &w);
384
385 recompute = false;
386 }
387
388 float wheel = GetMouseWheelMove();
389 if (wheel != 0) {
390 Vector2 offset = GetMousePosition ();
391 camera.target = GetScreenToWorld2D (offset, camera);
392 camera.offset = offset;
393 camera.zoom = Clamp (expf (logf (camera.zoom) + .2*wheel), .125, 64);
394 }
395
396 Vector2 mouse_hud = GetMousePosition ();
397 Vector2 mouse = GetScreenToWorld2D (mouse_hud, camera);
398
399 if (IsMouseButtonDown (MOUSE_BUTTON_LEFT)
400 && mouse_hud.y > screen.y - graph_height
401 && mouse_hud.y < screen.y - graph_height + RAYGUI_WINDOWBOX_STATUSBAR_HEIGHT) {
402 resizing_graph = true;
403 }
404
405 if (resizing_graph) {
406 graph_height = Clamp (RAYGUI_WINDOWBOX_STATUSBAR_HEIGHT + 2, screen.y - 4,
407 screen.y - mouse_hud.y + RAYGUI_WINDOWBOX_STATUSBAR_HEIGHT/2);
408 if (IsMouseButtonReleased (MOUSE_BUTTON_LEFT))
409 resizing_graph = false;
410 }
411
412 BeginDrawing ();
413 ClearBackground (BACKGROUND);
414 BeginMode2D (camera);
415
416 if (CheckCollisionPointCircle (mouse, in.r_beg, 10)) {
417 DrawCircleLinesV (in.r_beg, 10, BLUE);
418 if (!move_v_beg && IsMouseButtonDown (MOUSE_BUTTON_LEFT))
419 move_r_beg = true;
420 } else if (CheckCollisionPointCircle (mouse, in.r_end, 10)) {
421 DrawCircleLinesV (in.r_end, 10, BLUE);
422 if (!move_v_end && IsMouseButtonDown (MOUSE_BUTTON_LEFT))
423 move_r_end = true;
424 } else if (CheckCollisionPointCircle (mouse, Vector2Add (in.r_beg, in.v_beg), 10)) {
425 DrawCircleLinesV (Vector2Add (in.r_beg, in.v_beg), 10, BLUE);
426 if (!move_r_beg && IsMouseButtonDown (MOUSE_BUTTON_LEFT))
427 move_v_beg = true;
428 } else if (CheckCollisionPointCircle (mouse, Vector2Add (in.r_end, in.v_end), 10)) {
429 DrawCircleLinesV (Vector2Add (in.r_end, in.v_end), 10, BLUE);
430 if (!move_r_end && IsMouseButtonDown (MOUSE_BUTTON_LEFT))
431 move_v_end = true;
432 }
433
434 if (move_r_beg) {
435 in.r_beg = mouse;
436 if (IsMouseButtonReleased (MOUSE_BUTTON_LEFT))
437 move_r_beg = false;
438 }
439 if (move_r_end) {
440 in.r_end = mouse;
441 if (IsMouseButtonReleased (MOUSE_BUTTON_LEFT))
442 move_r_end = false;
443 }
444 if (move_v_beg) {
445 in.v_beg = Vector2Subtract (mouse, in.r_beg);
446 if (IsMouseButtonReleased (MOUSE_BUTTON_LEFT))
447 move_v_beg = false;
448 }
449 if (move_v_end) {
450 in.v_end = Vector2Subtract (mouse, in.r_end);
451 if (IsMouseButtonReleased (MOUSE_BUTTON_LEFT))
452 move_v_end = false;
453 }
454
455 if (animate_sample_offset)
456 sample_offset = (int) (animation_speed*t) % (int) sample_spacing;
457
458 // rlPushMatrix ();
459 // rlTranslatef (0, 25*50, 0);
460 // rlRotatef (90, 1, 0, 0);
461 // DrawGrid (100, 50);
462 // rlPopMatrix ();
463
464 draw_path (&pt, spline_thickness);
465 if (draw_cp) draw_bezier5 (cp);
466 draw_arrow (in.r_beg, Vector2Add (in.r_beg, in.v_beg), arrow_thickness, GREEN);
467 draw_arrow (in.r_end, Vector2Add (in.r_end, in.v_end), arrow_thickness, RED);
468
469 EndMode2D ();
470
471 if (move_r_beg ||
472 move_r_end ||
473 move_v_beg ||
474 move_v_end) {
475 GuiLock ();
476 recompute = true;
477 }
478
479 if (show_menu) {
480 int x = 2;
481 int y = 2;
482
483 GuiPanel ((Rectangle) { x, y, PANEL_WIDTH, PANEL_HEIGHT (panel_item) }, menu_to_label[menu]);
484 y += RAYGUI_WINDOWBOX_STATUSBAR_HEIGHT;
485 y += ITEM_MARGIN;
486 panel_item = 0;
487 switch (menu) {
488 case MENU_VISUALIZATION:
489 panel_slider (x, y, panel_item++, "Arrow", "%.2f", &arrow_thickness, 1, 10);
490 panel_slider (x, y, panel_item++, "Spline", "%.2f", &spline_thickness, 1, 10);
491 panel_slider (x, y, panel_item++, "Spacing", "%.0f", &sample_spacing, 2, PATH_SAMPLE_COUNT - 1);
492 panel_slider (x, y, panel_item++, "Offset", "%.0f", &sample_offset, 0, sample_spacing);
493 panel_slider (x, y, panel_item++, "Speed", "%.0f", &animation_speed, 0, 30);
494 panel_bool (x, y, panel_item++, "Animate offset", &animate_sample_offset);
495 panel_bool (x, y, panel_item++, "Draw dr", &sample_dr);
496 panel_bool (x, y, panel_item++, "Draw ddr", &sample_ddr);
497 panel_bool (x, y, panel_item++, "Draw cp", &draw_cp);
498 break;
499
500 case MENU_INPUT:
501 recompute |= panel_slider (x, y, panel_item++, "v_lim", "%.2f", &in.v_max, fmaxf (Vector2Length (in.v_beg), Vector2Length (in.v_beg)), 500);
502 recompute |= panel_slider (x, y, panel_item++, "a_lim", "%.2f", &in.a_max, 1, 500);
503 recompute |= panel_slider (x, y, panel_item++, "j_lim", "%.2f", &in.j_max, 1, 100);
504 panel_var (x, y, panel_item++, "r_beg.x", "%.2f", &in.r_beg.x);
505 panel_var (x, y, panel_item++, "r_beg.y", "%.2f", &in.r_beg.y);
506 panel_var (x, y, panel_item++, "r_end.x", "%.2f", &in.r_end.x);
507 panel_var (x, y, panel_item++, "r_end.y", "%.2f", &in.r_end.y);
508 panel_var (x, y, panel_item++, "v_beg.x", "%.2f", &in.v_beg.x);
509 panel_var (x, y, panel_item++, "v_beg.y", "%.2f", &in.v_beg.y);
510 panel_var (x, y, panel_item++, "v_end.x", "%.2f", &in.v_end.x);
511 panel_var (x, y, panel_item++, "v_end.y", "%.2f", &in.v_end.y);
512 break;
513
514 case MENU_CHROMOSOME:
515 recompute |= panel_slider (x, y, panel_item++, "rho", "%.2f", &ch.rho, 1, 1000);
516 recompute |= panel_slider (x, y, panel_item++, "tau_1", "%.2f", &ch.tau_1, 0, 10);
517 recompute |= panel_slider (x, y, panel_item++, "alpha_2", "%.2f", &ch.alp_2, 0, 10);
518 recompute |= panel_slider (x, y, panel_item++, "beta_2", "%+.2f", &ch.bet_2, -5, 5);
519 recompute |= panel_slider (x, y, panel_item++, "alpha_3", "%.2f", &ch.alp_3, 0, 10);
520 recompute |= panel_slider (x, y, panel_item++, "beta_3", "%+.2f", &ch.bet_3, -5, 5);
521 recompute |= panel_slider (x, y, panel_item++, "tau_4", "%.2f", &ch.tau_4, 0, 10);
522 break;
523
524 case MENU_WEIGHTS:
525 recompute |= panel_slider (x, y, panel_item++, "w_time", "%.2f", &w.time, 0, 10);
526 recompute |= panel_slider (x, y, panel_item++, "w_length", "%.2f", &w.length, 0, 10);
527 recompute |= panel_slider (x, y, panel_item++, "w_max_kappa", "%.2f", &w.max_abs_kappa, 0, 100);
528 recompute |= panel_slider (x, y, panel_item++, "w_max_dkappa", "%.2f", &w.max_abs_dkappa, 0, 100);
529 recompute |= panel_slider (x, y, panel_item++, "w_max_a", "%.2f", &w.max_abs_a, 0, 100);
530 recompute |= panel_slider (x, y, panel_item++, "w_max_j", "%.2f", &w.max_abs_j, 0, 100);
531 recompute |= panel_slider (x, y, panel_item++, "w_rms_kappa", "%.2f", &w.rms_kappa, 0, 10);
532 recompute |= panel_slider (x, y, panel_item++, "w_rms_dkappa", "%.2f", &w.rms_dkappa, 0, 10);
533 recompute |= panel_slider (x, y, panel_item++, "w_rms_a", "%.2f", &w.rms_a, 0, 10);
534 recompute |= panel_slider (x, y, panel_item++, "w_rms_j", "%.2f", &w.rms_j, 0, 1);
535 recompute |= panel_slider (x, y, panel_item++, "w_violation_a", "%.2f", &w.violation_a, 0, 10);
536 recompute |= panel_slider (x, y, panel_item++, "w_violation_j", "%.2f", &w.violation_j, 0, 1);
537 recompute |= panel_slider (x, y, panel_item++, "w_terminal", "%.2f", &w.terminal, 0, 100);
538 break;
539
540 case MENU_METRICS:
541 panel_var (x, y, panel_item++, "Length", "%.2f", &pt.s[PATH_SAMPLE_COUNT - 1]);
542 panel_var (x, y, panel_item++, "Duration", "%.2f", &mp.t[PATH_SAMPLE_COUNT - 1]);
543 panel_var (x, y, panel_item++, "Cost", "%.2f", &fb.total_cost);
544
545 panel_var (x, y, panel_item++, "v_max", "%.2f", &mp.v_max);
546 panel_var (x, y, panel_item++, "a_max", "%.2f", &mp.a_max);
547 panel_var (x, y, panel_item++, "j_max", "%.2f", &mp.j_max);
548
549 panel_var (x, y, panel_item++, "time_cost", "%.2f", &fb.time_cost);
550 panel_var (x, y, panel_item++, "length_cost", "%.2f", &fb.length_cost);
551 panel_var (x, y, panel_item++, "kappa_cost", "%.2f", &fb.kappa_cost);
552 panel_var (x, y, panel_item++, "dkappa_cost", "%.2f", &fb.dkappa_cost);
553 panel_var (x, y, panel_item++, "accel_rms_cost", "%.2f", &fb.accel_rms_cost);
554 panel_var (x, y, panel_item++, "jerk_rms_cost", "%.2f", &fb.jerk_rms_cost);
555 panel_var (x, y, panel_item++, "accel_violation_cost", "%.2f", &fb.accel_violation_cost);
556 panel_var (x, y, panel_item++, "jerk_violation_cost", "%.2f", &fb.jerk_violation_cost);
557 panel_var (x, y, panel_item++, "terminal_cost", "%.2f", &fb.terminal_cost);
558 panel_var (x, y, panel_item++, "failure_cost", "%.2f", &fb.failure_cost);
559 panel_var (x, y, panel_item++, "duration", "%.2f", &fb.duration);
560 panel_var (x, y, panel_item++, "length", "%.2f", &fb.length);
561 panel_var (x, y, panel_item++, "kappa_rms", "%.2f", &fb.kappa_rms);
562 panel_var (x, y, panel_item++, "dkappa_rms", "%.2f", &fb.dkappa_rms);
563 panel_var (x, y, panel_item++, "accel_rms", "%.2f", &fb.accel_rms);
564 panel_var (x, y, panel_item++, "jerk_rms", "%.2f", &fb.jerk_rms);
565 panel_var (x, y, panel_item++, "accel_violation", "%.2f", &fb.accel_violation);
566 panel_var (x, y, panel_item++, "jerk_violation", "%.2f", &fb.jerk_violation);
567 break;
568 default: break;
569 }
570 }
571 GuiUnlock ();
572
573 if (show_graph) {
574 Rectangle bb;
575 bb.x = 2;
576 bb.width = screen.x - 4;
577 bb.height = graph_height;
578 bb.y = screen.y - 2 - bb.height;
579 GuiPanel (bb, "GRAPH");
580 bb.y += RAYGUI_WINDOWBOX_STATUSBAR_HEIGHT;
581 bb.height -= RAYGUI_WINDOWBOX_STATUSBAR_HEIGHT;
582 plot_motion_profile (bb, &mp, in.v_max, in.a_max, in.j_max);
583 }
584
585 if (show_fps)
586 DrawFPS (screen.x - 75, 0);
587 EndDrawing ();
588 }
589
590 CloseWindow ();
591
592 return EXIT_SUCCESS;
593}
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 @@
1#include "retiming.h"
2
3Vector2
4bezier5_point (const bezier5 cp, float u)
5{
6 float w = 1 - u;
7
8 float b0 = w*w*w*w*w * 1;
9 float b1 = w*w*w*w*u * 5;
10 float b2 = w*w*w*u*u * 10;
11 float b3 = w*w*u*u*u * 10;
12 float b4 = w*u*u*u*u * 5;
13 float b5 = u*u*u*u*u * 1;
14
15 return (Vector2) {
16 .x = b0 * cp[0].x +
17 b1 * cp[1].x +
18 b2 * cp[2].x +
19 b3 * cp[3].x +
20 b4 * cp[4].x +
21 b5 * cp[5].x,
22 .y = b0 * cp[0].y +
23 b1 * cp[1].y +
24 b2 * cp[2].y +
25 b3 * cp[3].y +
26 b4 * cp[4].y +
27 b5 * cp[5].y,
28 };
29}
30
31Vector2
32bezier5_deriv1 (const bezier5 cp, float u)
33{
34 float w = 1 - u;
35
36 float b0 = w*w*w*w * 1;
37 float b1 = w*w*w*u * 4;
38 float b2 = w*w*u*u * 6;
39 float b3 = w*u*u*u * 4;
40 float b4 = u*u*u*u * 1;
41
42 Vector2 q0 = Vector2Subtract (cp[1], cp[0]);
43 Vector2 q1 = Vector2Subtract (cp[2], cp[1]);
44 Vector2 q2 = Vector2Subtract (cp[3], cp[2]);
45 Vector2 q3 = Vector2Subtract (cp[4], cp[3]);
46 Vector2 q4 = Vector2Subtract (cp[5], cp[4]);
47
48 return (Vector2) {
49 5*(b0*q0.x + b1*q1.x + b2*q2.x + b3*q3.x + b4*q4.x),
50 5*(b0*q0.y + b1*q1.y + b2*q2.y + b3*q3.y + b4*q4.y),
51 };
52}
53
54Vector2
55bezier5_deriv2(const bezier5 cp, float u)
56{
57 float w = 1 - u;
58
59 float b0 = w*w*w * 1;
60 float b1 = w*w*u * 3;
61 float b2 = w*u*u * 3;
62 float b3 = u*u*u * 1;
63
64 Vector2 r0 = Vector2Add (Vector2Subtract (cp[2], Vector2Scale (cp[1], 2)), cp[0]);
65 Vector2 r1 = Vector2Add (Vector2Subtract (cp[3], Vector2Scale (cp[2], 2)), cp[1]);
66 Vector2 r2 = Vector2Add (Vector2Subtract (cp[4], Vector2Scale (cp[3], 2)), cp[2]);
67 Vector2 r3 = Vector2Add (Vector2Subtract (cp[5], Vector2Scale (cp[4], 2)), cp[3]);
68
69 return (Vector2) {
70 20*(b0*r0.x + b1*r1.x + b2*r2.x + b3*r3.x),
71 20*(b0*r0.y + b1*r1.y + b2*r2.y + b3*r3.y),
72 };
73}
74
75void
76build_path_table (struct path_table *table, const bezier5 cp)
77{
78 int i, c = PATH_SAMPLE_COUNT;
79 for (i = 0; i < c; ++i) table->u [i] = i /(float) (PATH_SAMPLE_COUNT - 1);
80 for (i = 0; i < c; ++i) table->r [i] = bezier5_point (cp, table->u[i]);
81 for (i = 0; i < c; ++i) table->dr [i] = bezier5_deriv1 (cp, table->u[i]);
82 for (i = 0; i < c; ++i) table->ddr [i] = bezier5_deriv2 (cp, table->u[i]);
83
84 table->s[0] = 0;
85 for (i = 1; i < c; ++i) {
86 table->s[i] = table->s[i - 1] + Vector2Length (
87 Vector2Subtract (table->r[i], table->r[i - 1]));
88 }
89
90 float max_abs_kappa = 0;
91 for (i = 0; i < c; ++i) {
92 Vector2 dr = table-> dr[i];
93 Vector2 ddr = table->ddr[i];
94 float l = Vector2Length (dr);
95 float kappa = (dr.x*ddr.y - dr.y*ddr.x)/l/l/l;
96 table->kappa[i] = kappa;
97 if (fabsf (kappa) > max_abs_kappa)
98 max_abs_kappa = fabsf (kappa);
99 } table->max_abs_kappa = max_abs_kappa;
100
101 table->dkappa_ds[ 0] = (table->kappa[ 1] - table->kappa[ 0]) /
102 (table->s [ 1] - table->s [ 0]);
103 table->dkappa_ds[c - 1] = (table->kappa[c - 1] - table->kappa[c - 2]) /
104 (table->s [c - 1] - table->s [c - 2]);
105 for (i = 1; i < c - 1; ++i) {
106 table->dkappa_ds[i] = (table->kappa[i + 1] - table->kappa[i - 1]) /
107 (table->s [i + 1] - table->s [i - 1]);
108 }
109}
110
111float
112speed_limit (float kappa, float dkappa_ds,
113 float v_max, float a_max, float j_max)
114{
115 float v_lim = v_max;
116 float k = fabsf (kappa);
117
118 if (k > EPS) {
119 float va = sqrtf (fmaxf (0, a_max/k));
120 v_lim = fminf (v_lim, va);
121 }
122
123 // float jerk_denom = k*k + fabsf (dkappa_ds);
124 // if (jerk_denom > EPS) {
125 // float vj = cbrtf (fmaxf (0, j_max/jerk_denom));
126 // v_lim = fminf (v_lim, vj);
127 // }
128
129 if (!isfinite (v_lim)) v_lim = 0;
130 return fmaxf (v_lim, 0);
131}
132
133float
134centered_differences_in_time (float *d, const float *v, const float *t, int n)
135{
136 d[ 0] = (v[ 1] - v[ 0]) /
137 (t[ 1] - t[ 0]);
138 d[n - 1] = (v[n - 1] - v[n - 2]) /
139 (t[n - 1] - t[n - 2]);
140 float max = fabsf (d[0]) > fabsf(d[n - 1]) ? d[0] : d[n - 1];
141 for (int i = 1; i < n - 1; ++i) {
142 d[i] = (v[i + 1] - v[i - 1]) /
143 (t[i + 1] - t[i - 1]);
144 if (fabsf (d[i]) > fabsf (max))
145 max = d[i];
146 }
147
148 return max;
149}
150
151float
152tangential_accel_cap (float kappa, float v, float a_max)
153{
154 float an = fabsf (kappa)*v*v;
155 float rem = a_max*a_max - an*an;
156 return (rem > 0) ? sqrtf (rem) : 0;
157}
158
159int
160build_motion_profile (struct motion_profile *m, const struct path_table *p,
161 float v_beg, float v_end,
162 float v_max, float a_max, float j_max)
163{
164 static float v_lim[PATH_SAMPLE_COUNT];
165 static float v_fwd[PATH_SAMPLE_COUNT];
166 static float v_bwd[PATH_SAMPLE_COUNT];
167 static float a_fwd[PATH_SAMPLE_COUNT];
168 static float a_bwd[PATH_SAMPLE_COUNT];
169
170 const float MIN_TIME_SPEED = 1e-3f;
171 const int n = PATH_SAMPLE_COUNT;
172
173 int feasible = 1;
174
175 // Local speed ceilings
176 for (int i = 0; i < n; ++i) {
177 v_lim[i] = speed_limit (p->kappa[i], p->dkappa_ds[i], v_max, a_max, j_max);
178 }
179
180 if (v_beg > v_lim[ 0] + 1e-4f) feasible = 0;
181 if (v_end > v_lim[n - 1] + 1e-4f) feasible = 0;
182
183 // Forward pass
184 v_fwd[0] = v_beg;
185 a_fwd[0] = 0;
186 for (int i = 0; i < n - 1; ++i) {
187 float ds = p->s[i + 1] - p->s[i];
188 float v_cur = v_fwd[i];
189 float v_for_dt = fmaxf (v_cur, .25*v_max);
190 float dt_est = ds/v_for_dt;
191
192 float a_cap = tangential_accel_cap (p->kappa[i], v_cur, a_max);
193 float a_next = fminf (a_cap, a_fwd[i] + j_max*dt_est);
194 if (a_next < 0) a_next = 0;
195
196 float v_reach_sq = v_cur*v_cur + 2*a_next*ds;
197 float v_reach = sqrtf (fmaxf (0, v_reach_sq));
198
199 v_fwd[i + 1] = fminf (v_lim[i + 1], v_reach);
200 a_fwd[i + 1] = a_next;
201 }
202
203 // Backward pass
204 v_bwd[n - 1] = v_end;
205 a_bwd[n - 1] = 0;
206 for (int i = n - 1; i > 0; --i) {
207 float ds = p->s[i] - p->s[i - 1];
208 float v_cur = v_bwd[i];
209 float v_for_dt = fmaxf (v_cur, .25*v_max);
210 float dt_est = ds/v_for_dt;
211
212 float a_cap = tangential_accel_cap (p->kappa[i], v_cur, a_max);
213 float a_prev = fminf (a_cap, a_bwd[i] + j_max*dt_est);
214 if (a_prev < 0) a_prev = 0;
215
216 float v_reach_prev_sq = v_cur*v_cur + 2*a_prev*ds;
217 float v_reach_prev = sqrtf (fmaxf (0, v_reach_prev_sq));
218
219 v_bwd[i - 1] = fminf (v_lim[i - 1], v_reach_prev);
220 a_bwd[i - 1] = a_prev;
221 }
222
223 // Combined profile
224 for (int i = 0; i < n; ++i)
225 m->v[i] = fminf (v_fwd[i], v_bwd[i]);
226
227 // Build cumulative time
228 m->t[0] = 0;
229 for (int i = 1; i < n; ++i) {
230 float ds = p->s[i] - p->s[i - 1];
231 float v_avg = .5*(m->v[i - 1] + m->v[i]);
232 float dt = v_avg > EPS ? ds/v_avg : ds/MIN_TIME_SPEED;
233
234 if (!isfinite (dt) || dt < 0) {
235 dt = ds/MIN_TIME_SPEED;
236 feasible = 0;
237 }
238
239 m->t[i] = m->t[i - 1] + dt;
240 }
241
242 m->v_max = 0;
243 for (int i = 0; i < n; ++i) {
244 if (fabsf (m->v[i]) > fabsf (m->v_max))
245 m->v_max = m->v[i];
246 }
247 m->a_max = centered_differences_in_time (m->a, m->v, m->t, n);
248 m->j_max = centered_differences_in_time (m->j, m->a, m->t, n);
249
250 return feasible;
251}
252
253static inline float
254trapz_step (float y0, float y1, float dx)
255{
256 return 0.5f * (y0 + y1) * dx;
257}
258
259static inline float
260total_accel_norm (float kappa, float v, float a_t)
261{
262 float a_n = v*v*kappa;
263 return hypotf (a_t, a_n);
264}
265
266static inline float
267total_jerk_norm (float kappa, float dkappa_ds,
268 float v, float a_t, float j_t)
269{
270 float j_t_cart = j_t - v*v*v*kappa*kappa;
271 float j_n_cart = 3.0f*v*a_t*kappa + v*v*v*dkappa_ds;
272 return hypotf (j_t_cart, j_n_cart);
273}
274
275static inline float
276safe_ratio_sq (float num, float den, float fallback)
277{
278 if (!isfinite (num))
279 return fallback;
280 if (!isfinite (den) || fabsf (den) < EPS)
281 den = 1.0f;
282
283 {
284 float x = num / den;
285 if (!isfinite (x))
286 return fallback;
287 return x * x;
288 }
289}
290
291struct fitness_breakdown
292evaluate_motion_fitness (const struct path_table *p,
293 const struct motion_profile *m,
294 float v_beg_target,
295 float v_end_target,
296 float v_max,
297 float a_max,
298 float j_max,
299 const struct fitness_weights *w)
300{
301 struct fitness_breakdown out = {0};
302
303 const int n = PATH_SAMPLE_COUNT;
304
305 out.duration = m->t[n - 1] - m->t[0];
306 out.length = p->s[n - 1] - p->s[0];
307
308 float int_kappa2 = 0;
309 float int_dkappa2 = 0;
310 float int_a2_dt = 0;
311 float int_j2_dt = 0;
312 float int_a_violation_dt = 0;
313 float int_j_violation_dt = 0;
314
315 float max_abs_kappa = 0;
316 float max_abs_dkappa = 0;
317 float max_abs_a = 0;
318 float max_abs_j = 0;
319
320 for (int i = 0; i < n - 1; ++i) {
321 float ds = p->s[i + 1] - p->s[i];
322 float dt = m->t[i + 1] - m->t[i];
323
324 // max
325 float abs_kappa = fabsf (p->kappa [i]);
326 float abs_dkappa = fabsf (p->dkappa_ds[i]);
327 float abs_a = fabsf (m->a [i]);
328 float abs_j = fabsf (m->j [i]);
329 if (abs_kappa > max_abs_kappa ) max_abs_kappa = abs_kappa;
330 if (abs_dkappa > max_abs_dkappa) max_abs_dkappa = abs_dkappa;
331 if (abs_a > max_abs_a ) max_abs_a = abs_a;
332 if (abs_j > max_abs_j ) max_abs_j = abs_j;
333
334 /* geometry terms integrated over s */
335 {
336 float k0 = p->kappa[i ];
337 float k1 = p->kappa[i + 1];
338 float dk0 = p->dkappa_ds[i ];
339 float dk1 = p->dkappa_ds[i + 1];
340
341 int_kappa2 += trapz_step ( k0* k0, k1* k1, ds);
342 int_dkappa2 += trapz_step (dk0*dk0, dk1*dk1, ds);
343 }
344
345 /* dynamic terms integrated over t */
346 if (dt > EPS) {
347 float a0 = total_accel_norm (p->kappa[i ], m->v[i ], m->a[i ]);
348 float a1 = total_accel_norm (p->kappa[i + 1], m->v[i + 1], m->a[i + 1]);
349
350 float j0 = total_jerk_norm (p->kappa[i ], p->dkappa_ds[i ], m->v[i ], m->a[i ], m->j[i ]);
351 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]);
352
353 int_a2_dt += trapz_step (a0*a0, j_max > 0 ? a1*a1 : a1*a1, dt);
354 int_j2_dt += trapz_step (j0*j0, j1*j1, dt);
355
356 float av0 = fmaxf (0, (a0 - a_max) / fmaxf (a_max, EPS));
357 float av1 = fmaxf (0, (a1 - a_max) / fmaxf (a_max, EPS));
358 float jv0 = fmaxf (0, (j0 - j_max) / fmaxf (j_max, EPS));
359 float jv1 = fmaxf (0, (j1 - j_max) / fmaxf (j_max, EPS));
360
361 int_a_violation_dt += trapz_step (av0*av0, av1*av1, dt);
362 int_j_violation_dt += trapz_step (jv0*jv0, jv1*jv1, dt);
363 }
364 }
365
366 out.kappa_rms = sqrtf (int_kappa2 / fmaxf (out.length, EPS));
367 out.dkappa_rms = sqrtf (int_dkappa2 / fmaxf (out.length, EPS));
368 out.accel_rms = sqrtf (int_a2_dt / fmaxf (out.duration, EPS));
369 out.jerk_rms = sqrtf (int_j2_dt / fmaxf (out.duration, EPS));
370
371 out.accel_violation = int_a_violation_dt / fmaxf (out.duration, EPS);
372 out.jerk_violation = int_j_violation_dt / fmaxf (out.duration, EPS);
373
374 /* Weighted costs */
375 out.time_cost = w->time * out.duration;
376 out.length_cost = w->length * out.length;
377
378 out.max_abs_kappa_cost = w->max_abs_kappa * out.max_abs_kappa;
379 out.max_abs_dkappa_cost = w->max_abs_dkappa * out.max_abs_dkappa;
380 out.max_abs_a_cost = w->max_abs_a * out.max_abs_a;
381 out.max_abs_j_cost = w->max_abs_j * out.max_abs_j;
382
383 out.kappa_cost = w->rms_kappa * out.kappa_rms;
384 out.dkappa_cost = w->rms_dkappa * out.dkappa_rms;
385
386 out.accel_rms_cost = w->rms_a * (out.accel_rms / fmaxf (a_max, EPS));
387 out.jerk_rms_cost = w->rms_j * (out.jerk_rms / fmaxf (j_max, EPS));
388
389 out.accel_violation_cost = w->violation_a * out.accel_violation;
390 out.jerk_violation_cost = w->violation_j * out.jerk_violation;
391
392 {
393 float v0_err = m->v[0] - v_beg_target;
394 float vN_err = m->v[n - 1] - v_end_target;
395 float a0_err = m->a[0];
396 float aN_err = m->a[n - 1];
397
398 float v0_den = fmaxf (1.0f, fabsf (v_beg_target));
399 float vN_den = fmaxf (1.0f, fabsf (v_end_target));
400 float a_den = fmaxf (a_max, EPS);
401
402 float term =
403 safe_ratio_sq (v0_err, v0_den, 1e3f)
404 + safe_ratio_sq (vN_err, vN_den, 1e3f)
405 + safe_ratio_sq (a0_err, a_den, 1e3f)
406 + safe_ratio_sq (aN_err, a_den, 1e3f);
407
408 out.terminal_cost = w->terminal * term;
409 }
410
411 out.total_cost =
412 out.time_cost +
413 out.length_cost +
414 out.max_abs_kappa_cost +
415 out.max_abs_dkappa_cost +
416 out.max_abs_a_cost +
417 out.max_abs_j_cost +
418 out.kappa_cost +
419 out.dkappa_cost +
420 out.accel_rms_cost +
421 out.jerk_rms_cost +
422 out.accel_violation_cost +
423 out.jerk_violation_cost +
424 out.terminal_cost;
425
426 return out;
427}
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 @@
1#ifndef INCLUDED_RETIMING_H
2#define INCLUDED_RETIMING_H
3
4#include <raymath.h>
5
6#define EPS 1e-8f
7
8#define PATH_SAMPLE_COUNT 100
9
10typedef Vector2 bezier5[6];
11
12struct path_table {
13 float max_abs_kappa;
14 // S = s[PATH_SAMPLE_COUNT - 1]
15 // T[i] = dr[i]/||dr[i]||
16 // N[i] = { -T[i].y, T[i].x }
17 float u [PATH_SAMPLE_COUNT]; // Bezier parameter
18 Vector2 r [PATH_SAMPLE_COUNT]; // point on curve
19 Vector2 dr [PATH_SAMPLE_COUNT];
20 Vector2 ddr [PATH_SAMPLE_COUNT];
21 float s [PATH_SAMPLE_COUNT]; // arc length from start
22 float kappa [PATH_SAMPLE_COUNT]; // curvature
23 float dkappa_ds [PATH_SAMPLE_COUNT]; // curvature derivative
24};
25
26struct motion_profile {
27 float v_max;
28 float a_max;
29 float j_max;
30 float t[PATH_SAMPLE_COUNT]; // cumulative time at this node
31 float v[PATH_SAMPLE_COUNT]; // ds/dt
32 float a[PATH_SAMPLE_COUNT]; // d2s/dt2
33 float j[PATH_SAMPLE_COUNT]; // d3s/dt3
34};
35
36struct fitness_weights {
37 float time;
38 float length;
39 float max_abs_kappa;
40 float max_abs_dkappa;
41 float max_abs_a;
42 float max_abs_j;
43 float rms_kappa;
44 float rms_dkappa;
45 float rms_a;
46 float rms_j;
47 float violation_a;
48 float violation_j;
49 float terminal;
50};
51
52struct fitness_breakdown {
53 float total_cost;
54
55 float time_cost;
56 float length_cost;
57 float max_abs_kappa_cost;
58 float max_abs_dkappa_cost;
59 float max_abs_a_cost;
60 float max_abs_j_cost;
61 float kappa_cost;
62 float dkappa_cost;
63 float accel_rms_cost;
64 float jerk_rms_cost;
65 float accel_violation_cost;
66 float jerk_violation_cost;
67 float terminal_cost;
68 float failure_cost;
69
70 float duration;
71 float length;
72 float max_abs_kappa;
73 float max_abs_dkappa;
74 float max_abs_a;
75 float max_abs_j;
76 float kappa_rms;
77 float dkappa_rms;
78 float accel_rms;
79 float jerk_rms;
80 float accel_violation;
81 float jerk_violation;
82
83 int feasible;
84};
85
86Vector2 bezier5_point (const bezier5, float u);
87Vector2 bezier5_deriv1 (const bezier5, float u);
88Vector2 bezier5_deriv2 (const bezier5, float u);
89void build_path_table (struct path_table *, const bezier5);
90int build_motion_profile (struct motion_profile *m, const struct path_table *p,
91 float v_beg, float v_end,
92 float v_max, float a_max, float j_max);
93struct fitness_breakdown evaluate_motion_fitness (
94 const struct path_table *, const struct motion_profile *,
95 float v_beg_target,
96 float v_end_target,
97 float v_max,
98 float a_max,
99 float j_max,
100 const struct fitness_weights *);
101
102#endif // INCLUDED_RETIMING_H