Hi,

Here is an example I wrote in C.

Sincerely,
*Benjamin Bokser*
Cell: (917) 376-6326
Email: [email protected] <[email protected]>
https://www.linkedin.com/in/ben-bokser

On Wed, Nov 29, 2017 at 2:15 AM, P V V <[email protected]> wrote:

> Hi
> I tried to get in touch with you regarding help with NLOPT. I have an
> optimization problem with two nonlinear constraints - h(x) <= 0, g(x) <=0.
> Please let me know if this is possible in NLOPT.
> Thanks.
>
> _______________________________________________
> NLopt-discuss mailing list
> [email protected]
> http://ab-initio.mit.edu/cgi-bin/mailman/listinfo/nlopt-discuss
>
>
#include <math.h>
#include <nlopt.h>

/* setup Obj function */
// x[0] = xf
// x[1] = yf 
// x[2] = theta1
// x[3] = theta2

double pi = 3.14159265;
double xi = 2;
double yi = 2;

/* setup constraint function */
double xconstraint(unsigned n, const double *x, double *grad, void *datax)
{
    if (grad) {
        grad[0] = 1;
        grad[1] = 0;
	grad[2] = sin(x[2] - x[3]) + sin(x[2]);
	grad[3] = - sin(x[2] - x[3]);
    }
    return (x[0] - cos(x[2]) - cos(x[2]-x[3]));
 }

double yconstraint(unsigned n, const double *x, double *grad, void *datay)
{
    if (grad) {
        grad[0] = 0;
        grad[1] = 1;
	grad[2] = - cos(x[2] - x[3]) - cos(x[2]);
	grad[3] = cos(x[2] - x[3]);
    }
    return (x[1] - sin(x[2]) - sin(x[2]-x[3]));
 }

double myfunc(unsigned n, const double *x, double *grad, void *my_func_data)
{
    if (grad) {
        grad[0] = (2*x[0] - 2*xi)/(2*sqrt(pow((x[0] - xi),2) + pow((x[1] - yi),2)));
        grad[1] = (2*x[1] - 2*yi)/(2*sqrt(pow((x[0] - xi),2) + pow((x[1] - yi),2)));
	grad[2] = 0;
	grad[3] = 0;
    }
    return sqrt(pow((x[0]-xi),2) + pow((x[1]-yi),2)); //objective function sqrt((x[0]-xi)^2 + (x[1]-yi)^2)
}

int main(){
	double lb[4] = { 0.5, -1, 24*pi/180, 45*pi/180}; /* lower bounds x, y, th1, th2 */
	double ub[4] = { 2, 2, 90*pi/180, 108*pi/180}; /* upper bounds x, y, th1, th2 */
	nlopt_opt opt;

	opt = nlopt_create(NLOPT_LD_SLSQP, 4); /* algorithm and dimensionality */
	nlopt_set_lower_bounds(opt, lb);
	nlopt_set_upper_bounds(opt, ub);

	nlopt_set_min_objective(opt, myfunc, NULL);

	//add constraint
	nlopt_add_equality_constraint(opt, xconstraint, NULL, 1e-8);
	nlopt_add_equality_constraint(opt, yconstraint, NULL, 1e-8);
		
	nlopt_set_xtol_rel(opt, 1e-4);

	double x[4] = { 1, 1, 24*pi/180, 45*pi/180 };  /* some initial guess */
	double minf; /* the minimum objective value, upon return */

	//actually perform the optimization
	if (nlopt_optimize(opt, x, &minf) < 0) {
   	printf("nlopt failed!\n");
	}
	else {
    		printf("found minimum at 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