-
Notifications
You must be signed in to change notification settings - Fork 13
/
dogleg.c
2520 lines (2091 loc) · 85 KB
/
dogleg.c
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// -*- mode: C; c-basic-offset: 2 -*-
// Copyright 2011 Oblong Industries
// 2017-2018 Dima Kogan <[email protected]>
// License: GNU LGPL <http://www.gnu.org/licenses>.
// Apparently I need this in MSVC to get constants
#define _USE_MATH_DEFINES
#include <stdio.h>
#include <stdarg.h>
#include <math.h>
#include <string.h>
#include <float.h>
#include <stdlib.h>
#include "dogleg.h"
#if (CHOLMOD_VERSION > (CHOLMOD_VER_CODE(2,2))) && (CHOLMOD_VERSION < (CHOLMOD_VER_CODE(4,0)))
#include <cholmod_function.h>
#endif
// Any non-vnlog bit mask
#define DOGLEG_DEBUG_OTHER_THAN_VNLOG (~DOGLEG_DEBUG_VNLOG)
#define SAY_NONEWLINE(fmt, ...) fprintf(stderr, "libdogleg at %s:%d: " fmt, __FILE__, __LINE__, ## __VA_ARGS__)
#define SAY(fmt, ...) do { SAY_NONEWLINE(fmt, ## __VA_ARGS__); fprintf(stderr, "\n"); } while(0)
// This REQUIRES that a "dogleg_solverContext_t* ctx" be available
#define SAY_IF_VERBOSE(fmt,...) do { if( ctx->parameters->dogleg_debug & DOGLEG_DEBUG_OTHER_THAN_VNLOG ) SAY(fmt, ##__VA_ARGS__); } while(0)
// I do this myself because I want this to be active in all build modes, not just !NDEBUG
#define ASSERT(x) do { if(!(x)) { SAY("ASSERTION FAILED: " #x " is not true"); exit(1); } } while(0)
// used to consolidate the casts
#define P(A, index) ((unsigned int*)((A)->p))[index]
#define I(A, index) ((unsigned int*)((A)->i))[index]
#define X(A, index) ((double* )((A)->x))[index]
//////////////////////////////////////////////////////////////////////////////////////////
// vnlog debugging stuff
//
// This is used if the user calls dogleg_setDebug(DOGLEG_DEBUG_VNLOG | stuff)
//////////////////////////////////////////////////////////////////////////////////////////
#define VNLOG_DEBUG_STEP_TYPE_LIST(_) \
_(STEPTYPE_CAUCHY, "cauchy") \
_(STEPTYPE_GAUSSNEWTON, "gaussnewton") \
_(STEPTYPE_INTERPOLATED, "interpolated") \
_(STEPTYPE_FAILED, "failed")
#define VNLOG_DEBUG_STEP_TYPE_NAME_COMMA(name,shortname) name,
typedef enum { VNLOG_DEBUG_STEP_TYPE_LIST(VNLOG_DEBUG_STEP_TYPE_NAME_COMMA)
STEPTYPE_UNINITIALIZED } vnlog_debug_step_type_t;
#define VNLOG_DEBUG_FIELDS(_) \
_(double, norm2x_before, INFINITY) \
_(double, norm2x_after, INFINITY) \
_(double, step_len_cauchy, INFINITY) \
_(double, step_len_gauss_newton, INFINITY) \
_(double, step_len_interpolated, INFINITY) \
_(double, k_cauchy_to_gn, INFINITY) \
_(double, step_len, INFINITY) \
_(vnlog_debug_step_type_t, step_type, STEPTYPE_UNINITIALIZED) \
_(double, step_direction_change_deg, INFINITY) \
_(double, expected_improvement, INFINITY) \
_(double, observed_improvement, INFINITY) \
_(double, rho, INFINITY) \
_(double, trustregion_before, INFINITY) \
_(double, trustregion_after, INFINITY)
static struct vnlog_debug_data_t
{
#define VNLOG_DEBUG_DECLARE_FIELD(type, name, initialvalue) type name;
VNLOG_DEBUG_FIELDS(VNLOG_DEBUG_DECLARE_FIELD)
} vnlog_debug_data;
static void vnlog_debug_reset(void)
{
#define VNLOG_DEBUG_RESET_FIELD(type, name, initialvalue) vnlog_debug_data.name = initialvalue;
VNLOG_DEBUG_FIELDS(VNLOG_DEBUG_RESET_FIELD);
}
static void vnlog_debug_emit_legend(void)
{
#define VNLOG_DEBUG_SPACE_FIELD_NAME(type, name, initialvalue) " " #name
vnlog_debug_reset();
printf("# iteration step_accepted" VNLOG_DEBUG_FIELDS(VNLOG_DEBUG_SPACE_FIELD_NAME) "\n");
}
__attribute__((unused))
static void vnlog_emit_double(double x)
{
if(x == INFINITY) printf("- ");
else printf("%g ", x);
}
__attribute__((unused))
static void vnlog_emit_int(int x)
{
if(x == -1) printf("- ");
else printf("%d ", x);
}
__attribute__((unused))
static void vnlog_emit_vnlog_debug_step_type_t(vnlog_debug_step_type_t x)
{
#define VNLOG_DEBUG_STEP_TYPE_SWITCH_EMIT(name,shortname) case name: printf(shortname " "); break;
switch(x)
{
VNLOG_DEBUG_STEP_TYPE_LIST(VNLOG_DEBUG_STEP_TYPE_SWITCH_EMIT)
default: printf("- ");
}
}
static void vnlog_debug_emit_record(int iteration, int step_accepted)
{
#define VNLOG_DEBUG_EMIT_FIELD(type, name, initialvalue) vnlog_emit_ ## type(vnlog_debug_data.name);
printf("%d %d ", iteration, step_accepted);
VNLOG_DEBUG_FIELDS(VNLOG_DEBUG_EMIT_FIELD);
printf("\n");
fflush(stdout);
vnlog_debug_reset();
}
// Default parameters. Used only by the original API, which uses a global set of
// parameters
#define PARAMETERS_DEFAULT \
{ \
.max_iterations = 100, \
.dogleg_debug = 0, \
.trustregion0 = 1.0e3, \
.trustregion_decrease_factor = 0.1, \
.trustregion_decrease_threshold = 0.25, \
.trustregion_increase_factor = 2, \
.trustregion_increase_threshold = 0.75, \
.Jt_x_threshold = 1e-8, \
.update_threshold = 1e-8, \
.trustregion_threshold = 1e-8 \
}
static const dogleg_parameters2_t parameters_default = PARAMETERS_DEFAULT;
static dogleg_parameters2_t parameters_global = PARAMETERS_DEFAULT;
void dogleg_getDefaultParameters(dogleg_parameters2_t* parameters)
{
*parameters = parameters_default;
}
// if I ever see a singular JtJ, I factor JtJ + LAMBDA*I from that point on
#define LAMBDA_INITIAL 1e-10
// these parameters likely should be messed with
void dogleg_setDebug(int debug)
{
parameters_global.dogleg_debug = debug;
}
void dogleg_setInitialTrustregion(double t)
{
parameters_global.trustregion0 = t;
}
void dogleg_setThresholds(double Jt_x, double update, double trustregion)
{
if(Jt_x > 0.0) parameters_global.Jt_x_threshold = Jt_x;
if(update > 0.0) parameters_global.update_threshold = update;
if(trustregion > 0.0) parameters_global.trustregion_threshold = trustregion;
}
// these parameters likely should not be messed with.
void dogleg_setMaxIterations(int n)
{
parameters_global.max_iterations = n;
}
void dogleg_setTrustregionUpdateParameters(double downFactor, double downThreshold,
double upFactor, double upThreshold)
{
parameters_global.trustregion_decrease_factor = downFactor;
parameters_global.trustregion_decrease_threshold = downThreshold;
parameters_global.trustregion_increase_factor = upFactor;
parameters_global.trustregion_increase_threshold = upThreshold;
}
//////////////////////////////////////////////////////////////////////////////////////////
// general boring linear algebra stuff
// should really come from BLAS or libminimath
//////////////////////////////////////////////////////////////////////////////////////////
static double norm2(const double* x, unsigned int n)
{
double result = 0;
for(unsigned int i=0; i<n; i++)
result += x[i]*x[i];
return result;
}
static double inner(const double* x, const double* y, unsigned int n)
{
double result = 0;
for(unsigned int i=0; i<n; i++)
result += x[i]*y[i];
return result;
}
__attribute__((unused))
static double inner_withstride(const double* x, const double* y, unsigned int n, unsigned int stride)
{
double result = 0;
for(unsigned int i=0; i<n*stride; i+=stride)
result += x[i]*y[i];
return result;
}
// JtJ += outer(j,j). JtJ is packed, upper-triangular (lower-triangular as far
// as LAPACK is concerned)
static void accum_outerproduct_packed( double* JtJ, const double* j, int n )
{
int iJtJ=0;
for(int i1=0; i1<n; i1++)
for(int i0=i1; i0<n; i0++, iJtJ++)
JtJ[iJtJ] += j[i0]*j[i1];
}
static void vec_copy_scaled(double* dest,
const double* v, double scale, int n)
{
for(int i=0; i<n; i++)
dest[i] = scale * v[i];
}
__attribute__((unused))
static void vec_add(double* dest,
const double* v0, const double* v1, int n)
{
for(int i=0; i<n; i++)
dest[i] = v0[i] + v1[i];
}
__attribute__((unused))
static void vec_accum(double* dest,
const double* v, int n)
{
for(int i=0; i<n; i++)
dest[i] += v[i];
}
static void vec_negate(double* v, int n)
{
for(int i=0; i<n; i++)
v[i] *= -1.0;
}
// It would be nice to use the CHOLMOD implementation of these, but they're
// licensed under the GPL
static void mul_spmatrix_densevector(double* dest,
const cholmod_sparse* A, const double* x)
{
memset(dest, 0, sizeof(double) * A->nrow);
for(unsigned int i=0; i<A->ncol; i++)
{
for(unsigned int j=P(A, i); j<P(A, i+1); j++)
{
int row = I(A, j);
dest[row] += x[i] * X(A, j);
}
}
}
static double norm2_mul_spmatrix_t_densevector(const cholmod_sparse* At, const double* x)
{
// computes norm2(transpose(At) * x). For each row of A (col of At) I
// compute that element of A*x, and accumulate it immediately towards the
// norm
double result = 0.0;
for(unsigned int i=0; i<At->ncol; i++)
{
double dotproduct = 0.0;
for(unsigned int j=P(At, i); j<P(At, i+1); j++)
{
int row = I(At, j);
dotproduct += x[row] * X(At, j);
}
result += dotproduct * dotproduct;
}
return result;
}
// transpose(A)*x
static void mul_matrix_t_densevector(double* dest,
const double* A, const double* x,
int Nrows, int Ncols)
{
memset(dest, 0, sizeof(double) * Ncols);
for(int i=0; i<Ncols; i++)
for(int j=0; j<Nrows; j++)
dest[i] += A[i + j*Ncols]*x[j];
}
static double norm2_mul_matrix_vector(const double* A, const double* x, int Nrows, int Ncols)
{
// computes norm2(A * x). For each row of A I compute that element of A*x, and
// accumulate it immediately towards the norm
double result = 0.0;
for(int i=0; i<Nrows; i++)
{
double dotproduct = inner(x, &A[i*Ncols], Ncols);
result += dotproduct * dotproduct;
}
return result;
}
//////////////////////////////////////////////////////////////////////////////////////////
// routines for gradient testing
//////////////////////////////////////////////////////////////////////////////////////////
#define GRADTEST_DELTA 1e-6
static double getGrad(unsigned int var, int meas, const cholmod_sparse* Jt)
{
int row = P(Jt, meas);
int rownext = P(Jt, meas+1);
// this could be done more efficiently with bsearch()
for(int i=row; i<rownext; i++)
{
if(I(Jt,i) == var)
return X(Jt,i);
}
// This gradient is not in my sparse matrix, so its value is 0.0
return 0.0;
}
static double getGrad_dense(unsigned int var, int meas, const double* J, int Nstate)
{
return J[var + meas*Nstate];
}
static
void _dogleg_testGradient(unsigned int var, const double* p0,
unsigned int Nstate, unsigned int Nmeas, unsigned int NJnnz,
dogleg_callback_t* f, void* cookie)
{
int is_sparse = NJnnz > 0;
double* x0 = malloc(Nmeas * sizeof(double));
double* x = malloc(Nmeas * sizeof(double));
double* p = malloc(Nstate * sizeof(double));
ASSERT(x0);
ASSERT(x);
ASSERT(p);
memcpy(p, p0, Nstate * sizeof(double));
cholmod_common _cholmod_common;
cholmod_sparse* Jt;
cholmod_sparse* Jt0;
double* J_dense = NULL; // setting to NULL to pacify compiler's "uninitialized" warnings
double* J_dense0 = NULL; // setting to NULL to pacify compiler's "uninitialized" warnings
// This is a plain text table, that can be easily parsed with "vnlog" tools
printf("# ivar imeasurement gradient_reported gradient_observed error error_relative\n");
if( is_sparse )
{
if( !cholmod_start(&_cholmod_common) )
{
SAY( "Couldn't initialize CHOLMOD");
return;
}
Jt = cholmod_allocate_sparse(Nstate, Nmeas, NJnnz,
1, // sorted
1, // packed,
0, // NOT symmetric
CHOLMOD_REAL,
&_cholmod_common);
Jt0 = cholmod_allocate_sparse(Nstate, Nmeas, NJnnz,
1, // sorted
1, // packed,
0, // NOT symmetric
CHOLMOD_REAL,
&_cholmod_common);
p[var] -= GRADTEST_DELTA/2.0;
(*f)(p, x0, Jt0, cookie);
p[var] += GRADTEST_DELTA;
(*f)(p, x, Jt, cookie);
p[var] -= GRADTEST_DELTA/2.0;
}
else
{
J_dense = malloc( Nmeas * Nstate * sizeof(J_dense[0]) );
J_dense0 = malloc( Nmeas * Nstate * sizeof(J_dense[0]) );
dogleg_callback_dense_t* f_dense = (dogleg_callback_dense_t*)f;
p[var] -= GRADTEST_DELTA/2.0;
(*f_dense)(p, x0, J_dense0, cookie);
p[var] += GRADTEST_DELTA;
(*f_dense)(p, x, J_dense, cookie);
p[var] -= GRADTEST_DELTA/2.0;
}
for(unsigned int i=0; i<Nmeas; i++)
{
// estimated gradients at the midpoint between x and x0
double g_observed = (x[i] - x0[i]) / GRADTEST_DELTA;
double g_reported;
if( is_sparse )
g_reported = (getGrad(var, i, Jt0) + getGrad(var, i, Jt)) / 2.0;
else
g_reported = (getGrad_dense(var, i, J_dense0, Nstate) + getGrad_dense(var, i, J_dense, Nstate)) / 2.0;
double g_sum_abs = fabs(g_reported) + fabs(g_observed);
double g_abs_err = fabs(g_reported - g_observed);
printf( "%d %d %.6g %.6g %.6g %.6g\n", var, i,
g_reported, g_observed, g_abs_err,
g_sum_abs == 0.0 ? 0.0 : (g_abs_err / ( g_sum_abs / 2.0 )));
}
if( is_sparse )
{
cholmod_free_sparse(&Jt, &_cholmod_common);
cholmod_free_sparse(&Jt0, &_cholmod_common);
cholmod_finish(&_cholmod_common);
}
else
{
free(J_dense);
free(J_dense0);
}
free(x0);
free(x);
free(p);
}
void dogleg_testGradient(unsigned int var, const double* p0,
unsigned int Nstate, unsigned int Nmeas, unsigned int NJnnz,
dogleg_callback_t* f, void* cookie)
{
if( NJnnz == 0 )
{
SAY( "I must have NJnnz > 0, instead I have %d", NJnnz);
return;
}
return _dogleg_testGradient(var, p0, Nstate, Nmeas, NJnnz, f, cookie);
}
void dogleg_testGradient_dense(unsigned int var, const double* p0,
unsigned int Nstate, unsigned int Nmeas,
dogleg_callback_dense_t* f, void* cookie)
{
return _dogleg_testGradient(var, p0, Nstate, Nmeas, 0, (dogleg_callback_t*)f, cookie);
}
//////////////////////////////////////////////////////////////////////////////////////////
// solver routines
//////////////////////////////////////////////////////////////////////////////////////////
static void computeCauchyUpdate(dogleg_operatingPoint_t* point,
const dogleg_solverContext_t* ctx)
{
// I already have this data, so don't need to recompute
if(!point->updateCauchy_valid)
{
point->updateCauchy_valid = 1;
// I look at a step in the steepest direction that minimizes my
// quadratic error function (Cauchy point). If this is past my trust region,
// I move as far as the trust region allows along the steepest descent
// direction. My error function is F=norm2(f(p)). dF/dP = 2*ft*J.
// This is proportional to Jt_x, which is thus the steepest ascent direction.
//
// Thus along this direction we have F(k) = norm2(f(p + k Jt_x)). The Cauchy
// point is where F(k) is at a minimum:
// dF_dk = 2 f(p + k Jt_x)t J Jt_x ~ (x + k J Jt_x)t J Jt_x =
// = xt J Jt x + k xt J Jt J Jt x = norm2(Jt x) + k norm2(J Jt x)
// dF_dk = 0 -> k= -norm2(Jt x) / norm2(J Jt x)
// Summary:
// the steepest direction is parallel to Jt*x. The Cauchy point is at
// k*Jt*x where k = -norm2(Jt*x)/norm2(J*Jt*x)
double norm2_Jt_x = norm2(point->Jt_x, ctx->Nstate);
double norm2_J_Jt_x = ctx->is_sparse ?
norm2_mul_spmatrix_t_densevector(point->Jt, point->Jt_x) :
norm2_mul_matrix_vector (point->J_dense, point->Jt_x, ctx->Nmeasurements, ctx->Nstate);
double k = -norm2_Jt_x / norm2_J_Jt_x;
point->updateCauchy_lensq = k*k * norm2_Jt_x;
vec_copy_scaled(point->updateCauchy,
point->Jt_x, k, ctx->Nstate);
SAY_IF_VERBOSE( "cauchy step size %.6g", sqrt(point->updateCauchy_lensq));
}
if( ctx->parameters->dogleg_debug & DOGLEG_DEBUG_VNLOG )
vnlog_debug_data.step_len_cauchy = sqrt(point->updateCauchy_lensq);
}
// LAPACK prototypes for a packed cholesky factorization and a linear solve
// using that factorization, respectively
int dpptrf_(char* uplo, int* n, double* ap,
int* info, int uplo_len);
int dpptrs_(char* uplo, int* n, int* nrhs,
double* ap, double* b, int* ldb, int* info,
int uplo_len);
void dogleg_computeJtJfactorization(dogleg_operatingPoint_t* point, dogleg_solverContext_t* ctx)
{
// I already have this data, so don't need to recompute
if(point->updateGN_valid)
return;
if( ctx->is_sparse )
{
// I'm assuming the pattern of zeros will remain the same throughout, so I
// analyze only once
if(ctx->factorization == NULL)
{
ctx->factorization = cholmod_analyze(point->Jt, &ctx->common);
ASSERT(ctx->factorization != NULL);
}
while(1)
{
if( ctx->lambda == 0.0 )
ASSERT( cholmod_factorize(point->Jt, ctx->factorization, &ctx->common) );
else
{
double beta[] = { ctx->lambda, 0 };
ASSERT( cholmod_factorize_p(point->Jt, beta, NULL, 0,
ctx->factorization, &ctx->common) );
}
if(ctx->factorization->minor == ctx->factorization->n)
break;
// singular JtJ. Raise lambda and go again
if( ctx->lambda == 0.0) ctx->lambda = LAMBDA_INITIAL;
else ctx->lambda *= 10.0;
ASSERT( isfinite(ctx->lambda) );
SAY_IF_VERBOSE( "singular JtJ. Have rank/full rank: %zd/%d. Adding %g I from now on",
ctx->factorization->minor, ctx->Nstate, ctx->lambda);
}
}
else
{
if(ctx->factorization_dense == NULL)
{
// Need to store symmetric JtJ, so I only need one triangle of it
ctx->factorization_dense = malloc( ctx->Nstate * (ctx->Nstate+1) / 2 *
sizeof( ctx->factorization_dense[0]));
ASSERT(ctx->factorization_dense);
}
while(1)
{
// I construct my JtJ. JtJ is packed and stored row-first. I have two
// equivalent implementations. The one enabled here is maybe a bit faster,
// but it's definitely clearer
#if 1
memset(ctx->factorization_dense,
0,
ctx->Nstate*(ctx->Nstate+1)/2*sizeof(ctx->factorization_dense[0]));
for(int i=0; i<ctx->Nmeasurements; i++)
accum_outerproduct_packed( ctx->factorization_dense, &point->J_dense[ctx->Nstate*i],
ctx->Nstate );
if( ctx->lambda > 0.0 )
{
int iJtJ=0;
for(int i1=0; i1<ctx->Nstate; i1++)
{
ctx->factorization_dense[iJtJ] += ctx->lambda;
iJtJ += ctx->Nstate-i1;
}
}
#else
int iJtJ = 0;
for(int i1=0; i1<ctx->Nstate; i1++)
{
#error this does not work. overwritten in the following loop
ctx->factorization_dense[iJtJ] += ctx->lambda;
for(int i0=i1; i0<ctx->Nstate; i0++, iJtJ++)
ctx->factorization_dense[iJtJ] = inner_withstride( &point->J_dense[i0],
&point->J_dense[i1],
ctx->Nmeasurements,
ctx->Nstate);
}
#endif
int info;
dpptrf_(&(char){'L'}, &(int){ctx->Nstate}, ctx->factorization_dense,
&info, 1);
ASSERT(info >= 0); // we MUST either succeed or see complain of singular
// JtJ
if( info == 0 )
break;
// singular JtJ. Raise lambda and go again
if( ctx->lambda == 0.0) ctx->lambda = LAMBDA_INITIAL;
else ctx->lambda *= 10.0;
SAY_IF_VERBOSE( "singular JtJ. Adding %g I from now on", ctx->lambda);
}
}
}
static void computeGaussNewtonUpdate(dogleg_operatingPoint_t* point, dogleg_solverContext_t* ctx)
{
// I already have this data, so don't need to recompute
if(!point->updateGN_valid)
{
dogleg_computeJtJfactorization(point, ctx);
// try to factorize the matrix directly. If it's singular, add a small
// constant to the diagonal. This constant gets larger if we keep being
// singular
if( ctx->is_sparse )
{
// solve JtJ*updateGN = Jt*x. Gauss-Newton step is then -updateGN
cholmod_dense Jt_x_dense = {.nrow = ctx->Nstate,
.ncol = 1,
.nzmax = ctx->Nstate,
.d = ctx->Nstate,
.x = point->Jt_x,
.xtype = CHOLMOD_REAL,
.dtype = CHOLMOD_DOUBLE};
if(point->updateGN_cholmoddense != NULL)
cholmod_free_dense(&point->updateGN_cholmoddense, &ctx->common);
point->updateGN_cholmoddense = cholmod_solve(CHOLMOD_A,
ctx->factorization,
&Jt_x_dense,
&ctx->common);
vec_negate(point->updateGN_cholmoddense->x,
ctx->Nstate); // should be more efficient than this later
point->updateGN_lensq = norm2(point->updateGN_cholmoddense->x, ctx->Nstate);
}
else
{
memcpy( point->updateGN_dense, point->Jt_x, ctx->Nstate * sizeof(point->updateGN_dense[0]));
int info;
dpptrs_(&(char){'L'}, &(int){ctx->Nstate}, &(int){1},
ctx->factorization_dense,
point->updateGN_dense, &(int){ctx->Nstate}, &info, 1);
vec_negate(point->updateGN_dense,
ctx->Nstate); // should be more efficient than this later
point->updateGN_lensq = norm2(point->updateGN_dense, ctx->Nstate);
}
SAY_IF_VERBOSE( "gn step size %.6g", sqrt(point->updateGN_lensq));
point->updateGN_valid = 1;
}
if( ctx->parameters->dogleg_debug & DOGLEG_DEBUG_VNLOG )
vnlog_debug_data.step_len_gauss_newton = sqrt(point->updateGN_lensq);
}
static void computeInterpolatedUpdate(double* update_dogleg,
double* update_dogleg_lensq,
dogleg_operatingPoint_t* point,
double trustregion,
const dogleg_solverContext_t* ctx)
{
// I interpolate between the Cauchy-point step and the Gauss-Newton step
// to find a step that takes me to the edge of my trust region.
//
// I have something like norm2(a + k*(b-a)) = dsq
// = norm2(a) + 2*at*(b-a) * k + norm2(b-a)*k^2 = dsq
// let c = at*(b-a), l2 = norm2(b-a) ->
// l2 k^2 + 2*c k + norm2(a)-dsq = 0
//
// This is a simple quadratic equation:
// k = (-2*c +- sqrt(4*c*c - 4*l2*(norm2(a)-dsq)))/(2*l2)
// = (-c +- sqrt(c*c - l2*(norm2(a)-dsq)))/l2
// to make 100% sure the discriminant is positive, I choose a to be the
// cauchy step. The solution must have k in [0,1], so I much have the
// +sqrt side, since the other one is negative
double dsq = trustregion*trustregion;
double norm2a = point->updateCauchy_lensq;
const double* a = point->updateCauchy;
const double* b = ctx->is_sparse ? point->updateGN_cholmoddense->x : point->updateGN_dense;
double l2 = 0.0;
double neg_c = 0.0;
for(int i=0; i<ctx->Nstate; i++)
{
double d = a[i] - b[i];
l2 += d*d;
neg_c += d*a[i];
}
double discriminant = neg_c*neg_c - l2* (norm2a - dsq);
if(discriminant < 0.0)
{
SAY( "negative discriminant: %.6g!", discriminant);
discriminant = 0.0;
}
double k = (neg_c + sqrt(discriminant))/l2;
*update_dogleg_lensq = 0.0;
for(int i=0; i<ctx->Nstate; i++)
{
update_dogleg[i] = a[i] + k*(b[i] - a[i]);
*update_dogleg_lensq += update_dogleg[i]*update_dogleg[i];
}
SAY_IF_VERBOSE( "k_cauchy_to_gn %.6g, norm %.6g",
k,
sqrt(*update_dogleg_lensq));
if(ctx->parameters->dogleg_debug & DOGLEG_DEBUG_VNLOG)
{
vnlog_debug_data.step_len_interpolated = sqrt(*update_dogleg_lensq);
vnlog_debug_data.k_cauchy_to_gn = k;
}
}
// takes in point->p, and computes all the quantities derived from it, storing
// the result in the other members of the operatingPoint structure. Returns
// true if the gradient-size termination criterion has been met
static int computeCallbackOperatingPoint(dogleg_operatingPoint_t* point, dogleg_solverContext_t* ctx)
{
if( ctx->is_sparse )
{
(*ctx->f)(point->p, point->x, point->Jt, ctx->cookie);
// compute Jt*x
mul_spmatrix_densevector(point->Jt_x, point->Jt, point->x);
}
else
{
(*ctx->f_dense)(point->p, point->x, point->J_dense, ctx->cookie);
// compute Jt*x
mul_matrix_t_densevector(point->Jt_x, point->J_dense, point->x,
ctx->Nmeasurements, ctx->Nstate);
}
// I just got a new operating point, so the current update vectors aren't
// valid anymore, and should be recomputed, as needed
point->updateCauchy_valid = 0;
point->updateGN_valid = 0;
// compute the 2-norm of the current error vector
// At some point this should be changed to use the call from libminimath
point->norm2_x = norm2(point->x, ctx->Nmeasurements);
// If the largest absolute gradient element is smaller than the threshold,
// we can stop iterating. This is equivalent to the inf-norm
for(int i=0; i<ctx->Nstate; i++)
if(fabs(point->Jt_x[i]) > ctx->parameters->Jt_x_threshold)
return 0;
SAY_IF_VERBOSE( "Jt_x all below the threshold. Done iterating!");
return 1;
}
static double computeExpectedImprovement(const double* step, const dogleg_operatingPoint_t* point,
const dogleg_solverContext_t* ctx)
{
// My error function is F=norm2(f(p + step)). F(0) - F(step) =
// = norm2(x) - norm2(x + J*step) = -2*inner(x,J*step) - norm2(J*step)
// = -2*inner(Jt_x,step) - norm2(J*step)
if( ctx->is_sparse )
return
- 2.0*inner(point->Jt_x, step, ctx->Nstate)
- norm2_mul_spmatrix_t_densevector(point->Jt, step);
else
return
- 2.0*inner(point->Jt_x, step, ctx->Nstate)
- norm2_mul_matrix_vector(point->J_dense, step, ctx->Nmeasurements, ctx->Nstate);
}
// takes a step from the given operating point, using the given trust region
// radius. Returns the expected improvement, based on the step taken and the
// linearized x(p). If we can stop iterating, returns a negative number
static double takeStepFrom(dogleg_operatingPoint_t* pointFrom,
double* p_new,
double* step,
double* step_len_sq,
double trustregion,
dogleg_solverContext_t* ctx)
{
SAY_IF_VERBOSE( "taking step with trustregion %.6g", trustregion);
if(ctx->parameters->dogleg_debug & DOGLEG_DEBUG_VNLOG)
{
vnlog_debug_data.trustregion_before = trustregion;
vnlog_debug_data.norm2x_before = pointFrom->norm2_x;
}
computeCauchyUpdate(pointFrom, ctx);
if(pointFrom->updateCauchy_lensq >= trustregion*trustregion)
{
SAY_IF_VERBOSE( "taking cauchy step");
if(ctx->parameters->dogleg_debug & DOGLEG_DEBUG_VNLOG)
{
vnlog_debug_data.step_type = STEPTYPE_CAUCHY;
vnlog_debug_data.step_len = vnlog_debug_data.step_len_cauchy;
}
*step_len_sq = pointFrom->updateCauchy_lensq;
// cauchy step goes beyond my trust region, so I do a gradient descent
// to the edge of my trust region and call it good
vec_copy_scaled(step,
pointFrom->updateCauchy,
trustregion / sqrt(pointFrom->updateCauchy_lensq),
ctx->Nstate);
pointFrom->didStepToEdgeOfTrustRegion = 1;
}
else
{
// I'm not yet done. The cauchy point is within the trust region, so I can
// go further. I look at the full Gauss-Newton step. If this is within the
// trust region, I use it. Otherwise, I find the point at the edge of my
// trust region that lies on a straight line between the Cauchy point and
// the Gauss-Newton solution, and use that. This is the heart of Powell's
// dog-leg algorithm.
computeGaussNewtonUpdate(pointFrom, ctx);
if(pointFrom->updateGN_lensq <= trustregion*trustregion)
{
SAY_IF_VERBOSE( "taking GN step");
if(ctx->parameters->dogleg_debug & DOGLEG_DEBUG_VNLOG)
{
vnlog_debug_data.step_type = STEPTYPE_GAUSSNEWTON;
vnlog_debug_data.step_len = vnlog_debug_data.step_len_gauss_newton;
}
*step_len_sq = pointFrom->updateGN_lensq;
// full Gauss-Newton step lies within my trust region. Take the full step
memcpy( step,
ctx->is_sparse ? pointFrom->updateGN_cholmoddense->x : pointFrom->updateGN_dense,
ctx->Nstate * sizeof(step[0]) );
pointFrom->didStepToEdgeOfTrustRegion = 0;
}
else
{
SAY_IF_VERBOSE( "taking interpolated step");
// full Gauss-Newton step lies outside my trust region, so I interpolate
// between the Cauchy-point step and the Gauss-Newton step to find a step
// that takes me to the edge of my trust region.
computeInterpolatedUpdate(step,
step_len_sq,
pointFrom, trustregion, ctx);
pointFrom->didStepToEdgeOfTrustRegion = 1;
if(ctx->parameters->dogleg_debug & DOGLEG_DEBUG_VNLOG)
{
vnlog_debug_data.step_type = STEPTYPE_INTERPOLATED;
vnlog_debug_data.step_len = vnlog_debug_data.step_len_interpolated;
}
}
}
// take the step
vec_add(p_new, pointFrom->p, step, ctx->Nstate);
double expectedImprovement = computeExpectedImprovement(step, pointFrom, ctx);
if(ctx->parameters->dogleg_debug & DOGLEG_DEBUG_VNLOG)
{
vnlog_debug_data.expected_improvement = expectedImprovement;
if(pointFrom->step_to_here_len_sq != INFINITY)
{
double cos_direction_change =
inner(step, pointFrom->step_to_here, ctx->Nstate) /
sqrt(*step_len_sq * pointFrom->step_to_here_len_sq);
// check the numerical overflow cases
if(cos_direction_change >= 1.0)
vnlog_debug_data.step_direction_change_deg = 0.0;
else if(cos_direction_change <= -1.0)
vnlog_debug_data.step_direction_change_deg = 180.0;
else
vnlog_debug_data.step_direction_change_deg = 180.0/M_PI*acos(cos_direction_change);
}
}
// are we done? For each state variable I look at the update step. If all the elements fall below
// a threshold, I call myself done
for(int i=0; i<ctx->Nstate; i++)
if( fabs(step[i]) > ctx->parameters->update_threshold )
return expectedImprovement;
SAY_IF_VERBOSE( "update small enough. Done iterating!");
return -1.0;
}
// I have a candidate step. I adjust the trustregion accordingly, and also
// report whether this step should be accepted (0 == rejected, otherwise
// accepted)
static int evaluateStep_adjustTrustRegion(const dogleg_operatingPoint_t* before,
const dogleg_operatingPoint_t* after,
double* trustregion,
double expectedImprovement,
dogleg_solverContext_t* ctx)
{
double observedImprovement = before->norm2_x - after->norm2_x;
double rho = observedImprovement / expectedImprovement;
SAY_IF_VERBOSE( "observed/expected improvement: %.6g/%.6g. rho = %.6g",
observedImprovement, expectedImprovement, rho);
if(ctx->parameters->dogleg_debug & DOGLEG_DEBUG_VNLOG)
{
vnlog_debug_data.observed_improvement = observedImprovement;
vnlog_debug_data.rho = rho;
}
// adjust the trust region
if( rho < ctx->parameters->trustregion_decrease_threshold )
{
SAY_IF_VERBOSE( "rho too small. decreasing trust region");
// Our model doesn't fit well. We should reduce the trust region size. If
// the trust region size was affecting the attempted step, do this by a
// constant factor. Otherwise, drop the trustregion to attempted step size
// first
if( !before->didStepToEdgeOfTrustRegion )
*trustregion = sqrt(before->updateGN_lensq);
*trustregion *= ctx->parameters->trustregion_decrease_factor;
}
else if (rho > ctx->parameters->trustregion_increase_threshold && before->didStepToEdgeOfTrustRegion)
{
SAY_IF_VERBOSE( "rho large enough. increasing trust region");
*trustregion *= ctx->parameters->trustregion_increase_factor;
}
if(ctx->parameters->dogleg_debug & DOGLEG_DEBUG_VNLOG)
vnlog_debug_data.trustregion_after = *trustregion;
return rho > 0.0;
}
static int runOptimizer(dogleg_solverContext_t* ctx)
{
double trustregion = ctx->parameters->trustregion0;
int stepCount = 0;
if( computeCallbackOperatingPoint(ctx->beforeStep, ctx) )
return stepCount;
SAY_IF_VERBOSE( "Initial operating point has norm2_x %.6g", ctx->beforeStep->norm2_x);
ctx->beforeStep->step_to_here_len_sq = INFINITY;
while( stepCount<ctx->parameters->max_iterations )
{
SAY_IF_VERBOSE( "================= step %d", stepCount );
while(1)
{
SAY_IF_VERBOSE("--------");
double expectedImprovement =
takeStepFrom(ctx->beforeStep,
ctx->afterStep->p,
ctx->afterStep->step_to_here,
&ctx->afterStep->step_to_here_len_sq,
trustregion, ctx);
// negative expectedImprovement is used to indicate that we're done
if(expectedImprovement < 0.0)
{
if( ctx->parameters->dogleg_debug & DOGLEG_DEBUG_VNLOG )
vnlog_debug_emit_record(stepCount, 1);
return stepCount;
}
int afterStepZeroGradient = computeCallbackOperatingPoint(ctx->afterStep, ctx);
SAY_IF_VERBOSE( "Evaluated operating point with norm2_x %.6g", ctx->afterStep->norm2_x);
if(ctx->parameters->dogleg_debug & DOGLEG_DEBUG_VNLOG)
vnlog_debug_data.norm2x_after = ctx->afterStep->norm2_x;
if( evaluateStep_adjustTrustRegion(ctx->beforeStep, ctx->afterStep, &trustregion,
expectedImprovement, ctx) )
{
SAY_IF_VERBOSE( "accepted step");
if( ctx->parameters->dogleg_debug & DOGLEG_DEBUG_VNLOG )
vnlog_debug_emit_record(stepCount, 1);
stepCount++;
// I accept this step, so the after-step operating point is the before-step operating point
// of the next iteration. I exchange the before- and after-step structures so that all the
// pointers are still around and I don't have to re-allocate
dogleg_operatingPoint_t* tmp;
tmp = ctx->afterStep;
ctx->afterStep = ctx->beforeStep;
ctx->beforeStep = tmp;
if( afterStepZeroGradient )
{
SAY_IF_VERBOSE( "Gradient low enough and we just improved. Done iterating!" );
return stepCount;
}
break;
}