pax_global_header00006660000000000000000000000064125667701060014524gustar00rootroot0000000000000052 comment=7e8afdbe7e18ea563fe1a300d8ea5c3137603166 libdogleg-0.09/000077500000000000000000000000001256677010600134045ustar00rootroot00000000000000libdogleg-0.09/Changes000066400000000000000000000042051256677010600147000ustar00rootroot00000000000000libdogleg (0.09) * Build now works with both suitesparse 2.2 and 2.4 -- Dima Kogan Mon, 24 Aug 2015 21:34:04 -0700 libdogleg (0.08) * Makefile, debian/ tweaked to allow packaging the for the main Debian repository -- Dima Kogan Sun, 04 Nov 2012 21:27:33 -0800 libdogleg (0.07) * fixed off-by-one error in reporting of iteration count * added sample program * improved handling of singular JtJ * more efficient trustregion reduction method for failed GN steps * builds under OSX. Contributed by Laurent Bartholdi. -- Dima Kogan Tue, 02 Oct 2012 22:41:16 -0700 libdogleg (0.06) * API-breaking change: the user can retrieve the full solver context -- Dima Kogan Tue, 17 Jan 2012 15:57:43 -0800 libdogleg (0.05) * I now require debhelper 7, not 8 * 'install' rules now builds everything * updated URL to the license text * removed unneeded packaging files * packaging shared object in a more debian-like way * I now make a native package -- Dima Kogan Sun, 30 Oct 2011 13:37:39 -0700 libdogleg (0.04-1) * Re-licensed under the LGPL * better documentation, now in a manpage * all versions tied to debian/changelog -- Dima Kogan Tue, 06 Sep 2011 14:54:33 -0700 libdogleg (0.03-1) * un-hardcoded the problem I'm asking CHOLMOD to solve * If I ever see a singular JtJ, I factor JtJ + LAMBDA*I from that point on. This is a quick/dirty way to handle singular JtJ matrices * CHOLMOD messages now go to stderr, not stdout -- Dima Kogan Fri, 02 Sep 2011 17:36:25 -0700 libdogleg (0.02-1) * libdogleg now reports the sovler rms and the iteration count * version bump * all debug output now reports more precision * debug output now contains rho * I now return the 2-norm of the optimal error vector. I no longer try to compute the RMS since I don't know what the inputs I'm passed in mean -- Dima Kogan Fri, 26 Aug 2011 15:18:47 -0700 libdogleg (0.01-1) * Initial release -- Dima Kogan Mon, 22 Aug 2011 00:33:18 -0700 libdogleg-0.09/LICENSE000066400000000000000000000001441256677010600144100ustar00rootroot00000000000000This library is distributed under the terms of the GNU LGPL .libdogleg-0.09/Makefile000066400000000000000000000040341256677010600150450ustar00rootroot00000000000000API_VERSION = 2 OS = $(shell uname -s) # I parse the version from the changelog. This version is generally something # like 0.04 .I strip leading 0s, so the above becomes 0.4 VERSION := $(shell sed -n 's/.*(\([0-9\.]*[0-9]\).*).*/\1/; s/\.0*/./g; p; q;' Changes) ifeq ($(strip $(VERSION)),) $(error "Couldn't parse version from debian/changelog") endif ifeq ($(OS),Darwin) CC = gcc # otherwise, CC defaults to clang SO_VERSION=$(API_VERSION).$(VERSION) TARGET_SO_BARE = libdogleg.dylib TARGET_SO_FULL = libdogleg.$(SO_VERSION).dylib TARGET_SO_SONAME = libdogleg.$(API_VERSION).dylib # osx doesn't have DT_NEEDED or something, so I specify these explicitly LDLIBS += -lsuitesparseconfig -lamd -lcolamd -llapack -lblas else SO_VERSION=$(API_VERSION).$(VERSION) TARGET_SO_BARE = libdogleg.so TARGET_SO_FULL = $(TARGET_SO_BARE).$(SO_VERSION) TARGET_SO_SONAME = $(TARGET_SO_BARE).$(API_VERSION) LDFLAGS += -Wl,-soname -Wl,libdogleg.so.$(API_VERSION) endif # Add my optimization flags if none already exist. These could exist if debian # packages are built. OPTFLAGS := $(if $(filter -O%, $(CFLAGS)),,-O3 -ffast-math -mtune=core2) FLAGS += -ggdb -Wall -Wextra -MMD $(OPTFLAGS) -I/usr/include/suitesparse CFLAGS += $(FLAGS) --std=gnu99 LDLIBS += -lcholmod LDLIBS += -lm LIB_TARGETS = libdogleg.a $(TARGET_SO_BARE) $(TARGET_SO_FULL) $(TARGET_SO_SONAME) MAN_SECTION = 3 MAN_TARGET = libdogleg.$(MAN_SECTION) ALL_TARGETS = $(LIB_TARGETS) $(MAN_TARGET) all: $(ALL_TARGETS) libdogleg.a: dogleg.o ar rcvu $@ $^ $(TARGET_SO_FULL): dogleg-pic.o $(CC) $(LDFLAGS) -shared $^ $(LDLIBS) -o $@ $(TARGET_SO_SONAME) $(TARGET_SO_BARE): $(TARGET_SO_FULL) ln -fs $^ $@ %-pic.o: %.c $(CC) $(CPPFLAGS) -fPIC $(CFLAGS) -c -o $@ $< $(MAN_TARGET): README.pod pod2man --center="libdogleg: Powell's dogleg method" --name=LIBDOGLEG --release="libdogleg $(VERSION)" --section=$(MAN_SECTION) $^ $@ sample: sample.o libdogleg.a $(CC) $^ $(LDLIBS) -o $@ sample.o: CFLAGS += -I. clean: rm -f libdogleg.so* *.o *.a *.d $(ALL_TARGETS) .PHONY: all clean -include *.d libdogleg-0.09/README.pod000066400000000000000000000331331256677010600150500ustar00rootroot00000000000000=head1 NAME libdogleg - A general purpose sparse optimizer to solve data fitting problems =head1 DESCRIPTION This is a library for solving large-scale nonlinear optimization problems. By employing sparse linear algebra, it is taylored for problems that have weak coupling between the optimization variables. For appropriately sparse problems this results in I performance gains. The main task of this library is to find the vector B

that minimizes norm2( B ) where B = I(B

) is a vector that has higher dimensionality than B

. The user passes in a callback function (of type C) that takes in the vector B

and returns the vector B and a matrix of derivatives B = dB/dB

. B is a matrix with a row for each element of I and a column for each element of B

. B is a sparse matrix, which results in substantial increases in computational efficiency if most entries of B are 0. B is stored row-first in the callback routine. libdogleg uses a column-first data representation so it references the transpose of B (called B). B stored row-first is identical to B stored column-first; this is purely a naming choice. This library implements Powell's dog-leg algorithm to solve the problem. Like the more-widely-known Levenberg-Marquardt algorithm, Powell's dog-leg algorithm solves a nonlinear optimization problem by interpolating between a Gauss-Newton step and a gradient descent step. Improvements over LM are =over =item * a more natural representation of the linearity of the operating point (trust region size vs a vague lambda term). =item * significant efficiency gains, since a matrix inversion isn't needed to retry a rejected step =back The algorithm is described in many places, originally in M. Powell. A Hybrid Method for Nonlinear Equations. In P. Rabinowitz, editor, Numerical Methods for Nonlinear Algebraic Equations, pages 87-144. Gordon and Breach Science, London, 1970. Various enhancements to Powell's original method are described in the literature; at this time only the original algorithm is implemented here. The sparse matrix algebra is handled by the CHOLMOD library, written by Tim Davis. Parts of CHOLMOD are licensed under the GPL and parts under the LGPL. Only the LGPL pieces are used here, allowing libdogleg to be licensed under the LGPL as well. Due to this I lose some convenience (all simple sparse matrix arithmetic in CHOLMOD is GPL-ed) and some performance (the fancier computational methods, such as supernodal analysis are GPL-ed). For my current applications the performance losses are minor. =head1 FUNCTIONS AND TYPES =head2 Main API =head3 dogleg_optimize This is the main call to the library. Its declared as double dogleg_optimize(double* p, unsigned int Nstate, unsigned int Nmeas, unsigned int NJnnz, dogleg_callback_t* f, void* cookie, dogleg_solverContext_t** returnContext); =over =item * B

is the initial estimate of the state vector (and holds the final result) =item * C specifies the number of optimization variables (elements of B

) =item * C specifies the number of measurements (elements of B). C= Nstate> is a requirement =item * C specifies the number of non-zero elements of the jacobian matrix dB/dB

. In a dense matrix C. We are dealing with sparse jacobians, so C should be far less. If not, libdogleg is not an appropriate routine to solve this problem. =item * C specifies the callback function that the optimization routine calls to sample the problem being solved =item * C is an arbitrary data pointer passed untouched to C =item * If not C, C can be used to retrieve the full context structure from the solver. This can be useful since this structure contains the latest operating point values. It also has an active C structure, which can be reused if more CHOLMOD routines need to be called externally. I when done>. =back C returns norm2( B ) at the minimum, or a negative value if an error occurred. =head3 dogleg_freeContext Used to deallocate memory used for an optimization cycle. Defined as: void dogleg_freeContext(dogleg_solverContext_t** ctx); If a pointer to a context is not requested (by passing C to C), libdogleg calls this routine automatically. If the user I retrieve this pointer, though, it must be freed with C when the user is finished. =head3 dogleg_testGradient libdogleg requires the user to compute the jacobian matrix B. This is a performance optimization, since B could be computed by differences of B. This optimization is often worth the extra effort, but it creates a possibility that B will have a mistake and B = dB/dB

would not be true. To find these types of issues, the user can call void dogleg_testGradient(unsigned int var, const double* p0, unsigned int Nstate, unsigned int Nmeas, unsigned int NJnnz, dogleg_callback_t* f, void* cookie); This function computes the jacobian with center differences and compares the result with the jacobian computed by the callback function. It is recommended to do this for every variable while developing the program that uses libdogleg. =over =item * C is the index of the variable being tested =item * C is the state vector B

where we're evaluating the jacobian =item * C, C, C are the number of state variables, measurements and non-zero jacobian elements, as before =item * C is the callback function, as before =item * C is the user data, as before =back This function returns nothing, but prints out the test results. =head3 dogleg_callback_t The main user callback that specifies the optimization problem has type typedef void (dogleg_callback_t)(const double* p, double* x, cholmod_sparse* Jt, void* cookie); =over =item * B

is the current state vector =item * B is the resulting I(B

) =item * B is the transpose of dB/dB

at B

. As mentioned previously, B is stored column-first by CHOLMOD, which can be interpreted as storing B row-first by the user-defined callback routine =item * The C is the user-defined arbitrary data passed into C. =back =head3 dogleg_solverContext_t This is the solver context that can be retrieved through the C parameter of the C call. This structure contains I the internal state used by the solver. If requested, the user is responsible for calling C when done. This structure is defined as: typedef struct { cholmod_common common; dogleg_callback_t* f; void* cookie; // between steps, beforeStep contains the operating point of the last step. // afterStep is ONLY used while making the step. Externally, use beforeStep // unless you really know what you're doing dogleg_operatingPoint_t* beforeStep; dogleg_operatingPoint_t* afterStep; // The result of the last JtJ factorization performed. Note that JtJ is not // necessarily factorized at every step, so this is NOT guaranteed to contain // the factorization of the most recent JtJ cholmod_factor* factorization; // Have I ever seen a singular JtJ? If so, I add a small constant to the // diagonal from that point on. This is a simple and fast way to deal with // singularities. This is suboptimal but works for me for now. int wasPositiveSemidefinite; } dogleg_solverContext_t; Some of the members are copies of the data passed into C; some others are internal state. Of potential interest are =over =item * C is a cholmod_common structure used by all CHOLMOD calls. This can be used for any extra CHOLMOD work the user may want to do =item * C contains the operating point of the optimum solution. The user can analyze this data without the need to re-call the callback routine. =back =head3 dogleg_operatingPoint_t An operating point of the solver. This is a part of C. Various variables describing the operating point such as B

, B, B, B and B are available. All of the just-mentioned variables are computed at every step and are thus always valid. // an operating point of the solver typedef struct { double* p; double* x; double norm2_x; cholmod_sparse* Jt; double* Jt_x; // the cached update vectors. It's useful to cache these so that when a step is rejected, we can // reuse these when we retry double* updateCauchy; cholmod_dense* updateGN_cholmoddense; double updateCauchy_lensq, updateGN_lensq; // update vector lengths // whether the current update vectors are correct or not int updateCauchy_valid, updateGN_valid; int didStepToEdgeOfTrustRegion; } dogleg_operatingPoint_t; =head2 Parameters It is not required to call any of these, but it's highly recommended to set the initial trust-region size and the termination thresholds to match the problem being solved. Furthermore, it's highly recommended for the problem being solved to be scaled so that every state variable affects the objective norm2( B ) equally. This makes this method's concept of "trust region" much more well-defined and makes the termination criteria work correctly. =head3 dogleg_setMaxIterations To set the maximum number of solver iterations, call void dogleg_setMaxIterations(int n); =head3 dogleg_setDebug To turn on debug output, call void dogleg_setDebug(int debug); with a non-zero value for C. By default, debug output is disabled. =head3 dogleg_setInitialTrustregion The optimization method keeps track of a trust region size. Here, the trust region is a ball in R^Nstate. When the method takes a step B

-> B

, it makes sure that S ) ) < trust region size>. The initial value of the trust region size can be set with void dogleg_setInitialTrustregion(double t); The dogleg algorithm is efficient when recomputing a rejected step for a smaller trust region, so set the initial trust region size to a value larger to a reasonable estimate; the method will quickly shrink the trust region to the correct size. =head3 dogleg_setThresholds The routine exits when the maximum number of iterations is exceeded, or a termination threshold is hit, whichever happens first. The termination thresholds are all designed to trigger when very slow progress is being made. If all went well, this slow progress is due to us finding the optimum. There are 3 termination thresholds: =over =item * The function being minimized is E = norm2( B ) where B = I(B

). dE/dB

= 2*B*B where B is transpose(dB/dB

). if( for every i fabs(Jt_x[i]) < JT_X_THRESHOLD ) { we are done; } =item * The method takes discrete steps: B

-> B

if( for every i fabs(delta_p[i]) < UPDATE_THRESHOLD) { we are done; } =item * The method dynamically controls the trust region. if(trustregion < TRUSTREGION_THRESHOLD) { we are done; } =back To set these threholds, call void dogleg_setThresholds(double Jt_x, double update, double trustregion); To leave a particular threshold alone, specify a negative value. =head3 dogleg_setTrustregionUpdateParameters This function sets the parameters that control when and how the trust region is updated. The default values should work well in most cases, and shouldn't need to be tweaked. Declaration looks like void dogleg_setTrustregionUpdateParameters(double downFactor, double downThreshold, double upFactor, double upThreshold); To see what the parameters do, look at C in the source. Again, these should just work as is. =head1 BUGS The current implementation doesn't handle a singular B gracefully (B = B * B). Analytically, B is at worst positive semi-definite (has 0 eigenvalues). If a singular B is ever encountered, from that point on, B + lambda*B is inverted instead for some positive constant lambda. This makes the matrix strictly positive definite, but is sloppy. At least I should vary lambda. In my current applications, a singular B only occurs if at a particular operating point the vector B has no dependence at all on some elements of B

. In the general case other causes could exist, though. There's an inefficiency in that the callback always returns B and B. When I evaluate and reject a step, I do not end up using B at all. Dependng on the callback function, it may be better to ask for B and then, if the step is accepted, to ask for B. =head1 AUTHOR Dima Kogan, C<< >> =head1 LICENSE AND COPYRIGHT Copyright 2011 Oblong Industries This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. The full text of the license is available at L libdogleg-0.09/dogleg.c000066400000000000000000000645021256677010600150200ustar00rootroot00000000000000// Copyright 2011 Oblong Industries // License: GNU LGPL . #include #include #include #include #ifdef __APPLE__ #include #else #include #endif #include "dogleg.h" #if (CHOLMOD_VERSION > (CHOLMOD_VER_CODE(2,2))) #include #endif // I do this myself because I want this to be active in all build modes, not just !NDEBUG #define ASSERT(x) do { if(!(x)) { fprintf(stderr, "ASSERTION FAILED at %s:%d\n", __FILE__, __LINE__); 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] ////////////////////////////////////////////////////////////////////////////////////////// // parameter stuff ////////////////////////////////////////////////////////////////////////////////////////// // These are the optimizer parameters. They have semi-arbitrary defaults. The // user should adjust them through the API static int DOGLEG_DEBUG = 0; static int MAX_ITERATIONS = 100; // it is cheap to reject a too-large trust region, so I start with something // "large". The solver will quickly move down to something reasonable. Only the // user really knows if this is "large" or not, so they should change this via // the API static double TRUSTREGION0 = 1.0e3; // These are probably OK to leave alone. Tweaking them can maybe result in // slightly faster convergence static double TRUSTREGION_DECREASE_FACTOR = 0.1; static double TRUSTREGION_INCREASE_FACTOR = 2; static double TRUSTREGION_INCREASE_THRESHOLD = 0.75; static double TRUSTREGION_DECREASE_THRESHOLD = 0.25; // The termination thresholds. Documented in the header static double JT_X_THRESHOLD = 1e-8; static double UPDATE_THRESHOLD = 1e-8; static double TRUSTREGION_THRESHOLD = 1e-8; // 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) { DOGLEG_DEBUG = debug; } void dogleg_setInitialTrustregion(double t) { TRUSTREGION0 = t; } void dogleg_setThresholds(double Jt_x, double update, double trustregion) { if(Jt_x > 0.0) JT_X_THRESHOLD = Jt_x; if(update > 0.0) UPDATE_THRESHOLD = update; if(trustregion > 0.0) TRUSTREGION_THRESHOLD = trustregion; } // these parameters likely should not be messed with. void dogleg_setMaxIterations(int n) { MAX_ITERATIONS = n; } void dogleg_setTrustregionUpdateParameters(double downFactor, double downThreshold, double upFactor, double upThreshold) { TRUSTREGION_DECREASE_FACTOR = downFactor; TRUSTREGION_DECREASE_THRESHOLD = downThreshold; TRUSTREGION_INCREASE_FACTOR = upFactor; 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; inrow); for(unsigned int i=0; incol; i++) { for(unsigned int j=P(A, i); jncol; i++) { double dotproduct = 0.0; for(unsigned int j=P(At, i); jupdateCauchy_valid) return; 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 minumum: // 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, point->Jt->nrow); double norm2_J_Jt_x = norm2_mul_spmatrix_t_densevector(point->Jt, point->Jt_x); 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, point->Jt->nrow); if( DOGLEG_DEBUG ) fprintf(stderr, "cauchy step size %.6g\n", sqrt(point->updateCauchy_lensq)); } 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) return; point->updateGN_valid = 1; // 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); } // 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 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; if( DOGLEG_DEBUG ) fprintf(stderr, "singular JtJ. Have rank/full rank: %zd/%zd. Adding %g I from now on\n", ctx->factorization->minor, ctx->factorization->n, ctx->lambda); } // solve JtJ*updateGN = Jt*x. Gauss-Newton step is then -updateGN cholmod_dense Jt_x_dense = {.nrow = point->Jt->nrow, .ncol = 1, .nzmax = point->Jt->nrow, .d = point->Jt->nrow, .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, point->Jt->nrow); // should be more efficient than this later point->updateGN_lensq = norm2(point->updateGN_cholmoddense->x, point->Jt->nrow); if( DOGLEG_DEBUG ) fprintf(stderr, "gn step size %.6g\n", sqrt(point->updateGN_lensq)); } static void computeInterpolatedUpdate(double* update_dogleg, dogleg_operatingPoint_t* point, double trustregion) { // 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 = point->updateGN_cholmoddense->x; double a_minus_b[point->Jt->nrow]; vec_sub(a_minus_b, a, b, point->Jt->nrow); double l2 = norm2(a_minus_b, point->Jt->nrow); double neg_c = inner(a_minus_b, a, point->Jt->nrow); double discriminant = neg_c*neg_c - l2* (norm2a - dsq); if(discriminant < 0.0) { fprintf(stderr, "negative discriminant: %.6g!\n", discriminant); discriminant = 0.0; } double k = (neg_c + sqrt(discriminant))/l2; // I can rehash this to not store this data array at all, but it's clearer // to vec_interpolate(update_dogleg, a, -k, a_minus_b, point->Jt->nrow); if( DOGLEG_DEBUG ) { double updateNorm = norm2(update_dogleg, point->Jt->nrow); fprintf(stderr, "k %.6g, norm %.6g\n", k, sqrt(updateNorm)); } } // 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) { (*ctx->f)(point->p, point->x, point->Jt, ctx->cookie); // 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, point->Jt->ncol); // compute Jt*x mul_spmatrix_densevector(point->Jt_x, point->Jt, point->x); // If the largest absolute gradient element is smaller than the threshold, // we can stop iterating. This is equivalent to the inf-norm for(unsigned int i=0; iJt->nrow; i++) if(fabs(point->Jt_x[i]) > JT_X_THRESHOLD) return 0; if( DOGLEG_DEBUG ) fprintf(stderr, "Jt_x all below the threshold. Done iterating!\n"); return 1; } static double computeExpectedImprovement(const double* step, const dogleg_operatingPoint_t* point) { // 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) return - 2.0*inner(point->Jt_x, step, point->Jt->nrow) - norm2_mul_spmatrix_t_densevector(point->Jt, step); } // 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* newp, double trustregion, dogleg_solverContext_t* ctx) { if( DOGLEG_DEBUG ) fprintf(stderr, "taking step with trustregion %.6g\n", trustregion); double update_array[pointFrom->Jt->nrow]; double* update; computeCauchyUpdate(pointFrom); if(pointFrom->updateCauchy_lensq >= trustregion*trustregion) { if( DOGLEG_DEBUG ) fprintf(stderr, "taking cauchy step\n"); // 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(update_array, pointFrom->updateCauchy, trustregion / sqrt(pointFrom->updateCauchy_lensq), pointFrom->Jt->nrow); update = update_array; 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) { if( DOGLEG_DEBUG ) fprintf(stderr, "taking GN step\n"); // full Gauss-Newton step lies within my trust region. Take the full step update = pointFrom->updateGN_cholmoddense->x; pointFrom->didStepToEdgeOfTrustRegion = 0; } else { if( DOGLEG_DEBUG ) fprintf(stderr, "taking interpolated step\n"); // 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(update_array, pointFrom, trustregion); update = update_array; pointFrom->didStepToEdgeOfTrustRegion = 1; } } // take the step vec_add(newp, pointFrom->p, update, pointFrom->Jt->nrow); double expectedImprovement = computeExpectedImprovement(update, pointFrom); // 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 unsigned int i; for(i=0; iJt->nrow; i++) if( fabs(update[i]) > UPDATE_THRESHOLD ) return expectedImprovement; if( DOGLEG_DEBUG ) fprintf(stderr, "update small enough. Done iterating!\n"); 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) { double observedImprovement = before->norm2_x - after->norm2_x; double rho = observedImprovement / expectedImprovement; if( DOGLEG_DEBUG ) { fprintf(stderr, "observed/expected improvement: %.6g/%.6g. rho = %.6g\n", observedImprovement, expectedImprovement, rho); } // adjust the trust region if( rho < TRUSTREGION_DECREASE_THRESHOLD ) { if( DOGLEG_DEBUG ) fprintf(stderr, "rho too small. decreasing trust region\n"); // 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 *= TRUSTREGION_DECREASE_FACTOR; } else if (rho > TRUSTREGION_INCREASE_THRESHOLD && before->didStepToEdgeOfTrustRegion) { if( DOGLEG_DEBUG ) fprintf(stderr, "rho large enough. increasing trust region\n"); *trustregion *= TRUSTREGION_INCREASE_FACTOR; } return rho > 0.0; } static int runOptimizer(dogleg_solverContext_t* ctx) { double trustregion = TRUSTREGION0; int stepCount = 0; if( computeCallbackOperatingPoint(ctx->beforeStep, ctx) ) return stepCount; if( DOGLEG_DEBUG ) fprintf(stderr, "Initial operating point has norm2_x %.6g\n", ctx->beforeStep->norm2_x); while( stepCountbeforeStep, ctx->afterStep->p, trustregion, ctx); // negative expectedImprovement is used to indicate that we're done if(expectedImprovement < 0.0) return stepCount; int afterStepZeroGradient = computeCallbackOperatingPoint(ctx->afterStep, ctx); if( DOGLEG_DEBUG ) fprintf(stderr, "Evaluated operating point with norm2_x %.6g\n", ctx->afterStep->norm2_x); if( evaluateStep_adjustTrustRegion(ctx->beforeStep, ctx->afterStep, &trustregion, expectedImprovement) ) { if( DOGLEG_DEBUG ) fprintf(stderr, "accepted step\n"); 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 ) { if( DOGLEG_DEBUG ) fprintf(stderr, "Gradient low enough and we just improved. Done iterating!"); return stepCount; } break; } if( DOGLEG_DEBUG ) fprintf(stderr, "rejected step\n"); // This step was rejected. check if the new trust region size is small // enough to give up if(trustregion < TRUSTREGION_THRESHOLD) { if( DOGLEG_DEBUG ) fprintf(stderr, "trust region small enough. Giving up. Done iterating!\n"); return stepCount; } // I have rejected this step, so I try again with the new trust region } } if( DOGLEG_DEBUG && stepCount == MAX_ITERATIONS) fprintf(stderr, "Exceeded max number of iterations\n"); return stepCount; } static dogleg_operatingPoint_t* allocOperatingPoint(int Nstate, int numMeasurements, int numNonzeroJacobianElements, cholmod_common* common) { dogleg_operatingPoint_t* point = malloc(sizeof(dogleg_operatingPoint_t)); ASSERT(point != NULL); point->p = malloc(Nstate * sizeof(point->p[0])); ASSERT(point->p != NULL); point->x = malloc(numMeasurements * sizeof(point->x[0])); ASSERT(point->x != NULL); point->Jt = cholmod_allocate_sparse(Nstate, numMeasurements, numNonzeroJacobianElements, 1, // sorted 1, // packed, 0, // NOT symmetric CHOLMOD_REAL, common); ASSERT(point->Jt != NULL); // the 1-column vector Jt * x point->Jt_x = malloc(Nstate * sizeof(point->Jt_x[0])); ASSERT(point->Jt_x != NULL); // the cached update vectors point->updateCauchy = malloc(Nstate * sizeof(point->updateCauchy[0])); point->updateGN_cholmoddense = NULL; // This will be allocated as it is used // vectors don't have any valid data yet point->updateCauchy_valid = 0; point->updateGN_valid = 0; return point; } static void freeOperatingPoint(dogleg_operatingPoint_t** point, cholmod_common* common) { free((*point)->p); free((*point)->x); cholmod_free_sparse(&(*point)->Jt, common); free((*point)->Jt_x); // the cached update vectors free((*point)->updateCauchy); if((*point)->updateGN_cholmoddense != NULL) cholmod_free_dense(&(*point)->updateGN_cholmoddense, common); free(*point); *point = NULL; } static int cholmod_error_callback(const char* s, ...) { va_list ap; va_start(ap, s); int ret = vfprintf(stderr, s, ap); va_end(ap); return ret; } static void set_cholmod_options(cholmod_common* cc) { // I want to use LGPL parts of CHOLMOD only, so I turn off the supernodal routines. This gave me a // 25% performance hit in the solver for a particular set of optical calibration data. cc->supernodal = 0; // I want all output to go to STDERR, not STDOUT #if (CHOLMOD_VERSION <= (CHOLMOD_VER_CODE(2,2))) cc->print_function = cholmod_error_callback; #else CHOLMOD_FUNCTION_DEFAULTS ; CHOLMOD_FUNCTION_PRINTF(cc) = cholmod_error_callback; #endif } void dogleg_freeContext(dogleg_solverContext_t** ctx) { freeOperatingPoint(&(*ctx)->beforeStep, &(*ctx)->common); freeOperatingPoint(&(*ctx)->afterStep , &(*ctx)->common); if((*ctx)->factorization != NULL) cholmod_free_factor (&(*ctx)->factorization, &(*ctx)->common); cholmod_finish(&(*ctx)->common); free(*ctx); *ctx = NULL; } double dogleg_optimize(double* p, unsigned int Nstate, unsigned int Nmeas, unsigned int NJnnz, dogleg_callback_t* f, void* cookie, dogleg_solverContext_t** returnContext) { dogleg_solverContext_t* ctx = malloc(sizeof(dogleg_solverContext_t)); ctx->f = f; ctx->cookie = cookie; ctx->factorization = NULL; ctx->lambda = 0.0; if( returnContext != NULL ) *returnContext = ctx; if( !cholmod_start(&ctx->common) ) { fprintf(stderr, "Couldn't initialize CHOLMOD\n"); return -1.0; } set_cholmod_options(&ctx->common); ctx->beforeStep = allocOperatingPoint(Nstate, Nmeas, NJnnz, &ctx->common); ctx->afterStep = allocOperatingPoint(Nstate, Nmeas, NJnnz, &ctx->common); memcpy(ctx->beforeStep->p, p, Nstate * sizeof(double)); // everything is set up, so run the solver! int numsteps = runOptimizer(ctx); double norm2_x = ctx->beforeStep->norm2_x; // runOptimizer places the most recent results into beforeStep in preparation for another // iteration memcpy(p, ctx->beforeStep->p, Nstate * sizeof(double)); if( returnContext == NULL ) dogleg_freeContext(&ctx); fprintf(stderr, "success! took %d iterations\n", numsteps); return norm2_x; } libdogleg-0.09/dogleg.h000066400000000000000000000114021256677010600150140ustar00rootroot00000000000000// Copyright 2011 Oblong Industries // License: GNU LGPL . #pragma once #include typedef void (dogleg_callback_t)(const double* p, double* x, cholmod_sparse* Jt, void* cookie); // an operating point of the solver typedef struct { double* p; double* x; double norm2_x; cholmod_sparse* Jt; double* Jt_x; // the cached update vectors. It's useful to cache these so that when a step is rejected, we can // reuse these when we retry double* updateCauchy; cholmod_dense* updateGN_cholmoddense; double updateCauchy_lensq, updateGN_lensq; // update vector lengths // whether the current update vectors are correct or not int updateCauchy_valid, updateGN_valid; int didStepToEdgeOfTrustRegion; } dogleg_operatingPoint_t; // solver context. This has all the internal state of the solver typedef struct { cholmod_common common; dogleg_callback_t* f; void* cookie; // between steps, beforeStep contains the operating point of the last step. // afterStep is ONLY used while making the step. Externally, use beforeStep // unless you really know what you're doing dogleg_operatingPoint_t* beforeStep; dogleg_operatingPoint_t* afterStep; // The result of the last JtJ factorization performed. Note that JtJ is not // necessarily factorized at every step, so this is NOT guaranteed to contain // the factorization of the most recent JtJ cholmod_factor* factorization; // Have I ever seen a singular JtJ? If so, I add this constant to the diagonal // from that point on. This is a simple and fast way to deal with // singularities. This constant starts at 0, and is increased every time a // singular JtJ is encountered. This is suboptimal but works for me for now. double lambda; } dogleg_solverContext_t; // The main optimization callback. Initial estimate of the solution passed in p, // final optimized solution returned in p. p has Nstate variables. There are // Nmeas measurements, the jacobian matrix has NJnnz non-zero entries. // // The evaluation function is given in the callback f; this function is passed // the given cookie // // If we want to get the full solver state when we're done, a non-NULL // returnContext pointer can be given. If this is done then THE USER IS // RESPONSIBLE FOR FREEING ITS MEMORY WITH dogleg_freeContext() double dogleg_optimize(double* p, unsigned int Nstate, unsigned int Nmeas, unsigned int NJnnz, dogleg_callback_t* f, void* cookie, dogleg_solverContext_t** returnContext); 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 we want to get the full solver state when we're done optimizing, we can // pass a non-NULL returnContext pointer to dogleg_optimize(). If we do this, // then the user MUST call dogleg_freeContext() to deallocate the pointer when // the USER is done void dogleg_freeContext(dogleg_solverContext_t** ctx); //////////////////////////////////////////////////////////////// // solver parameters //////////////////////////////////////////////////////////////// void dogleg_setMaxIterations(int n); void dogleg_setTrustregionUpdateParameters(double downFactor, double downThreshold, double upFactor, double upThreshold); // lots of solver-related debug output when on void dogleg_setDebug(int debug); // The following parameters reflect the scaling of the problem being solved, so // the user is strongly encouraged to tweak these. The defaults are set // semi-arbitrarily // The size of the trust region at start. It is cheap to reject a too-large // trust region, so this should be something "large". Say 10x the length of an // "expected" step size void dogleg_setInitialTrustregion(double t); // termination thresholds. These really depend on the scaling of the input // problem, so the user should set these appropriately // // Jt_x threshold: // The function being minimized is E = norm2(x) where x is a function of the state p. // dE/dp = 2*Jt*x where Jt is transpose(dx/dp). // if( for every i fabs(Jt_x[i]) < JT_X_THRESHOLD ) // { we are done; } // // update threshold: // if(for every i fabs(state_update[i]) < UPDATE_THRESHOLD) // { we are done; } // // trust region threshold: // if(trustregion < TRUSTREGION_THRESHOLD) // { we are done; } // // to leave a particular threshold alone, use a value <= 0 here void dogleg_setThresholds(double Jt_x, double update, double trustregion); libdogleg-0.09/sample.c000066400000000000000000000126231256677010600150350ustar00rootroot00000000000000#include #include #include #include #include "dogleg.h" // This is a trivial sample application to demonstrate libdogleg in action. // Let's say that I have a simple non-linear model // // a*b * x**2 + b*c * y**2 + c * x*y + d * x + e * y * f = measurements // // here I'm trying to estimate the vector (a,b,c,d,e,f) to most closely fit the // data vector measurements. This problem is clearly non-sparse and libdogleg is // overkill to solve it, but it serves decently well as a demo // // First I generate some noise-corrupted data, and then use libdogleg to solve // the problem. // My state vector (a,b,c,d,e,f) has 6 elements #define Nstate 6 // I simulate my measurements using these as the TRUE values for the model #define REFERENCE_A 1.0 #define REFERENCE_B 2.0 #define REFERENCE_C 3.0 #define REFERENCE_D 4.0 #define REFERENCE_E 5.0 #define REFERENCE_F 6.0 // I simulate by sampling the x-y space in a grid. This grid is defined here #define SIMULATION_GRID_WIDTH 10 #define SIMULATION_GRID_MIN -10 #define SIMULATION_GRID_DELTA 2.0 #define Nmeasurements (SIMULATION_GRID_WIDTH*SIMULATION_GRID_WIDTH) static double allx [Nmeasurements]; static double ally [Nmeasurements]; static double allm_simulated_noisy[Nmeasurements]; static void simulate(void) { for(int i=0; ip; int* Jcolidx = (int*)Jt->i; double* Jval = (double*)Jt->x; int iJacobian = 0; #define STORE_JACOBIAN(col, g) \ do \ { \ Jcolidx[ iJacobian ] = col; \ Jval [ iJacobian ] = g; \ iJacobian++; \ } while(0) double norm2_x = 0.0; for(int i=0; i