File size: 20,183 Bytes
7f50cd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
/* NBIPOP-aCMA-ES, CEC2013 reproduction; see ../PORT.md and vendor/.
 * CMA update: Nikolaus Hansen's cmaes 3.55.beta (GNU GPL).
 * Restart rules: Ilya Loshchilov, xacmes.m, NBIPOP configuration.
 * The only objective information enters through value().
 */
#ifdef NATIVE_CHECK
extern double value(double *);
#else
#include "api.h"
#endif
#ifndef DIM
#define DIM 10
#define POP_CAP 3000
#define HIST_CAP 302
#define CACHE_CAP 128
#define BOUND_LO (-100.0)
#define BOUND_HI 100.0
#endif
#define NULL ((void *)0)
#define INF (__builtin_inf())
#define sqrt __builtin_sqrt
#define fabs __builtin_fabs
#define log __ieee754_log
#define exp __ieee754_exp
extern double __ieee754_log(double);
extern double __ieee754_exp(double);

static double min2(double x, double y) { return x < y ? x : y; }
static double max2(double x, double y) { return x > y ? x : y; }
static int finite(double x) { return __builtin_isfinite(x); }
static double box(double x) { return min2(BOUND_HI, max2(BOUND_LO, x)); }
static double power(double x, double y) { return exp(y * log(x)); }

/* Freestanding support for any compiler-generated memory operations. */
void *memset(void *p, int v, unsigned long n) {
    unsigned char *q = p;
    for (unsigned long i = 0; i < n; ++i) q[i] = (unsigned char)v;
    return p;
}
void *memcpy(void *p, const void *s, unsigned long n) {
    unsigned char *q = p;
    const unsigned char *r = s;
    for (unsigned long i = 0; i < n; ++i) q[i] = r[i];
    return p;
}

static unsigned rng;
static unsigned next(unsigned *s) {
    *s ^= *s << 13; *s ^= *s >> 17; *s ^= *s << 5;
    return *s;
}
static double uniform(unsigned *s) { return (next(s) + 0.5) / 4294967296.0; }
/* Marsaglia polar normal sampling. Both coordinates are used within a vector.
 * Each individual's starting state is saved so its exact sample can be
 * regenerated without storing a population-sized matrix in WASM memory. */
static void normals(unsigned *s, double *z) {
    for (int j = 0; j < DIM; j += 2) {
        double a, b, r;
        do {
            a = 2 * uniform(s) - 1;
            b = 2 * uniform(s) - 1;
            r = a*a + b*b;
        } while (r >= 1 || r == 0);
        double f = sqrt(-2 * log(r) / r);
        z[j] = a*f;
        if (j + 1 < DIM) z[j+1] = b*f;
    }
}

static double C[DIM][DIM], B[DIM][DIM], BD[DIM][DIM];
static double positive[DIM][DIM], negative[DIM][DIM], check[DIM][DIM];
static double D[DIM], diagC[DIM], pc[DIM], ps[DIM];
static double mean[DIM], oldmean[DIM], newmean[DIM], zmean[DIM];
static double point[DIM], z[DIM], y[DIM], zneg[DIM];
static double eigenvalues[DIM], eigentmp[DIM];
static double fit[POP_CAP], selected[POP_CAP], weights[POP_CAP];
static double norms[POP_CAP], factors[POP_CAP];
static unsigned seeds[POP_CAP];
static double cached_z[CACHE_CAP][DIM], cached_y[CACHE_CAP][DIM];
static int order[POP_CAP], normorder[POP_CAP];
#define SORT_CAP ((POP_CAP > HIST_CAP) ? POP_CAP : HIST_CAP)
static double scratch[SORT_CAP];
static double hist[10 + 30*DIM], histbest[HIST_CAP], histmedian[HIST_CAP];
static double dfithist[21 + 3*DIM], bweights[DIM];
static int equalhist[10 + DIM];
static int lambda, mu, iteration, used, limit, hlen, hcount, longlen;
static int dfitlen, validfit, iniphase;
static double sigma, mueff, cc, cs, c1, cmu, cneg, damps, chi;
static double best_run;
static int eigen_ok;
/* Implementation work allowance for the fixed 50M VM-fuel contract. These
 * conservative operation charges are independent of objective values. They
 * stop computation, never change an update or choose another optimizer. */
static double work_left;
static int work_stop;
static int debit(double cost) {
    work_left -= cost;
    if (work_left < 0) work_stop = 1;
    return !work_stop;
}

static double myhypot(double a, double b) {
    double x = fabs(a), t = fabs(b);
    if (x < t) { double v = x; x = t; t = v; }
    if (x == 0) return 0;
    t /= x;
    return x * sqrt(1 + t*t);
}
static void QLalgo2(int, double *, double *, double [DIM][DIM]);
static void Householder2(int, double [DIM][DIM], double *, double *);
#define FATAL(a,b,c,d) __builtin_trap()
#include "eigen.inc"

static int eig(double a[DIM][DIM], double b[DIM][DIM], double *values) {
    if (!debit(16.0*DIM*DIM*DIM + 100.0*DIM*DIM)) return 0;
    eigen_ok = 1;
    Eigen(DIM, a, values, b, eigentmp);
    for (int i = 0; i < DIM; ++i) if (!finite(values[i])) return 0;
    return eigen_ok;
}

/* Heapsort indices with deterministic tie handling; no library qsort. */
static int later(const double *key, int a, int b) {
    return key[a] > key[b] || (key[a] == key[b] && a > b);
}
static void sift(const double *key, int *idx, int root, int n) {
    for (;;) {
        int child = 2*root + 1;
        if (child >= n) return;
        if (child+1 < n && later(key, idx[child+1], idx[child])) ++child;
        if (!later(key, idx[child], idx[root])) return;
        int t = idx[root]; idx[root] = idx[child]; idx[child] = t;
        root = child;
    }
}
static void indexsort(const double *key, int *idx, int n) {
    for (int i = 0; i < n; ++i) idx[i] = i;
    for (int i = n/2; i-- > 0;) sift(key, idx, i, n);
    for (int end = n-1; end > 0; --end) {
        int t = idx[0]; idx[0] = idx[end]; idx[end] = t;
        sift(key, idx, 0, end);
    }
}
/* In-place heapsort of a scratch copy for percentiles and medians. */
static void dsift(double *v, int r, int n) {
    for (;;) {
        int c = 2*r+1;
        if (c >= n) return;
        if (c+1 < n && v[c+1] > v[c]) ++c;
        if (v[r] >= v[c]) return;
        double t = v[r]; v[r] = v[c]; v[c] = t; r = c;
    }
}
static void dsort(double *v, int n) {
    for (int i = n/2; i-- > 0;) dsift(v, i, n);
    for (int end = n-1; end > 0; --end) {
        double t = v[0]; v[0] = v[end]; v[end] = t; dsift(v, 0, end);
    }
}
static double nth(double *v, int n, int k) {
    int left = 0, right = n-1;
    while (left < right) {
        double pivot = v[(left+right)/2];
        int i = left, j = right;
        while (i <= j) {
            while (v[i] < pivot) ++i;
            while (v[j] > pivot) --j;
            if (i <= j) { double t = v[i]; v[i++] = v[j]; v[j--] = t; }
        }
        if (k <= j) right = j;
        else if (k >= i) left = i;
        else break;
    }
    return v[k];
}
static double median(const double *v, int n) {
    for (int i = 0; i < n; ++i) scratch[i] = v[i];
    double upper = nth(scratch,n,n/2);
    if (n % 2) return upper;
    double lower = scratch[0];
    for (int i = 1; i < n/2; ++i) lower = max2(lower,scratch[i]);
    return 0.5*lower + 0.5*upper;
}
static double percentile(const double *sorted, int n, double p) {
    double pos = p*n - 0.5;
    if (pos <= 0) return sorted[0];
    if (pos >= n-1) return sorted[n-1];
    int k = (int)pos;
    return sorted[k] + (pos-k)*(sorted[k+1]-sorted[k]);
}
static void push(double *v, int n, double x) {
    for (int i = n-1; i > 0; --i) v[i] = v[i-1];
    v[0] = x;
}
static double query(const double *x) {
    for (int j = 0; j < DIM; ++j) point[j] = box(x[j]);
    double f = value(point);
    ++used;
    best_run = min2(best_run, f);
    return f;
}
static void transform(const double *normal, double *step) {
    for (int j = 0; j < DIM; ++j) {
        double s = 0;
        for (int k = 0; k < DIM; ++k) s += BD[j][k] * normal[k];
        step[j] = s;
    }
}
static void replay(int i) {
    if (i < CACHE_CAP) {
        for (int j = 0; j < DIM; ++j) { z[j] = cached_z[i][j]; y[j] = cached_y[i][j]; }
        return;
    }
    unsigned s = seeds[i];
    normals(&s, z);
    transform(z, y);
}

static void parameters(void) {
    mu = lambda/2;
    double sum = 0, sq = 0;
    for (int k = 0; k < mu; ++k) {
        weights[k] = log(mu + 0.5) - log(k + 1.0);
        sum += weights[k]; sq += weights[k]*weights[k];
    }
    mueff = sum*sum/sq;
    for (int k = 0; k < mu; ++k) weights[k] /= sum;
    cc = (4 + mueff/DIM) / (DIM + 4 + 2*mueff/DIM);
    cs = (mueff + 2) / (DIM + mueff + 3);
    c1 = min2(2, lambda/3.0) / ((DIM+1.3)*(DIM+1.3) + mueff);
    cmu = min2(1-c1, min2(2, lambda/3.0)*(mueff-2+1/mueff)
                         / ((DIM+2.0)*(DIM+2.0)+mueff));
    cneg = (1-cmu)*0.25*mueff / ((DIM+2)*sqrt(DIM+2) + 2*mueff);
    damps = 1 + 2*max2(0, sqrt((mueff-1)/(DIM+1))-1) + cs;
    chi = sqrt(DIM)*(1 - 1.0/(4*DIM) + 1.0/(21*DIM*DIM));
}

static void initialize(double sigmafactor, int source_run, int basepop) {
    debit(5000.0+1000*DIM);
    iteration = longlen = 0;
    /* initializeRun precedes the BIPOP population override in xacmes.m. */
    double initial_lambda = basepop * power(2, source_run-1);
    hlen = 10 + (int)__builtin_ceil(30*DIM/initial_lambda);
    hcount = 1;
    for (int i = 0; i < 10+DIM; ++i) equalhist[i] = 0;
    for (int j = 0; j < DIM; ++j) {
        mean[j] = BOUND_LO + (BOUND_HI-BOUND_LO)*uniform(&rng);
        oldmean[j] = mean[j];
        pc[j] = ps[j] = bweights[j] = 0;
        D[j] = diagC[j] = 1;
        for (int k = 0; k < DIM; ++k) C[j][k] = B[j][k] = BD[j][k] = (j == k);
    }
    best_run = INF;
    hist[0] = query(mean);       /* EvalInitialX = yes */
    /* xacmes overrides sigma after initializeRun; retain that order. */
    sigma = 0.6*(BOUND_HI-BOUND_LO)*sigmafactor;
    dfithist[0] = 1; dfitlen = 1; validfit = 0; iniphase = 1;
    parameters();
}

static void boundary_penalty(void) {
    for (int i = 0; i < lambda; ++i) scratch[i] = fit[i];
    dsort(scratch, lambda);
    double sumdiag = 0;
    for (int j = 0; j < DIM; ++j) sumdiag += diagC[j];
    double delta = (percentile(scratch, lambda, .75)-percentile(scratch, lambda, .25))
                   / sumdiag / (sigma*sigma);
    if (!finite(delta) || delta == 0) {
        int bad = !finite(delta);
        delta = dfithist[0];
        for (int i = 1; i < dfitlen; ++i)
            delta = bad ? max2(delta,dfithist[i]) : min2(delta,dfithist[i]);
    } else if (!validfit) {
        dfitlen = 0; validfit = 1;
    }
    int maxhist = (int)__builtin_ceil(20 + 3.0*DIM/lambda);
    if (dfitlen < maxhist) ++dfitlen;
    push(dfithist, dfitlen, delta);
    int outside = 0;
    for (int j = 0; j < DIM; ++j) if (mean[j] != box(mean[j])) outside = 1;
    if (iniphase && outside) {
        double weight = 2.0002 * median(dfithist, dfitlen);
        for (int j = 0; j < DIM; ++j) bweights[j] = weight * (sumdiag/DIM) / diagC[j];
        if (validfit && iteration > 2) iniphase = 0;
    }
    if (outside) {
        double multiplier = power(1.2, min2(1, mueff/10/DIM));
        for (int j = 0; j < DIM; ++j) {
            double diff = mean[j]-box(mean[j]), move = mean[j]-oldmean[j];
            if (fabs(diff) > 3*max2(1,sqrt(DIM)/mueff)*sigma*sqrt(diagC[j])
                && ((diff > 0 && move > 0) || (diff < 0 && move < 0)))
                bweights[j] *= multiplier;
        }
    }
    for (int i = 0; i < lambda; ++i) {
        replay(i);
        double penalty = 0;
        for (int j = 0; j < DIM; ++j) {
            double raw = mean[j] + sigma*y[j], difference = box(raw)-raw;
            penalty += bweights[j]*difference*difference;
        }
        selected[i] = fit[i] + penalty;
    }
}

/* Returns 0 to continue, 1 for a source stopping criterion, 2 for the
 * interface's query/storage limit. A partial last population is evaluated
 * without a further distribution update. */
static int generation(double maxiter) {
    double replay_extra = lambda > CACHE_CAP ? 50.0*DIM*DIM*lambda : 0;
    if (!debit(lambda*(35.0*DIM*DIM+350.0*DIM+1000)
               + 20.0*DIM*DIM + 100.0*DIM + 1000 + 30.0*longlen
               + replay_extra)) return 2;
    ++iteration;
    for (int i = 0; i < lambda; ++i) {
        if (used >= limit) return 2;
        seeds[i] = rng;
        normals(&rng, z); transform(z, y);
        if (i < CACHE_CAP) for (int j = 0; j < DIM; ++j) {
            cached_z[i][j] = z[j]; cached_y[i][j] = y[j];
        }
        for (int j = 0; j < DIM; ++j) point[j] = mean[j] + sigma*y[j];
        fit[i] = query(point);
    }
    if (used >= limit) return 2;
    boundary_penalty();
    indexsort(selected, order, lambda);
    double lo = fit[0], hi = fit[0];
    for (int i = 1; i < lambda; ++i) { lo = min2(lo,fit[i]); hi = max2(hi,fit[i]); }
    if (hcount < hlen) ++hcount;
    push(hist, hcount, lo);
    int grow = longlen < 120 + (int)__builtin_ceil(30.0*DIM/lambda)
               || (iteration % 5 == 0 && longlen < 20000);
    if (grow && longlen == HIST_CAP) return 2;
    if (grow) ++longlen;
    push(histbest, longlen, lo);
    push(histmedian, longlen, median(fit,lambda));
    for (int j = 0; j < DIM; ++j) {
        newmean[j] = zmean[j] = 0;
        for (int k = 0; k < DIM; ++k) positive[j][k] = negative[j][k] = 0;
    }
    /* Weighted positive update and recombination, same samples as evaluated. */
    for (int k = 0; k < mu; ++k) {
        replay(order[k]);
        for (int j = 0; j < DIM; ++j) {
            newmean[j] += weights[k]*(mean[j]+sigma*y[j]);
            zmean[j] += weights[k]*z[j];
        }
        /* Source arpos uses the rounded arx, not the pre-addition y. */
        for (int j = 0; j < DIM; ++j) y[j] = ((mean[j]+sigma*y[j])-mean[j])/sigma;
        for (int j = 0; j < DIM; ++j)
            for (int h = 0; h <= j; ++h) positive[j][h] += weights[k]*y[j]*y[h];
    }
    double psnorm = 0;
    for (int j = 0; j < DIM; ++j) {
        double v = 0;
        for (int h = 0; h < DIM; ++h) v += B[j][h]*zmean[h];
        ps[j] = (1-cs)*ps[j] + sqrt(cs*(2-cs)*mueff)*v;
        psnorm += ps[j]*ps[j];
    }
    int hsig = sqrt(psnorm)/sqrt(1-power(1-cs,2*iteration))/chi < 1.4 + 2.0/(DIM+1);
    for (int j = 0; j < DIM; ++j) {
        pc[j] = (1-cc)*pc[j] + hsig*sqrt(cc*(2-cc)*mueff)*(newmean[j]-mean[j])/sigma;
    }
    /* Active update: invert the ordering of lengths of the worst mu z's. */
    for (int k = 0; k < mu; ++k) {
        replay(order[lambda-1-k]);
        double length = 0;
        for (int j = 0; j < DIM; ++j) length += z[j]*z[j];
        norms[k] = sqrt(length);
    }
    indexsort(norms, normorder, mu);
    double trace = 0;
    for (int k = 0; k < mu; ++k) {
        int i = normorder[k];
        double reversed = norms[normorder[mu-1-k]];
        factors[i] = reversed/norms[i];
        trace += weights[i]*reversed*reversed;
    }
    int needcheck = 1-cneg*trace < 0.66;
    if (needcheck) for (int j = 0; j < DIM; ++j)
        for (int h = 0; h < DIM; ++h) check[j][h] = 0;
    for (int k = 0; k < mu; ++k) {
        replay(order[lambda-1-k]);
        for (int j = 0; j < DIM; ++j) { zneg[j] = z[j]*factors[k]; y[j] *= factors[k]; }
        for (int j = 0; j < DIM; ++j) for (int h = 0; h <= j; ++h) {
            negative[j][h] += weights[k]*y[j]*y[h];
            if (needcheck) check[j][h] += weights[k]*zneg[j]*zneg[h];
        }
    }
    double cn = cneg;
    if (needcheck) {
        for (int j = 0; j < DIM; ++j) for (int h = 0; h < j; ++h) check[h][j] = check[j][h];
        if (!eig(check,check,eigenvalues)) return work_stop ? 2 : 1;
        cn = min2(cneg, (1-cmu)*0.34/eigenvalues[DIM-1]);
    }
    double factor = 1-c1-cmu+0.5*cn+(1-hsig)*c1*cc*(2-cc);
    for (int j = 0; j < DIM; ++j) {
        for (int h = 0; h <= j; ++h) {
            C[j][h] = factor*C[j][h] + c1*pc[j]*pc[h]
                    + (cmu+0.5*cn)*positive[j][h] - cn*negative[j][h];
            C[h][j] = C[j][h];
        }
        diagC[j] = C[j][j]; oldmean[j] = mean[j]; mean[j] = newmean[j];
    }
    sigma *= exp(min2(1, (sqrt(psnorm)/chi-1)*cs/damps));
    double period = 1/(c1+cmu+cneg)/DIM/10;
    if (iteration - __builtin_floor(iteration/period)*period < 1) {
        if (!eig(C,B,D)) return work_stop ? 2 : 1;
        if (D[0] <= 0 || D[DIM-1] > 1e14*D[0]) return 1;
        for (int j = 0; j < DIM; ++j) D[j] = sqrt(D[j]);
        for (int j = 0; j < DIM; ++j) for (int h = 0; h < DIM; ++h) BD[j][h] = B[j][h]*D[h];
    }
    if (!finite(sigma) || sigma <= 0) return 1;
    if (sigma > 1e10*D[DIM-1]) {
        double scale = sigma/D[DIM-1]; sigma /= scale;
        for (int j = 0; j < DIM; ++j) {
            pc[j] *= scale; D[j] *= scale; diagC[j] *= scale*scale;
            for (int h = 0; h < DIM; ++h) { C[j][h] *= scale*scale; BD[j][h] *= scale; }
        }
    }
    double maxdiag = 0;
    for (int j = 0; j < DIM; ++j) {
        if (!finite(mean[j]) || !finite(diagC[j]) || diagC[j] <= 0) return 1;
        maxdiag = max2(maxdiag, sqrt(diagC[j]));
    }
    sigma = min2(sigma, 0.5*(BOUND_HI-BOUND_LO)/maxdiag); /* source maxdx */
    int tolx = 1, axis = 1;
    for (int j = 0; j < DIM; ++j) {
        double sd = sqrt(diagC[j]);
        if (mean[j] == mean[j] + 0.2*sigma*sd) return 1;
        if (sigma*max2(fabs(pc[j]),sd) >= 1e-12*0.6*(BOUND_HI-BOUND_LO)) tolx = 0;
        if (mean[j] != mean[j]+0.1*sigma*BD[j][iteration%DIM]) axis = 0;
    }
    if (tolx || axis || iteration >= maxiter) return 1;
    int eqidx = (int)__builtin_ceil(0.1+lambda/4.0);
    if (selected[order[0]] == selected[order[eqidx]]) {
        for (int i = 9+DIM; i > 0; --i) equalhist[i] = equalhist[i-1];
        equalhist[0] = iteration;
        if (equalhist[9+DIM] > iteration-3*(10+DIM)) return 1;
    }
    double hmin = hist[0], hmax = hist[0];
    for (int i = 1; i < hcount; ++i) { hmin = min2(hmin,hist[i]); hmax = max2(hmax,hist[i]); }
    if (iteration > 2 && max2(hmax,selected[order[0]])
                        -min2(hmin,selected[order[0]]) == 0) return 1;
    if (iteration > 2 && max2(hmax,selected[order[lambda-1]])
                        -min2(hmin,selected[order[0]]) <= 1e-12) return 1;
    if (iteration >= hlen && hmax-hmin <= 1e-12) return 1;
    int l = longlen/3;
    if (iteration > DIM*(5+100.0/lambda) && longlen > 100
        && median(histmedian,l) >= median(histmedian+longlen-l-1,l+1)
        && median(histbest,l) >= median(histbest+longlen-l-1,l+1)) return 1;
    return 0;
}

void run(int dimension, int query_limit, int random_state) {
    if (dimension != DIM || query_limit < 1) return;
    rng = (unsigned)random_state;
    if (!rng) rng = 0x9e3779b9u;
    used = 0; limit = query_limit;
    work_left = 40000000; work_stop = 0;
    int basepop = 4 + (int)(3*log(DIM));
    while (used < limit) {   /* Adapter.m starts a fresh scheduler if necessary. */
        int run_id = 0, smallruns = 1, nrestarts = 9;
        double smallbudget = 0, largebudget = 0, ratio = 1;
        double smallbest = INF, largebest = INF;
        int continue_small = 0;
        while ((run_id <= nrestarts || continue_small) && used < limit) {
            ++run_id;
            int before = used, small = 0;
            double nominal_pop = basepop*power(2,run_id-smallruns);
            double sigmafactor, maxiter;
            if (run_id > 2 && smallbudget < ratio*largebudget) {
                small = 1; ++nrestarts; ++smallruns;
                lambda = basepop;
                sigmafactor = power(0.01,uniform(&rng));
                maxiter = 0.5*largebudget/lambda;
            } else {
                /* The source doubles population in the large regime. */
                if (nominal_pop > POP_CAP) return;
                lambda = (int)(nominal_pop+0.5);
                sigmafactor = power(1.6,-(run_id-smallruns));
                maxiter = INF;
            }
            if (lambda > POP_CAP) return;
            maxiter = min2(maxiter,100+50.0*(DIM+3)*(DIM+3)/sqrt(lambda));
            initialize(sigmafactor,run_id,basepop);
            if (work_stop) return;
            int stopped = 0;
            while (!stopped && used < limit) stopped = generation(maxiter);
            if (stopped == 2 || used >= limit) return;
            if (used < limit) query(mean);  /* cmaes_finalize: evaluate mean */
            if (!small || run_id < 3) largebest = min2(largebest,best_run);
            if (small || run_id < 3) smallbest = min2(smallbest,best_run);
            ratio = largebest < smallbest ? 0.5 : 2;
            double spent = used-before;
            /* Preserve the official wrapper's double first-small accounting. */
            if (run_id == 1) smallbudget = 2*spent;
            else if (small) smallbudget += spent;
            else largebudget += spent;
            continue_small = smallbudget < ratio*largebudget;
        }
    }
}