Hi, I am trying to solve the tutorial example at 
http://ab-initio.mit.edu/wiki/index.php/NLopt_Tutorial, by using the Hessian.
As you see my source code below, I copied and pasted most of the code from the 
tutorial with a few lines of replacement (refered to 
http://ab-initio.mit.edu/wiki/index.php/NLopt_Reference#Preconditioning_with_approximate_Hessians)
 for the use of the hessian.
But it does not seem to converge to the solution. (The printed objective 
evaluations are:)

Eval[0] : f(1.234,5.678) = 2.38285543
Eval[1] : f(1.234,5.678) = 2.38285543
...
Eval[99] : f(1.234,5.678) = 2.38285543

Please correct me if I made any mistake. Thanks.


/*------------- Code to Solve Tutorial Example with Hessian -------------*/
#include <stdio.h>
#include <math.h>
#include <nlopt.h>

int count = 0;
double myfunc(unsigned n, const double *x, double *grad, void *my_func_data)
{
    if (grad) {
        grad[0] = 0.0;
        grad[1] = 0.5 / sqrt(x[1]);
    }
    double J = sqrt(x[1]);

    printf("Eval[%d] : f(%g,%g) = %0.10g\n", count++, x[0], x[1], J);
    return J;
}

typedef struct {
    double a, b;
} my_constraint_data;

double myconstraint(unsigned n, const double *x, double *grad, void *data)
{
    my_constraint_data *d = (my_constraint_data *) data;
    double a = d->a, b = d->b;
    if (grad) {
        grad[0] = 3 * a * (a*x[0] + b) * (a*x[0] + b);
        grad[1] = -1.0;
    }
    return ((a*x[0] + b) * (a*x[0] + b) * (a*x[0] + b) - x[1]);
}

/* The preconditioner of objective */
void pre(unsigned n, const double *x, const double *v, double *vpre, void 
*f_data) {
    /*
     * Hessian:  [ 0 ,              0
     *                     0, -1/4*x[1]^(-3/2) ]
     */
    vpre[0] = 0;
    vpre[1] = -.25/(x[1]*sqrt(x[1])) * v[1];
}

int main() {
    double lb[2] = { -HUGE_VAL, 0 }; /* lower bounds */
    nlopt_opt opt;

    opt = nlopt_create(NLOPT_LD_CCSAQ, 2); /* algorithm and dimensionality */
    nlopt_set_lower_bounds(opt, lb);

    //nlopt_set_min_objective(opt, myfunc, NULL);
    nlopt_set_precond_min_objective(opt, myfunc, pre, NULL);

    my_constraint_data data[2] = { {2,0}, {-1,1} };

    nlopt_add_inequality_constraint(opt, myconstraint, &data[0], 1e-8);
    nlopt_add_inequality_constraint(opt, myconstraint, &data[1], 1e-8);

    //nlopt_set_xtol_rel(opt, 1e-4);
    nlopt_set_stopval(opt, sqrt(8./27.)+1e-3);
    nlopt_set_maxeval(opt, 100);

    double x[2] = { 1.234, 5.678 };  /* some initial guess */
    double minf; /* the minimum objective value, upon return */

    if (nlopt_optimize(opt, x, &minf) < 0) {
        printf("nlopt failed!\n");
    }
    else {
        printf("found minimum after %d evaluations\n", count);
        printf("  f(%g,%g) = %0.10g\n", x[0], x[1], minf);
    }

    nlopt_destroy(opt);

    return 0;
}
_______________________________________________
NLopt-discuss mailing list
[email protected]
http://ab-initio.mit.edu/cgi-bin/mailman/listinfo/nlopt-discuss

Reply via email to