#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); }