File: CMAESTest.cpp

package info (click to toggle)
simbody 3.7%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 72,876 kB
  • sloc: cpp: 248,828; ansic: 18,240; sh: 29; makefile: 24
file content (576 lines) | stat: -rw-r--r-- 18,593 bytes parent folder | download | duplicates (4)
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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
/* -------------------------------------------------------------------------- *
 *                        Simbody(tm): SimTKmath                              *
 * -------------------------------------------------------------------------- *
 * This is part of the SimTK biosimulation toolkit originating from           *
 * Simbios, the NIH National Center for Physics-Based Simulation of           *
 * Biological Structures at Stanford, funded under the NIH Roadmap for        *
 * Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody.  *
 *                                                                            *
 * Portions copyright (c) 2006-14 Stanford University and the Authors.        *
 * Authors: Chris Dembia                                                      *
 * Contributors:                                                              *
 *                                                                            *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may    *
 * not use this file except in compliance with the License. You may obtain a  *
 * copy of the License at http://www.apache.org/licenses/LICENSE-2.0.         *
 *                                                                            *
 * Unless required by applicable law or agreed to in writing, software        *
 * distributed under the License is distributed on an "AS IS" BASIS,          *
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   *
 * See the License for the specific language governing permissions and        *
 * limitations under the License.                                             *
 * -------------------------------------------------------------------------- */

// TODO
// 3. restart.
// 5. memory leaks.
// 6. how to disable reading of cmaes_signals.par.
// 9. allow verbosity; diagnostics level.
// 12 all the cmaes options.
// 14 threading.
//
// 

#include "SimTKmath.h"
#include "OptimizerSystems.h"

#include <iostream>
using std::cout;
using std::endl;
using SimTK::Vector;
using SimTK::Real;
using SimTK::Optimizer;
using SimTK::OptimizerSystem;

// Utilities.
// ==========
bool vectorsAreEqual(const Vector& actual, const Vector& expected, double tol,
        bool printWhenNotEqual = true)
{
    unsigned int N = actual.size();
    bool isEqual = true;
    for (unsigned int i=0; i < N; ++i) {
        if(!SimTK::Test::numericallyEqual(actual[i], expected[i], 1, tol)) {
            if (printWhenNotEqual) {
                printf("error actual[%d] = %f  expected[%d] = %f \n",
                        i, actual[i], i, expected[i]);
            }
            isEqual = false;
        }
        else {
            if (!printWhenNotEqual) {
                printf("equal actual[%d] = %f  expected[%d] = %f \n",
                        i, actual[i], i, expected[i]);
            }
        }
    }
    return isEqual;
}

#define SimTK_TEST_OPT(opt, results, tol) \
do { \
Real funval = opt.optimize(results); \
const TestOptimizerSystem& sys = \
    *static_cast<const TestOptimizerSystem*>(&opt.getOptimizerSystem()); \
bool passed = vectorsAreEqual(results, sys.optimalParameters(), tol); \
if (!SimTK::Test::numericallyEqual(funval, sys.optimalValue(), 1, tol)) { \
    passed = false; \
} \
if (!passed) printf("f = %f (expected: %f)", funval, sys.optimalValue()); \
if (!passed) {SimTK_TEST_FAILED("Optimization failed.");} \
} \
while(false)


// Subtests.
// =========

void testCMAESAvailable() {
    SimTK_TEST(Optimizer::isAlgorithmAvailable(SimTK::CMAES));
}

// If we try to create an OptimizerSystem with only one parameter,
// we should get an exception.
void testTwoOrMoreParameters() {
    SimTK_TEST_MUST_THROW_EXC(Optimizer opt(Cigtab(1), SimTK::CMAES),
            SimTK::Exception::ValueOutOfRange
            );
}

// This tests that setting max iterations works using the Simbody
// interface. CMAES cannot find the optimum of Cigtab in 500 iterations (or
// less) given the initial condition we use.
void testMaxIterations() {

    Cigtab sys(22);
    int N = sys.getNumParameters();

    // set initial conditions.
    Vector results(N);
    results.setTo(0.5);

    // Create optimizer; set settings.
    Optimizer opt(sys, SimTK::CMAES);
    opt.setConvergenceTolerance(1e-12);
    opt.setAdvancedRealOption("init_stepsize", 0.3);
    opt.setMaxIterations(500);

    // Optimize!
    Real f = opt.optimize(results);

    // Make sure the result is not correct.
    SimTK_TEST_NOTEQ_TOL(results, sys.optimalParameters(), 1e-5);
}

// This also tests that setting max iterations works using the Simbody
// interface, because Cigtab is not optimized in under the default number of
// max iterations (1000 at the time of this writing).
void testCigtabOptimum() {

    Cigtab sys(22);
    int N = sys.getNumParameters();

    // set initial conditions.
    Vector results(N);
    results.setTo(0.5);

    // Create optimizer; set settings.
    Optimizer opt(sys, SimTK::CMAES);
    opt.setConvergenceTolerance(1e-12);
    opt.setMaxIterations(5000);
    opt.setAdvancedRealOption("init_stepsize", 0.3);
    // Sometimes this test fails, so choose a seed where the test passes.
    opt.setAdvancedIntOption("seed", 42);
    opt.setAdvancedRealOption("maxTimeFractionForEigendecomposition", 1);
    
    // Optimize!
    SimTK_TEST_OPT(opt, results, 1e-5);
}

void testParameterLimits() {

    Easom sys;
    int N = sys.getNumParameters();

    // No exception if initial guess is on the border of the limits.
    Vector results(N);
    results.setTo(100);

    Optimizer opt(sys, SimTK::CMAES);
    opt.optimize(results);

    // Exception if our initial guess is out of bounds.
    results.setTo(100.01);
    SimTK_TEST_MUST_THROW_EXC(opt.optimize(results),
            SimTK::Exception::APIArgcheckFailed
            );
}

// Make sure that we are able to set init_stepsize (sigma) using Simbody's
// interface, and that with appropriate step size, we can find the optimum of
// Ackley's function.
void testSigmaAndAckleyOptimum() {

    Ackley sys(2);
    int N = sys.getNumParameters();

    // set initial conditions.
    Vector results(N);
    // Far from optimum, but within the parameter limits.
    results.setTo(25);

    // Create optimizer; set settings.
    Optimizer opt(sys, SimTK::CMAES);
    opt.setConvergenceTolerance(1e-12);
    opt.setMaxIterations(5000);
    opt.setAdvancedIntOption("popsize", 50);
    opt.setAdvancedIntOption("seed", 30);
    opt.setAdvancedRealOption("maxTimeFractionForEigendecomposition", 1);

    // Default init_stepsize leaves us in a local minimum.
    // ===================================================

    // Optimize!
    Real f1 = opt.optimize(results);

    static const Real TOL = 1e-5;

    // Should end up in the 24.9997 local minimum.
    Vector expectedLocalMinimum(N, 24.999749);
    SimTK_TEST(vectorsAreEqual(results, expectedLocalMinimum, TOL));

    // Can find the optimum with an appropriate step size.
    // ===================================================
    // init_stepsize should be 1/4 the range of possible values.
    opt.setAdvancedRealOption("init_stepsize", 0.5 * 64);

    // Optimize!  Can now find the solution.
    results.setTo(25);
    SimTK_TEST_OPT(opt, results, TOL);
}

// To find the optimum of this function, we need lots of samples. Thus, this
// test makes sure that we are able to modify this setting.
void testDropWaveOptimumLambda() {

    DropWave sys;
    int N = sys.getNumParameters();

    // set initial conditions.
    Vector results(N);
    results.setTo(2);

    // Create optimizer; set settings.
    Optimizer opt(sys, SimTK::CMAES);
    opt.setConvergenceTolerance(1e-5);
    opt.setMaxIterations(5000);
    opt.setAdvancedRealOption("init_stepsize", 3.5);
    // With default popsize, this test fails. So if this test passes, we know we
    // can set popsize.
    opt.setAdvancedIntOption("popsize", 1000);
    // Sometimes, we need more function evaluations.
    opt.setAdvancedIntOption("stopMaxFunEvals", 100000);
    opt.setAdvancedIntOption("seed", 10);
    opt.setAdvancedRealOption("maxTimeFractionForEigendecomposition", 1);

    SimTK_TEST_OPT(opt, results, 1e-2);
}

void testMaxFunEvals() {

    Cigtab sys(22);
    int N = sys.getNumParameters();

    // set initial conditions.
    Vector results(N);
    results.setTo(5);

    // Create optimizer; set settings.
    Optimizer opt(sys, SimTK::CMAES);
    opt.setConvergenceTolerance(1e-12);
    opt.setAdvancedRealOption("init_stepsize", 0.3);
    opt.setAdvancedIntOption("seed", 10);
    opt.setAdvancedRealOption("maxTimeFractionForEigendecomposition", 1);
    
    // Will not find optimum to tolerance with small # function evals.
    // =================================================================
    opt.setAdvancedIntOption("stopMaxFunEvals", 1);
    // Optimize!
    Real f1 = opt.optimize(results);

    // With default max function evaluations, should not have found optimum.
    SimTK_TEST(!vectorsAreEqual(results, sys.optimalParameters(), 1e-4, false));

    // With enough function evals, we can find the optimum.
    // ====================================================
    opt.setAdvancedIntOption("stopMaxFunEvals", 100000);

    // Check that the result is correct.
    results.setTo(5);
    SimTK_TEST_OPT(opt, results, 1e-4);
}

void testSeed() {

    Ackley sys(22);
    int N = sys.getNumParameters();

    // set initial conditions.
    Vector results(N);
    results.setTo(25);

    // Create optimizer; set settings.
    Optimizer opt(sys, SimTK::CMAES);
    opt.setConvergenceTolerance(1e-12);
    opt.setAdvancedRealOption("init_stepsize", 1);
    
    // A negative seed causes an exception to be thrown upon optimization.
    // ===================================================================
    opt.setAdvancedIntOption("seed", -10);
    SimTK_TEST_MUST_THROW_EXC(
            Real f = opt.optimize(results),
            SimTK::Exception::ValueWasNegative
    );

    // Using the same seed gives identical results, if maxtime is 1.
    // =============================================================
    // We end prematurely because non-identical seeds may lead to similar
    // results at the optimum; we don't want to be at the optimum.
    opt.setMaxIterations(100);
    opt.setAdvancedIntOption("seed", 42);

    // First optimization.
    Real f1 = opt.optimize(results);
    Vector results1 = results;

    // Second optimization.
    opt.setAdvancedRealOption("maxTimeFractionForEigendecomposition", 1);
    results.setTo(25);
    Real f2 = opt.optimize(results);
    Vector results2 = results;

    // Third optimization, which should now produce identical values to f2.
    results.setTo(25);
    Real f3 = opt.optimize(results);
    Vector results3 = results;

    // Print results of the optimizations.
    /**
    printf("Seed: f1 = %f params1 = ", f1);
    for (unsigned int i = 0; i < N; ++i) {
        printf(" %f", results1[i]);
    }
    printf("\n");
    printf("Seed: f2 = %f params2 = ", f2);
    for (unsigned int i = 0; i < N; ++i) {
        printf(" %f", results2[i]);
    }
    printf("\n");
    printf("Seed: f3 = %f params3 = ", f3);
    for (unsigned int i = 0; i < N; ++i) {
        printf(" %f", results3[i]);
    }
    printf("\n");
    */

    // f1 and f2 don't match.
    // ----------------------
    // Using the same seed without maxtime leads to identical results. This
    // helps ensure that we are able to set maxtime.
    /** TODO too often, we DO get a match, which isn't bad.
    SimTK_TEST_NOTEQ_TOL(f1, f2, 1e-12);
    SimTK_TEST(!vectorsAreEqual(results1, results2, 1e-10, false));
    */

    // f2 and f3 match.
    // ----------------
    // Using the same seed leads to the same results.
    SimTK_TEST_EQ_TOL(f2, f3, 1e-10);
    SimTK_TEST(vectorsAreEqual(results2, results3, 1e-10));

    // Using a different seed gives different results.
    // ===============================================
    opt.setAdvancedIntOption("seed", 50);
    results.setTo(25);
    Real f4 = opt.optimize(results);
    Vector results4 = results;

    // Using different seeds leads to different results.
    SimTK_TEST_NOTEQ_TOL(f2, f4, 1e-4);
    SimTK_TEST(!vectorsAreEqual(results2, results4, 1e-10, false));
}

void testConvergenceTolerance() {

    Cigtab sys(2);
    int N = sys.getNumParameters();

    // set initial conditions.
    Vector results(N);
    // Far from optimum, but within the parameter limits.
    results.setTo(5);

    // Create optimizer; set settings.
    Optimizer opt(sys, SimTK::CMAES);
    opt.setAdvancedIntOption("seed", 10);
    opt.setAdvancedRealOption("maxTimeFractionForEigendecomposition", 1);

    Real looseTolerance = 0.001;
    Real tightTolerance = 1e-10;

    // Use a loose tolerance.
    // ======================
    opt.setConvergenceTolerance(looseTolerance);

    // Optimize!
    results.setTo(5);
    Real f = opt.optimize(results);

    // Optimal value should be correct within the loose tolerance.
    SimTK_TEST_EQ_TOL(f, sys.optimalValue(), looseTolerance);

    // If the setting of the convergence tolerance is working, we can't hit the
    // tight tolerance.
    /* TODO doesn't always pass, which is not a bad thing.
    SimTK_TEST_NOTEQ_TOL(f, sys.optimalValue(), tightTolerance);
    */

    // Use the tight tolerance.
    // ========================
    opt.setConvergenceTolerance(tightTolerance);
    results.setTo(5);
    f = opt.optimize(results);
    SimTK_TEST_EQ_TOL(f, sys.optimalValue(), tightTolerance);
}

// CMA-ES is able to minimize the Rosenbrock function.
// https://www.lri.fr/~hansen/cmsa-versus-cma.html
void testRosenbrock() {

    Rosenbrock sys(22);
    int N = sys.getNumParameters();

    // set initial conditions.
    Vector results(N);
    results.setTo(0.5);

    // Create optimizer; set settings.
    Optimizer opt(sys, SimTK::CMAES);
    opt.setConvergenceTolerance(1e-12);
    opt.setMaxIterations(100000);
    opt.setAdvancedRealOption("init_stepsize", 0.3);
    opt.setAdvancedIntOption("seed", 42);
    opt.setAdvancedRealOption("maxTimeFractionForEigendecomposition", 1);

    // Optimize!
    SimTK_TEST_OPT(opt, results, 1e-6);
}

void testSchwefel() {

    Schwefel sys(4);
    int N = sys.getNumParameters();

    // set initial conditions.
    Vector results(N);
    results.setTo(200);

    // Create optimizer; set settings.
    Optimizer opt(sys, SimTK::CMAES);
    // Only know the solution to 4 digits.
    opt.setConvergenceTolerance(1e-4);
    opt.setAdvancedIntOption("popsize", 200);
    opt.setAdvancedRealOption("init_stepsize", 300);
    opt.setAdvancedIntOption("seed", 42);
    opt.setAdvancedRealOption("maxTimeFractionForEigendecomposition", 1);
    
    // Optimize!
    SimTK_TEST_OPT(opt, results, 1e-4);
}

void testEasom() {

    Easom sys;
    int N = sys.getNumParameters();

    // set initial conditions.
    Vector results(N);
    results.setTo(-10);

    // Create optimizer; set settings.
    Optimizer opt(sys, SimTK::CMAES);
    // TODO opt.setDiagnosticsLevel(3);
    opt.setAdvancedIntOption("popsize", 500);
    opt.setAdvancedRealOption("init_stepsize", 25);
    opt.setAdvancedIntOption("seed", 42);
    opt.setAdvancedRealOption("maxTimeFractionForEigendecomposition", 1);
    
    // Optimize!
    SimTK_TEST_OPT(opt, results, 1e-5);
}

void testStopFitness() {

    Ackley sys(2);
    int N = sys.getNumParameters();

    // set initial conditions.
    Vector results(N);
    // Far from optimum, but within the parameter limits.
    results.setTo(25);

    // Create optimizer; set settings.
    Optimizer opt(sys, SimTK::CMAES);
    // opt.setDiagnosticsLevel(2);
    opt.setConvergenceTolerance(1e-12);
    opt.setMaxIterations(5000);
    opt.setAdvancedIntOption("popsize", 50);
    Vector initStepSize(N, 0.5 * 64);// test vector option
    opt.setAdvancedVectorOption("init_stepsize", initStepSize);
    opt.setAdvancedIntOption("seed", 30);
    opt.setAdvancedRealOption("maxTimeFractionForEigendecomposition", 1);

    Real stopFitness = 5;
    opt.setAdvancedRealOption("stopFitness", stopFitness);

    // Optimize!
    Real f1 = opt.optimize(results);

    SimTK_TEST(f1 > 0.01);
}

// This is a soft test. Just makes sure we get the right answer and we don't
// get any exceptions. We don't actually make sure that multithreading is
// occurring.
void testMultithreading() {

    Cigtab sys(22);
    int N = sys.getNumParameters();

    // set initial conditions.
    Vector results(N);
    results.setTo(0.5);

    // Create optimizer; set settings.
    Optimizer opt(sys, SimTK::CMAES);
    opt.setConvergenceTolerance(1e-12);
    opt.setMaxIterations(5000);
    Vector initStepSize(N, 0.3);// test vector option
    opt.setAdvancedVectorOption("init_stepsize", initStepSize);
    opt.setAdvancedIntOption("seed", 42);
    opt.setAdvancedRealOption("maxTimeFractionForEigendecomposition", 1);
    opt.setAdvancedStrOption("parallel", "multithreading");

    // Optimize!
    SimTK_TEST_OPT(opt, results, 1e-5);

    // Change the number of parallel threads.
    opt.setAdvancedIntOption("nthreads", 2);
    SimTK_TEST_OPT(opt, results, 1e-5);
}

// An exception should be thrown if the user tris
// to assign the init_stepsize through Vector and Real
// option
void testInitStepSizeException() {

    Easom sys;
    int N = sys.getNumParameters();

    // set initial conditions.
    Vector results(N);
    results.setTo(-10);

    // Create optimizer; set settings.
    Optimizer opt(sys, SimTK::CMAES);
    opt.setAdvancedRealOption("init_stepsize", 25);
    Vector initStepSize(N, 25);
    opt.setAdvancedVectorOption("init_stepsize", initStepSize);

    // Optimize!
    SimTK_TEST_MUST_THROW_EXC(opt.optimize(results), std::logic_error);
}

int main() {
    SimTK_START_TEST("CMAES");

        SimTK_SUBTEST(testCMAESAvailable);
        SimTK_SUBTEST(testTwoOrMoreParameters);
        SimTK_SUBTEST(testMaxIterations);
        SimTK_SUBTEST(testCigtabOptimum);
        SimTK_SUBTEST(testParameterLimits);
        SimTK_SUBTEST(testSigmaAndAckleyOptimum);
        SimTK_SUBTEST(testDropWaveOptimumLambda);
        SimTK_SUBTEST(testMaxFunEvals);
        SimTK_SUBTEST(testSeed);
        SimTK_SUBTEST(testConvergenceTolerance);
        SimTK_SUBTEST(testRosenbrock);
        SimTK_SUBTEST(testSchwefel);
        SimTK_SUBTEST(testEasom);
        SimTK_SUBTEST(testStopFitness);
        SimTK_SUBTEST(testMultithreading);
        SimTK_SUBTEST(testInitStepSizeException);
        // TODO        testRestart();

    SimTK_END_TEST();
}