chiark / gitweb /
71916f07a87b352d37fa32530d362b578e17bba5
[nlopt.git] / cobyla / cobyla.c
1 /* cobyla : contrained optimization by linear approximation */
2
3 /*
4  * Copyright (c) 1992, Michael J. D. Powell (M.J.D.Powell@damtp.cam.ac.uk)
5  * Copyright (c) 2004, Jean-Sebastien Roy (js@jeannot.org)
6  * 
7  * Permission is hereby granted, free of charge, to any person obtaining a
8  * copy of this software and associated documentation files (the
9  * "Software"), to deal in the Software without restriction, including
10  * without limitation the rights to use, copy, modify, merge, publish,
11  * distribute, sublicense, and/or sell copies of the Software, and to
12  * permit persons to whom the Software is furnished to do so, subject to
13  * the following conditions:
14  * 
15  * The above copyright notice and this permission notice shall be included
16  * in all copies or substantial portions of the Software.
17  * 
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
21  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
22  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
23  * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
24  * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25  */
26
27 /*
28  * This software is a C version of COBYLA2, a contrained optimization by linear
29  * approximation package developed by Michael J. D. Powell in Fortran.
30  * 
31  * The original source code can be found at :
32  * http://plato.la.asu.edu/topics/problems/nlores.html
33  */
34
35 static char const rcsid[] =
36   "@(#) $Jeannot: cobyla.c,v 1.11 2004/04/18 09:51:36 js Exp $";
37
38 #include <stdlib.h>
39 #include <stdio.h>
40 #include <math.h>
41
42 #include "cobyla.h"
43
44 /* SGJ, 2008: modified COBYLA code to take explicit account of bound
45    constraints.  Since bound constraints are linear, these should
46    already be handled exactly when COBYLA optimizes it linear model.
47    However, they were not handled properly when COBYLA created its
48    initial simplex, or when COBYLA updated unacceptable simplices.
49    Since NLopt guarantees that the objective will not be evaluated
50    outside the bound constraints, this required us to handle such
51    points by putting a slope discontinuity into the objective &
52    constraints (below), which slows convergence considerably for
53    smooth functions.  Instead, handling them explicitly prevents this
54    problem */
55 #define ENFORCE_BOUNDS 1
56
57 #define min(a,b) ((a) <= (b) ? (a) : (b))
58 #define max(a,b) ((a) >= (b) ? (a) : (b))
59 #define abs(x) ((x) >= 0 ? (x) : -(x))
60
61 #define U(n) ((unsigned) (n))
62
63 /**************************************************************************/
64 /* SGJ, 2008: NLopt-style interface function: */
65
66 typedef struct {
67      nlopt_func f;
68      void *f_data;
69      unsigned m_orig;
70      nlopt_constraint *fc;
71      unsigned p;
72      nlopt_constraint *h;
73      double *xtmp;
74      double *lb, *ub;
75      double *con_tol, *scale;
76      nlopt_stopping *stop;
77 } func_wrap_state;
78
79 static int func_wrap(int ni, int mi, double *x, double *f, double *con,
80                      func_wrap_state *s)
81 {
82      unsigned n = U(ni);
83      unsigned i, j, k;
84      double *xtmp = s->xtmp;
85      const double *lb = s->lb, *ub = s->ub;
86
87      (void) mi; /* unused */
88
89      /* in nlopt, we guarante that the function is never evaluated outside
90         the lb and ub bounds, so we need force this with xtmp ... note
91         that this leads to discontinuity in the first derivative, which
92         slows convergence if we don't enable the ENFORCE_BOUNDS feature
93         above. */
94      for (j = 0; j < n; ++j) {
95           if (x[j] < lb[j]) xtmp[j] = lb[j];
96           else if (x[j] > ub[j]) xtmp[j] = ub[j];
97           else xtmp[j] = x[j];
98      }
99      nlopt_unscale(n, s->scale, xtmp, xtmp);
100
101      *f = s->f(n, xtmp, NULL, s->f_data);
102      if (nlopt_stop_forced(s->stop)) return 1;
103      i = 0;
104      for (j = 0; j < s->m_orig; ++j) {
105           nlopt_eval_constraint(con + i, NULL, s->fc+j, n, xtmp);
106           if (nlopt_stop_forced(s->stop)) return 1;
107           for (k = 0; k < s->fc[j].m; ++k)
108                con[i + k] = -con[i + k];
109           i += s->fc[j].m;
110      }
111      for (j = 0; j < s->p; ++j) {
112           nlopt_eval_constraint(con + i, NULL, s->h+j, n, xtmp);
113           if (nlopt_stop_forced(s->stop)) return 1;
114           for (k = 0; k < s->h[j].m; ++k)
115                con[(i + s->h[j].m) + k] = -con[i + k];
116           i += 2 * s->h[j].m;
117      }
118      for (j = 0; j < n; ++j) {
119           if (!nlopt_isinf(lb[j]))
120                con[i++] = x[j] - lb[j];
121           if (!nlopt_isinf(ub[j]))
122                con[i++] = ub[j] - x[j];
123      }
124      return 0;
125 }
126
127 /*
128  * Verbosity level
129  */
130 typedef enum {
131   COBYLA_MSG_NONE = 0, /* No messages */
132   COBYLA_MSG_EXIT = 1, /* Exit reasons */
133   COBYLA_MSG_ITER = 2, /* Rho and Sigma changes */
134   COBYLA_MSG_INFO = 3 /* Informational messages */
135 } cobyla_message;
136
137 /*
138  * A function as required by cobyla
139  * state is a void pointer provided to the function at each call
140  *
141  * n     : the number of variables
142  * m     : the number of constraints
143  * x     : on input, then vector of variables (should not be modified)
144  * f     : on output, the value of the function
145  * con   : on output, the value of the constraints (vector of size m)
146  * state : on input, the value of the state variable as provided to cobyla
147  *
148  * COBYLA will try to make all the values of the constraints positive.
149  * So if you want to input a constraint j such as x[i] <= MAX, set:
150  *   con[j] = MAX - x[i]
151  * The function must returns 0 if no error occurs or 1 to immediately end the
152  * minimization.
153  *
154  */
155 typedef int cobyla_function(int n, int m, double *x, double *f, double *con,
156   func_wrap_state *state);
157
158 /*
159  * cobyla : minimize a function subject to constraints
160  *
161  * n         : number of variables (>=0)
162  * m         : number of constraints (>=0)
163  * x         : on input, initial estimate ; on output, the solution
164  * minf      : on output, minimum objective function
165  * rhobeg    : a reasonable initial change to the variables
166  * stop      : the NLopt stopping criteria
167  * lb, ub    : lower and upper bounds on x
168  * message   : see the cobyla_message enum
169  * calcfc    : the function to minimize (see cobyla_function)
170  * state     : used by function (see cobyla_function)
171  *
172  * The cobyla function returns the usual nlopt_result codes.
173  *
174  */
175 extern nlopt_result cobyla(int n, int m, double *x, double *minf, double rhobeg, double rhoend, nlopt_stopping *stop, const double *lb, const double *ub,
176   int message, cobyla_function *calcfc, func_wrap_state *state);
177
178 nlopt_result cobyla_minimize(unsigned n, nlopt_func f, void *f_data,
179                              unsigned m, nlopt_constraint *fc,
180                              unsigned p, nlopt_constraint *h,
181                              const double *lb, const double *ub, /* bounds */
182                              double *x, /* in: initial guess, out: minimizer */
183                              double *minf,
184                              nlopt_stopping *stop,
185                              const double *dx)
186 {
187      unsigned i, j;
188      func_wrap_state s;
189      nlopt_result ret;
190      double rhobeg, rhoend;
191
192      s.f = f; s.f_data = f_data;
193      s.m_orig = m;
194      s.fc = fc; 
195      s.p = p;
196      s.h = h;
197      s.stop = stop;
198      s.lb = s.ub = s.xtmp = s.con_tol = s.scale = NULL;
199
200      s.scale = nlopt_compute_rescaling(n, dx);
201      if (!s.scale) { ret = NLOPT_OUT_OF_MEMORY; goto done; }
202
203      s.lb = nlopt_new_rescaled(n, s.scale, lb);
204      if (!s.lb) { ret = NLOPT_OUT_OF_MEMORY; goto done; }
205      s.ub = nlopt_new_rescaled(n, s.scale, ub);
206      if (!s.ub) { ret = NLOPT_OUT_OF_MEMORY; goto done; }
207
208      s.xtmp = (double *) malloc(sizeof(double) * n);
209      if (!s.xtmp) { ret = NLOPT_OUT_OF_MEMORY; goto done; }
210
211      /* SGJ, 2008: compute rhoend from NLopt stop info */
212      rhobeg = dx[0] / s.scale[0];
213      rhoend = stop->xtol_rel * (rhobeg);
214      for (j = 0; j < n; ++j)
215           if (rhoend < stop->xtol_abs[j] / s.scale[j])
216                rhoend = stop->xtol_abs[j] / s.scale[j];
217
218      /* each equality constraint gives two inequality constraints */
219      m = nlopt_count_constraints(m, fc) + 2 * nlopt_count_constraints(p, h);
220
221      /* add constraints for lower/upper bounds (if any) */
222      for (j = 0; j < n; ++j) {
223           if (!nlopt_isinf(lb[j]))
224                ++m;
225           if (!nlopt_isinf(ub[j]))
226                ++m;
227      }
228
229      s.con_tol = (double *) malloc(sizeof(double) * m);
230      if (m && !s.con_tol) { ret = NLOPT_OUT_OF_MEMORY; goto done; }
231
232      for (j = 0; j < m; ++j) s.con_tol[j] = 0;
233      for (j = i = 0; i < s.m_orig; ++i) {
234           unsigned ji = j, jnext = j + fc[i].m;
235           for (; j < jnext; ++j) s.con_tol[j] = fc[i].tol[j - ji];
236      }
237      for (i = 0; i < s.p; ++i) {
238           unsigned ji = j, jnext = j + h[i].m;
239           for (; j < jnext; ++j) s.con_tol[j] = h[i].tol[j - ji];
240           ji = j; jnext = j + h[i].m;
241           for (; j < jnext; ++j) s.con_tol[j] = h[i].tol[j - ji];
242      }
243
244      nlopt_rescale(n, s.scale, x, x);
245      ret = cobyla((int) n, (int) m, x, minf, rhobeg, rhoend,
246                   stop, s.lb, s.ub, COBYLA_MSG_NONE, 
247                   func_wrap, &s);
248      nlopt_unscale(n, s.scale, x, x);
249
250      /* make sure e.g. rounding errors didn't push us slightly out of bounds */
251      for (j = 0; j < n; ++j) {
252           if (x[j] < lb[j]) x[j] = lb[j];
253           if (x[j] > ub[j]) x[j] = ub[j];
254      }
255
256 done:
257      free(s.con_tol);
258      free(s.xtmp);
259      free(s.ub);
260      free(s.lb);
261      free(s.scale);
262      return ret;
263 }
264
265 /**************************************************************************/
266
267 /* SGJ, 2010: I find that it seems to increase robustness of the algorithm
268    if, on "simplex" steps (which are intended to improve the linear
269    independence of the simplex, not improve the objective), we multiply
270    the steps by pseudorandom numbers in [0,1).  Intuitively, pseudorandom
271    steps are likely to avoid any accidental dependency in the simplex
272    vertices.  However, since I still want COBYLA to be a deterministic
273    algorithm, and I don't care all that much about the quality of the
274    randomness here, I implement a simple linear congruential generator
275    rather than use nlopt_urand, and set the initial seed deterministically. */
276
277 #if defined(HAVE_STDINT_H)
278 #  include <stdint.h>
279 #endif
280
281 #ifndef HAVE_UINT32_T
282 #  if SIZEOF_UNSIGNED_LONG == 4
283 typedef unsigned long uint32_t;
284 #  elif SIZEOF_UNSIGNED_INT == 4
285 typedef unsigned int uint32_t;
286 #  else
287 #    error No 32-bit unsigned integer type
288 #  endif
289 #endif
290
291 /* a simple linear congruential generator */
292
293 static uint32_t lcg_rand(uint32_t *seed)
294 {
295      return (*seed = *seed * 1103515245 + 12345);
296 }
297
298 static double lcg_urand(uint32_t *seed, double a, double b)
299 {
300      return a + lcg_rand(seed) * (b - a) / ((uint32_t) -1);
301 }
302
303 /**************************************************************************/
304
305 static nlopt_result cobylb(int *n, int *m, int *mpp, double *x, double *minf, double *rhobeg, double rhoend,
306   nlopt_stopping *stop, const double *lb, const double *ub, int *iprint, double *con, double *sim,
307   double *simi, double *datmat, double *a, double *vsig, double *veta,
308   double *sigbar, double *dx, double *w, int *iact, cobyla_function *calcfc,
309   func_wrap_state *state);
310 static nlopt_result trstlp(int *n, int *m, double *a, double *b, double *rho,
311   double *dx, int *ifull, int *iact, double *z__, double *zdota, double *vmultc,
312   double *sdirn, double *dxnew, double *vmultd);
313
314 /* ------------------------------------------------------------------------ */
315
316 nlopt_result cobyla(int n, int m, double *x, double *minf, double rhobeg, double rhoend, nlopt_stopping *stop, const double *lb, const double *ub, int iprint,
317   cobyla_function *calcfc, func_wrap_state *state)
318 {
319   int icon, isim, isigb, idatm, iveta, isimi, ivsig, iwork, ia, idx, mpp;
320   int *iact;
321   double *w;
322   nlopt_result rc;
323
324 /*
325  * This subroutine minimizes an objective function F(X) subject to M
326  * inequality constraints on X, where X is a vector of variables that has 
327  * N components. The algorithm employs linear approximations to the 
328  * objective and constraint functions, the approximations being formed by 
329  * linear interpolation at N+1 points in the space of the variables. 
330  * We regard these interpolation points as vertices of a simplex. The 
331  * parameter RHO controls the size of the simplex and it is reduced 
332  * automatically from RHOBEG to RHOEND. For each RHO the subroutine tries 
333  * to achieve a good vector of variables for the current size, and then 
334  * RHO is reduced until the value RHOEND is reached. Therefore RHOBEG and 
335  * RHOEND should be set to reasonable initial changes to and the required 
336  * accuracy in the variables respectively, but this accuracy should be 
337  * viewed as a subject for experimentation because it is not guaranteed. 
338  * The subroutine has an advantage over many of its competitors, however, 
339  * which is that it treats each constraint individually when calculating 
340  * a change to the variables, instead of lumping the constraints together 
341  * into a single penalty function. The name of the subroutine is derived 
342  * from the phrase Constrained Optimization BY Linear Approximations. 
343  *
344  * The user must set the values of N, M, RHOBEG and RHOEND, and must 
345  * provide an initial vector of variables in X. Further, the value of 
346  * IPRINT should be set to 0, 1, 2 or 3, which controls the amount of 
347  * printing during the calculation. Specifically, there is no output if 
348  * IPRINT=0 and there is output only at the end of the calculation if 
349  * IPRINT=1. Otherwise each new value of RHO and SIGMA is printed. 
350  * Further, the vector of variables and some function information are 
351  * given either when RHO is reduced or when each new value of F(X) is 
352  * computed in the cases IPRINT=2 or IPRINT=3 respectively. Here SIGMA 
353  * is a penalty parameter, it being assumed that a change to X is an 
354  * improvement if it reduces the merit function 
355  *      F(X)+SIGMA*MAX(0.0,-C1(X),-C2(X),...,-CM(X)), 
356  * where C1,C2,...,CM denote the constraint functions that should become 
357  * nonnegative eventually, at least to the precision of RHOEND. In the 
358  * printed output the displayed term that is multiplied by SIGMA is 
359  * called MAXCV, which stands for 'MAXimum Constraint Violation'. The 
360  * argument MAXFUN is an int variable that must be set by the user to a 
361  * limit on the number of calls of CALCFC, the purpose of this routine being 
362  * given below. The value of MAXFUN will be altered to the number of calls 
363  * of CALCFC that are made. The arguments W and IACT provide real and 
364  * int arrays that are used as working space. Their lengths must be at 
365  * least N*(3*N+2*M+11)+4*M+6 and M+1 respectively. 
366  *
367  * In order to define the objective and constraint functions, we require 
368  * a subroutine that has the name and arguments 
369  *      SUBROUTINE CALCFC (N,M,X,F,CON) 
370  *      DIMENSION X(*),CON(*)  . 
371  * The values of N and M are fixed and have been defined already, while 
372  * X is now the current vector of variables. The subroutine should return 
373  * the objective and constraint functions at X in F and CON(1),CON(2), 
374  * ...,CON(M). Note that we are trying to adjust X so that F(X) is as 
375  * small as possible subject to the constraint functions being nonnegative. 
376  *
377  * Partition the working space array W to provide the storage that is needed 
378  * for the main calculation.
379  */
380
381   stop->nevals = 0;
382
383   if (n == 0)
384   {
385     if (iprint>=1) fprintf(stderr, "cobyla: N==0.\n");
386     return NLOPT_SUCCESS;
387   }
388
389   if (n < 0 || m < 0)
390   {
391     if (iprint>=1) fprintf(stderr, "cobyla: N<0 or M<0.\n");
392     return NLOPT_INVALID_ARGS;
393   }
394
395   /* workspace allocation */
396   w = (double*) malloc(U(n*(3*n+2*m+11)+4*m+6)*sizeof(*w));
397   if (w == NULL)
398   {
399     if (iprint>=1) fprintf(stderr, "cobyla: memory allocation error.\n");
400     return NLOPT_OUT_OF_MEMORY;
401   }
402   iact = (int*)malloc(U(m+1)*sizeof(*iact));
403   if (iact == NULL)
404   {
405     if (iprint>=1) fprintf(stderr, "cobyla: memory allocation error.\n");
406     free(w);
407     return NLOPT_OUT_OF_MEMORY;
408   }
409   
410   /* Parameter adjustments */
411   --iact;
412   --w;
413   --x;
414   --lb; --ub;
415
416   /* Function Body */
417   mpp = m + 2;
418   icon = 1;
419   isim = icon + mpp;
420   isimi = isim + n * n + n;
421   idatm = isimi + n * n;
422   ia = idatm + n * mpp + mpp;
423   ivsig = ia + m * n + n;
424   iveta = ivsig + n;
425   isigb = iveta + n;
426   idx = isigb + n;
427   iwork = idx + n;
428   rc = cobylb(&n, &m, &mpp, &x[1], minf, &rhobeg, rhoend, stop, &lb[1], &ub[1], &iprint,
429       &w[icon], &w[isim], &w[isimi], &w[idatm], &w[ia], &w[ivsig], &w[iveta],
430       &w[isigb], &w[idx], &w[iwork], &iact[1], calcfc, state);
431
432   /* Parameter adjustments (reverse) */
433   ++iact;
434   ++w;
435
436   free(w);
437   free(iact);
438   
439   return rc;
440 } /* cobyla */
441
442 /* ------------------------------------------------------------------------- */
443 static nlopt_result cobylb(int *n, int *m, int *mpp,
444    double *x, double *minf, double *rhobeg, double rhoend,
445     nlopt_stopping *stop, const double *lb, const double *ub,
446     int *iprint, double *con, double *sim, double *simi, 
447     double *datmat, double *a, double *vsig, double *veta,
448      double *sigbar, double *dx, double *w, int *iact, cobyla_function *calcfc,
449      func_wrap_state *state)
450 {
451   /* System generated locals */
452   int sim_dim1, sim_offset, simi_dim1, simi_offset, datmat_dim1, 
453       datmat_offset, a_dim1, a_offset, i__1, i__2, i__3;
454   double d__1, d__2;
455
456   /* Local variables */
457   double alpha, delta, denom, tempa, barmu;
458   double beta, cmin = 0.0, cmax = 0.0;
459   double cvmaxm, dxsign, prerem = 0.0;
460   double edgmax, pareta, prerec = 0.0, phimin, parsig = 0.0;
461   double gamma_;
462   double phi, rho, sum = 0.0;
463   double ratio, vmold, parmu, error, vmnew;
464   double resmax, cvmaxp;
465   double resnew, trured;
466   double temp, wsig, f;
467   double weta;
468   int i__, j, k, l;
469   int idxnew;
470   int iflag = 0;
471   int iptemp;
472   int isdirn, izdota;
473   int ivmc;
474   int ivmd;
475   int mp, np, iz, ibrnch;
476   int nbest, ifull, iptem, jdrop;
477   nlopt_result rc = NLOPT_SUCCESS;
478   uint32_t seed = (uint32_t) (*n + *m); /* arbitrary deterministic LCG seed */
479   int feasible;
480
481   /* SGJ, 2008: added code to keep track of minimum feasible function val */
482   *minf = HUGE_VAL;
483
484 /* Set the initial values of some parameters. The last column of SIM holds */
485 /* the optimal vertex of the current simplex, and the preceding N columns */
486 /* hold the displacements from the optimal vertex to the other vertices. */
487 /* Further, SIMI holds the inverse of the matrix that is contained in the */
488 /* first N columns of SIM. */
489
490   /* Parameter adjustments */
491   a_dim1 = *n;
492   a_offset = 1 + a_dim1 * 1;
493   a -= a_offset;
494   simi_dim1 = *n;
495   simi_offset = 1 + simi_dim1 * 1;
496   simi -= simi_offset;
497   sim_dim1 = *n;
498   sim_offset = 1 + sim_dim1 * 1;
499   sim -= sim_offset;
500   datmat_dim1 = *mpp;
501   datmat_offset = 1 + datmat_dim1 * 1;
502   datmat -= datmat_offset;
503   --x;
504   --con;
505   --vsig;
506   --veta;
507   --sigbar;
508   --dx;
509   --w;
510   --iact;
511   --lb; --ub;
512
513   /* Function Body */
514   iptem = min(*n,4);
515   iptemp = iptem + 1;
516   np = *n + 1;
517   mp = *m + 1;
518   alpha = .25;
519   beta = 2.1;
520   gamma_ = .5;
521   delta = 1.1;
522   rho = *rhobeg;
523   parmu = 0.;
524   if (*iprint >= 2) {
525     fprintf(stderr,
526       "cobyla: the initial value of RHO is %12.6E and PARMU is set to zero.\n",
527       rho);
528   }
529   temp = 1. / rho;
530   i__1 = *n;
531   for (i__ = 1; i__ <= i__1; ++i__) {
532     double rhocur;
533     sim[i__ + np * sim_dim1] = x[i__];
534     i__2 = *n;
535     for (j = 1; j <= i__2; ++j) {
536       sim[i__ + j * sim_dim1] = 0.;
537       simi[i__ + j * simi_dim1] = 0.;
538     }
539     rhocur = rho;
540 #if ENFORCE_BOUNDS
541     /* SGJ: make sure step rhocur stays inside [lb,ub] */
542     if (x[i__] + rhocur > ub[i__]) {
543          if (x[i__] - rhocur >= lb[i__])
544               rhocur = -rhocur;
545          else if (ub[i__] - x[i__] > x[i__] - lb[i__])
546               rhocur = 0.5 * (ub[i__] - x[i__]);
547          else
548               rhocur = 0.5 * (x[i__] - lb[i__]);
549     }
550 #endif
551     sim[i__ + i__ * sim_dim1] = rhocur;
552     simi[i__ + i__ * simi_dim1] = 1.0 / rhocur;
553   }
554   jdrop = np;
555   ibrnch = 0;
556
557 /* Make the next call of the user-supplied subroutine CALCFC. These */
558 /* instructions are also used for calling CALCFC during the iterations of */
559 /* the algorithm. */
560
561   /* SGJ comment: why the hell couldn't he just use a damn subroutine?
562      #*&!%*@ Fortran-66 spaghetti code */
563
564 L40:
565   if (nlopt_stop_forced(stop)) rc = NLOPT_FORCED_STOP;
566   else if (nlopt_stop_evals(stop)) rc = NLOPT_MAXEVAL_REACHED;
567   else if (nlopt_stop_time(stop)) rc = NLOPT_MAXTIME_REACHED;
568   if (rc != NLOPT_SUCCESS) goto L600;
569
570   stop->nevals++;
571   if (calcfc(*n, *m, &x[1], &f, &con[1], state))
572   {
573     if (*iprint >= 1) {
574       fprintf(stderr, "cobyla: user requested end of minimization.\n");
575     }
576     rc = NLOPT_FORCED_STOP;
577     goto L600;
578   }
579
580   resmax = 0.;
581   feasible = 1; /* SGJ, 2010 */
582   if (*m > 0) {
583     i__1 = *m;
584     for (k = 1; k <= i__1; ++k) {
585       d__1 = resmax, d__2 = -con[k];
586       resmax = max(d__1,d__2);
587       if (d__2 > state->con_tol[k-1])
588            feasible = 0; /* SGJ, 2010 */
589     }
590   }
591
592   /* SGJ, 2008: check for minf_max reached by feasible point */
593   if (f < stop->minf_max && feasible) {
594        rc = NLOPT_MINF_MAX_REACHED;
595        goto L620; /* not L600 because we want to use current x, f, resmax */
596   }
597
598   if (stop->nevals == *iprint - 1 || *iprint == 3) {
599     fprintf(stderr, "cobyla: NFVALS = %4d, F =%13.6E, MAXCV =%13.6E\n",
600             stop->nevals, f, resmax);
601     i__1 = iptem;
602     fprintf(stderr, "cobyla: X =");
603     for (i__ = 1; i__ <= i__1; ++i__) {
604       if (i__>1) fprintf(stderr, "  ");
605       fprintf(stderr, "%13.6E", x[i__]);
606     }
607     if (iptem < *n) {
608       i__1 = *n;
609       for (i__ = iptemp; i__ <= i__1; ++i__) {
610         if (!((i__-1) % 4)) fprintf(stderr, "\ncobyla:  ");
611         fprintf(stderr, "%15.6E", x[i__]);
612       }
613     }
614     fprintf(stderr, "\n");
615   }
616   con[mp] = f;
617   con[*mpp] = resmax;
618   if (ibrnch == 1) {
619     goto L440;
620   }
621
622 /* Set the recently calculated function values in a column of DATMAT. This */
623 /* array has a column for each vertex of the current simplex, the entries of */
624 /* each column being the values of the constraint functions (if any) */
625 /* followed by the objective function and the greatest constraint violation */
626 /* at the vertex. */
627
628   i__1 = *mpp;
629   for (k = 1; k <= i__1; ++k) {
630     datmat[k + jdrop * datmat_dim1] = con[k];
631   }
632   if (stop->nevals > np) {
633     goto L130;
634   }
635
636 /* Exchange the new vertex of the initial simplex with the optimal vertex if */
637 /* necessary. Then, if the initial simplex is not complete, pick its next */
638 /* vertex and calculate the function values there. */
639
640   if (jdrop <= *n) {
641     if (datmat[mp + np * datmat_dim1] <= f) {
642       x[jdrop] = sim[jdrop + np * sim_dim1];
643     } else { /* improvement in function val */
644       double rhocur = x[jdrop] - sim[jdrop + np * sim_dim1];
645       /* SGJ: use rhocur instead of rho.  In original code, rhocur == rho
646               always, but I want to change this to ensure that simplex points
647               fall within [lb,ub]. */
648       sim[jdrop + np * sim_dim1] = x[jdrop];
649       i__1 = *mpp;
650       for (k = 1; k <= i__1; ++k) {
651         datmat[k + jdrop * datmat_dim1] = datmat[k + np * datmat_dim1]
652             ;
653         datmat[k + np * datmat_dim1] = con[k];
654       }
655       i__1 = jdrop;
656       for (k = 1; k <= i__1; ++k) {
657         sim[jdrop + k * sim_dim1] = -rhocur;
658         temp = 0.f;
659         i__2 = jdrop;
660         for (i__ = k; i__ <= i__2; ++i__) {
661           temp -= simi[i__ + k * simi_dim1];
662         }
663         simi[jdrop + k * simi_dim1] = temp;
664       }
665     }
666   }
667   if (stop->nevals <= *n) { /* evaluating initial simplex */
668     jdrop = stop->nevals;
669     /* SGJ: was += rho, but using sim[jdrop,jdrop] enforces consistency
670             if we change the stepsize above to stay in [lb,ub]. */
671     x[jdrop] += sim[jdrop + jdrop * sim_dim1];
672     goto L40;
673   }
674 L130:
675   ibrnch = 1;
676
677 /* Identify the optimal vertex of the current simplex. */
678
679 L140:
680   phimin = datmat[mp + np * datmat_dim1] + parmu * datmat[*mpp + np * 
681       datmat_dim1];
682   nbest = np;
683   i__1 = *n;
684   for (j = 1; j <= i__1; ++j) {
685     temp = datmat[mp + j * datmat_dim1] + parmu * datmat[*mpp + j * 
686         datmat_dim1];
687     if (temp < phimin) {
688       nbest = j;
689       phimin = temp;
690     } else if (temp == phimin && parmu == 0.) {
691       if (datmat[*mpp + j * datmat_dim1] < datmat[*mpp + nbest * 
692           datmat_dim1]) {
693         nbest = j;
694       }
695     }
696   }
697
698 /* Switch the best vertex into pole position if it is not there already, */
699 /* and also update SIM, SIMI and DATMAT. */
700
701   if (nbest <= *n) {
702     i__1 = *mpp;
703     for (i__ = 1; i__ <= i__1; ++i__) {
704       temp = datmat[i__ + np * datmat_dim1];
705       datmat[i__ + np * datmat_dim1] = datmat[i__ + nbest * datmat_dim1]
706           ;
707       datmat[i__ + nbest * datmat_dim1] = temp;
708     }
709     i__1 = *n;
710     for (i__ = 1; i__ <= i__1; ++i__) {
711       temp = sim[i__ + nbest * sim_dim1];
712       sim[i__ + nbest * sim_dim1] = 0.;
713       sim[i__ + np * sim_dim1] += temp;
714       tempa = 0.;
715       i__2 = *n;
716       for (k = 1; k <= i__2; ++k) {
717         sim[i__ + k * sim_dim1] -= temp;
718         tempa -= simi[k + i__ * simi_dim1];
719       }
720       simi[nbest + i__ * simi_dim1] = tempa;
721     }
722   }
723
724 /* Make an error return if SIGI is a poor approximation to the inverse of */
725 /* the leading N by N submatrix of SIG. */
726
727   error = 0.;
728   i__1 = *n;
729   for (i__ = 1; i__ <= i__1; ++i__) {
730     i__2 = *n;
731     for (j = 1; j <= i__2; ++j) {
732       temp = 0.;
733       if (i__ == j) {
734         temp += -1.;
735       }
736       i__3 = *n;
737       for (k = 1; k <= i__3; ++k) if (sim[k + j * sim_dim1] != 0) {
738         temp += simi[i__ + k * simi_dim1] * sim[k + j * sim_dim1];
739       }
740       d__1 = error, d__2 = abs(temp);
741       error = max(d__1,d__2);
742     }
743   }
744   if (error > .1) {
745     if (*iprint >= 1) {
746       fprintf(stderr, "cobyla: rounding errors are becoming damaging.\n");
747     }
748     rc = NLOPT_FAILURE;
749     goto L600;
750   }
751
752 /* Calculate the coefficients of the linear approximations to the objective */
753 /* and constraint functions, placing minus the objective function gradient */
754 /* after the constraint gradients in the array A. The vector W is used for */
755 /* working space. */
756
757   i__2 = mp;
758   for (k = 1; k <= i__2; ++k) {
759     con[k] = -datmat[k + np * datmat_dim1];
760     i__1 = *n;
761     for (j = 1; j <= i__1; ++j) {
762       w[j] = datmat[k + j * datmat_dim1] + con[k];
763     }
764     i__1 = *n;
765     for (i__ = 1; i__ <= i__1; ++i__) {
766       temp = 0.;
767       i__3 = *n;
768       for (j = 1; j <= i__3; ++j) {
769         temp += w[j] * simi[j + i__ * simi_dim1];
770       }
771       if (k == mp) {
772         temp = -temp;
773       }
774       a[i__ + k * a_dim1] = temp;
775     }
776   }
777
778 /* Calculate the values of sigma and eta, and set IFLAG=0 if the current */
779 /* simplex is not acceptable. */
780
781   iflag = 1;
782   parsig = alpha * rho;
783   pareta = beta * rho;
784   i__1 = *n;
785   for (j = 1; j <= i__1; ++j) {
786     wsig = 0.;
787     weta = 0.;
788     i__2 = *n;
789     for (i__ = 1; i__ <= i__2; ++i__) {
790       d__1 = simi[j + i__ * simi_dim1];
791       wsig += d__1 * d__1;
792       d__1 = sim[i__ + j * sim_dim1];
793       weta += d__1 * d__1;
794     }
795     vsig[j] = 1. / sqrt(wsig);
796     veta[j] = sqrt(weta);
797     if (vsig[j] < parsig || veta[j] > pareta) {
798       iflag = 0;
799     }
800   }
801
802 /* If a new vertex is needed to improve acceptability, then decide which */
803 /* vertex to drop from the simplex. */
804
805   if (ibrnch == 1 || iflag == 1) {
806     goto L370;
807   }
808   jdrop = 0;
809   temp = pareta;
810   i__1 = *n;
811   for (j = 1; j <= i__1; ++j) {
812     if (veta[j] > temp) {
813       jdrop = j;
814       temp = veta[j];
815     }
816   }
817   if (jdrop == 0) {
818     i__1 = *n;
819     for (j = 1; j <= i__1; ++j) {
820       if (vsig[j] < temp) {
821         jdrop = j;
822         temp = vsig[j];
823       }
824     }
825   }
826
827 /* Calculate the step to the new vertex and its sign. */
828
829   temp = gamma_ * rho * vsig[jdrop];
830   i__1 = *n;
831   for (i__ = 1; i__ <= i__1; ++i__) {
832     dx[i__] = temp * simi[jdrop + i__ * simi_dim1];
833   }
834   cvmaxp = 0.;
835   cvmaxm = 0.;
836   i__1 = mp;
837   for (k = 1; k <= i__1; ++k) {
838     sum = 0.;
839     i__2 = *n;
840     for (i__ = 1; i__ <= i__2; ++i__) {
841       sum += a[i__ + k * a_dim1] * dx[i__];
842     }
843     if (k < mp) {
844       temp = datmat[k + np * datmat_dim1];
845       d__1 = cvmaxp, d__2 = -sum - temp;
846       cvmaxp = max(d__1,d__2);
847       d__1 = cvmaxm, d__2 = sum - temp;
848       cvmaxm = max(d__1,d__2);
849     }
850   }
851   dxsign = 1.;
852   if (parmu * (cvmaxp - cvmaxm) > sum + sum) {
853     dxsign = -1.;
854   }
855
856 /* Update the elements of SIM and SIMI, and set the next X. */
857
858   temp = 0.;
859   i__1 = *n;
860   for (i__ = 1; i__ <= i__1; ++i__) {
861     /* SGJ, 2010: pseudo-randomize simplex steps (see LCG comments above) */
862     dx[i__] = dxsign * dx[i__] * lcg_urand(&seed, 0.01, 1);
863     /* SGJ: make sure dx step says in [lb,ub] */
864 #if ENFORCE_BOUNDS
865     {
866          double xi = sim[i__ + np * sim_dim1];
867     fixdx:
868          if (xi + dx[i__] > ub[i__])
869               dx[i__] = -dx[i__];
870          if (xi + dx[i__] < lb[i__]) {
871               if (xi - dx[i__] <= ub[i__])
872                    dx[i__] = -dx[i__];
873               else { /* try again with halved step */
874                    dx[i__] *= 0.5;
875                    goto fixdx;
876               }
877          }
878     }
879 #endif
880     sim[i__ + jdrop * sim_dim1] = dx[i__];
881     temp += simi[jdrop + i__ * simi_dim1] * dx[i__];
882   }
883   i__1 = *n;
884   for (i__ = 1; i__ <= i__1; ++i__) {
885     simi[jdrop + i__ * simi_dim1] /= temp;
886   }
887   i__1 = *n;
888   for (j = 1; j <= i__1; ++j) {
889     if (j != jdrop) {
890       temp = 0.;
891       i__2 = *n;
892       for (i__ = 1; i__ <= i__2; ++i__) {
893         temp += simi[j + i__ * simi_dim1] * dx[i__];
894       }
895       i__2 = *n;
896       for (i__ = 1; i__ <= i__2; ++i__) {
897         simi[j + i__ * simi_dim1] -= temp * simi[jdrop + i__ * 
898             simi_dim1];
899       }
900     }
901     x[j] = sim[j + np * sim_dim1] + dx[j];
902   }
903   goto L40;
904
905 /* Calculate DX=x(*)-x(0). Branch if the length of DX is less than 0.5*RHO. */
906
907 L370:
908   iz = 1;
909   izdota = iz + *n * *n;
910   ivmc = izdota + *n;
911   isdirn = ivmc + mp;
912   idxnew = isdirn + *n;
913   ivmd = idxnew + *n;
914   rc = trstlp(n, m, &a[a_offset], &con[1], &rho, &dx[1], &ifull, &iact[1], &w[
915       iz], &w[izdota], &w[ivmc], &w[isdirn], &w[idxnew], &w[ivmd]);
916   if (rc != NLOPT_SUCCESS) goto L600;
917 #if ENFORCE_BOUNDS
918   /* SGJ: since the bound constraints are linear, we should never get
919      a dx that lies outside the [lb,ub] constraints here, but we'll
920      enforce this anyway just to be paranoid */
921   i__1 = *n;
922   for (i__ = 1; i__ <= i__1; ++i__) {
923        double xi = sim[i__ + np * sim_dim1];
924        if (xi + dx[i__] > ub[i__]) dx[i__] = ub[i__] - xi;
925        if (xi + dx[i__] < lb[i__]) dx[i__] = xi - lb[i__];
926   }
927 #endif
928   if (ifull == 0) {
929     temp = 0.;
930     i__1 = *n;
931     for (i__ = 1; i__ <= i__1; ++i__) {
932       d__1 = dx[i__];
933       temp += d__1 * d__1;
934     }
935     if (temp < rho * .25 * rho) {
936       ibrnch = 1;
937       goto L550;
938     }
939   }
940
941 /* Predict the change to F and the new maximum constraint violation if the */
942 /* variables are altered from x(0) to x(0)+DX. */
943
944   resnew = 0.;
945   con[mp] = 0.;
946   i__1 = mp;
947   for (k = 1; k <= i__1; ++k) {
948     sum = con[k];
949     i__2 = *n;
950     for (i__ = 1; i__ <= i__2; ++i__) {
951       sum -= a[i__ + k * a_dim1] * dx[i__];
952     }
953     if (k < mp) {
954       resnew = max(resnew,sum);
955     }
956   }
957
958 /* Increase PARMU if necessary and branch back if this change alters the */
959 /* optimal vertex. Otherwise PREREM and PREREC will be set to the predicted */
960 /* reductions in the merit function and the maximum constraint violation */
961 /* respectively. */
962
963   barmu = 0.;
964   prerec = datmat[*mpp + np * datmat_dim1] - resnew;
965   if (prerec > 0.) {
966     barmu = sum / prerec;
967   }
968   if (parmu < barmu * 1.5) {
969     parmu = barmu * 2.;
970     if (*iprint >= 2) {
971       fprintf(stderr, "cobyla: increase in PARMU to %12.6E\n", parmu);
972     }
973     phi = datmat[mp + np * datmat_dim1] + parmu * datmat[*mpp + np * 
974         datmat_dim1];
975     i__1 = *n;
976     for (j = 1; j <= i__1; ++j) {
977       temp = datmat[mp + j * datmat_dim1] + parmu * datmat[*mpp + j * 
978           datmat_dim1];
979       if (temp < phi) {
980         goto L140;
981       }
982       if (temp == phi && parmu == 0.f) {
983         if (datmat[*mpp + j * datmat_dim1] < datmat[*mpp + np * 
984             datmat_dim1]) {
985           goto L140;
986         }
987       }
988     }
989   }
990   prerem = parmu * prerec - sum;
991
992 /* Calculate the constraint and objective functions at x(*). Then find the */
993 /* actual reduction in the merit function. */
994
995   i__1 = *n;
996   for (i__ = 1; i__ <= i__1; ++i__) {
997     x[i__] = sim[i__ + np * sim_dim1] + dx[i__];
998   }
999   ibrnch = 1;
1000   goto L40;
1001 L440:
1002   vmold = datmat[mp + np * datmat_dim1] + parmu * datmat[*mpp + np * 
1003       datmat_dim1];
1004   vmnew = f + parmu * resmax;
1005   trured = vmold - vmnew;
1006   if (parmu == 0. && f == datmat[mp + np * datmat_dim1]) {
1007     prerem = prerec;
1008     trured = datmat[*mpp + np * datmat_dim1] - resmax;
1009   }
1010
1011 /* Begin the operations that decide whether x(*) should replace one of the */
1012 /* vertices of the current simplex, the change being mandatory if TRURED is */
1013 /* positive. Firstly, JDROP is set to the index of the vertex that is to be */
1014 /* replaced. */
1015
1016   ratio = 0.;
1017   if (trured <= 0.f) {
1018     ratio = 1.f;
1019   }
1020   jdrop = 0;
1021   i__1 = *n;
1022   for (j = 1; j <= i__1; ++j) {
1023     temp = 0.;
1024     i__2 = *n;
1025     for (i__ = 1; i__ <= i__2; ++i__) {
1026       temp += simi[j + i__ * simi_dim1] * dx[i__];
1027     }
1028     temp = abs(temp);
1029     if (temp > ratio) {
1030       jdrop = j;
1031       ratio = temp;
1032     }
1033     sigbar[j] = temp * vsig[j];
1034   }
1035
1036 /* Calculate the value of ell. */
1037
1038   edgmax = delta * rho;
1039   l = 0;
1040   i__1 = *n;
1041   for (j = 1; j <= i__1; ++j) {
1042     if (sigbar[j] >= parsig || sigbar[j] >= vsig[j]) {
1043       temp = veta[j];
1044       if (trured > 0.) {
1045         temp = 0.;
1046         i__2 = *n;
1047         for (i__ = 1; i__ <= i__2; ++i__) {
1048           d__1 = dx[i__] - sim[i__ + j * sim_dim1];
1049           temp += d__1 * d__1;
1050         }
1051         temp = sqrt(temp);
1052       }
1053       if (temp > edgmax) {
1054         l = j;
1055         edgmax = temp;
1056       }
1057     }
1058   }
1059   if (l > 0) {
1060     jdrop = l;
1061   }
1062   if (jdrop == 0) {
1063     goto L550;
1064   }
1065
1066 /* Revise the simplex by updating the elements of SIM, SIMI and DATMAT. */
1067
1068   temp = 0.;
1069   i__1 = *n;
1070   for (i__ = 1; i__ <= i__1; ++i__) {
1071     sim[i__ + jdrop * sim_dim1] = dx[i__];
1072     temp += simi[jdrop + i__ * simi_dim1] * dx[i__];
1073   }
1074   i__1 = *n;
1075   for (i__ = 1; i__ <= i__1; ++i__) {
1076     simi[jdrop + i__ * simi_dim1] /= temp;
1077   }
1078   i__1 = *n;
1079   for (j = 1; j <= i__1; ++j) {
1080     if (j != jdrop) {
1081       temp = 0.;
1082       i__2 = *n;
1083       for (i__ = 1; i__ <= i__2; ++i__) {
1084         temp += simi[j + i__ * simi_dim1] * dx[i__];
1085       }
1086       i__2 = *n;
1087       for (i__ = 1; i__ <= i__2; ++i__) {
1088         simi[j + i__ * simi_dim1] -= temp * simi[jdrop + i__ * 
1089             simi_dim1];
1090       }
1091     }
1092   }
1093   i__1 = *mpp;
1094   for (k = 1; k <= i__1; ++k) {
1095     datmat[k + jdrop * datmat_dim1] = con[k];
1096   }
1097
1098 /* Branch back for further iterations with the current RHO. */
1099
1100   if (trured > 0. && trured >= prerem * .1) {
1101     /* SGJ, 2010: following a suggestion in the SAS manual (which
1102        mentions a similar modification to COBYLA, although they didn't
1103        publish their source code), increase rho if predicted reduction
1104        is sufficiently close to the actual reduction.  Otherwise,
1105        COBLYA seems to easily get stuck making very small steps. 
1106        Also require iflag != 0 (i.e., acceptable simplex), again
1107        following SAS suggestion (otherwise I get convergence failure
1108        in some cases.) */
1109     if (trured >= prerem * 0.9 && trured <= prerem * 1.1 && iflag) {
1110          rho *= 2.0;
1111     }
1112     goto L140;
1113   }
1114 L550:
1115   if (iflag == 0) {
1116     ibrnch = 0;
1117     goto L140;
1118   }
1119
1120   /* SGJ, 2008: convergence tests for function vals; note that current
1121      best val is stored in datmat[mp + np * datmat_dim1], or in f if
1122      ifull == 1, and previous best is in *minf.  This seems like a
1123      sensible place to put the convergence test, as it is the same
1124      place that Powell checks the x tolerance (rho > rhoend). */
1125   {
1126        double fbest = ifull == 1 ? f : datmat[mp + np * datmat_dim1];
1127        if (fbest < *minf && nlopt_stop_ftol(stop, fbest, *minf)) {
1128             rc = NLOPT_FTOL_REACHED;
1129             goto L600;
1130        }
1131        *minf = fbest;
1132   }
1133
1134 /* Otherwise reduce RHO if it is not at its least value and reset PARMU. */
1135
1136   if (rho > rhoend) {
1137     rho *= .5;
1138     if (rho <= rhoend * 1.5) {
1139       rho = rhoend;
1140     }
1141     if (parmu > 0.) {
1142       denom = 0.;
1143       i__1 = mp;
1144       for (k = 1; k <= i__1; ++k) {
1145         cmin = datmat[k + np * datmat_dim1];
1146         cmax = cmin;
1147         i__2 = *n;
1148         for (i__ = 1; i__ <= i__2; ++i__) {
1149           d__1 = cmin, d__2 = datmat[k + i__ * datmat_dim1];
1150           cmin = min(d__1,d__2);
1151           d__1 = cmax, d__2 = datmat[k + i__ * datmat_dim1];
1152           cmax = max(d__1,d__2);
1153         }
1154         if (k <= *m && cmin < cmax * .5) {
1155           temp = max(cmax,0.) - cmin;
1156           if (denom <= 0.) {
1157             denom = temp;
1158           } else {
1159             denom = min(denom,temp);
1160           }
1161         }
1162       }
1163       if (denom == 0.) {
1164         parmu = 0.;
1165       } else if (cmax - cmin < parmu * denom) {
1166         parmu = (cmax - cmin) / denom;
1167       }
1168     }
1169     if (*iprint >= 2) {
1170       fprintf(stderr, "cobyla: reduction in RHO to %12.6E and PARMU =%13.6E\n",
1171         rho, parmu);
1172     }
1173     if (*iprint == 2) {
1174       fprintf(stderr, "cobyla: NFVALS = %4d, F =%13.6E, MAXCV =%13.6E\n",
1175         stop->nevals, datmat[mp + np * datmat_dim1], datmat[*mpp + np * datmat_dim1]);
1176
1177       fprintf(stderr, "cobyla: X =");
1178       i__1 = iptem;
1179       for (i__ = 1; i__ <= i__1; ++i__) {
1180         if (i__>1) fprintf(stderr, "  ");
1181         fprintf(stderr, "%13.6E", sim[i__ + np * sim_dim1]);
1182       }
1183       if (iptem < *n) {
1184         i__1 = *n;
1185         for (i__ = iptemp; i__ <= i__1; ++i__) {
1186           if (!((i__-1) % 4)) fprintf(stderr, "\ncobyla:  ");
1187           fprintf(stderr, "%15.6E", x[i__]);
1188         }
1189       }
1190       fprintf(stderr, "\n");
1191     }
1192     goto L140;
1193   }
1194   else
1195        rc = NLOPT_XTOL_REACHED;
1196
1197 /* Return the best calculated values of the variables. */
1198
1199   if (*iprint >= 1) {
1200     fprintf(stderr, "cobyla: normal return.\n");
1201   }
1202   if (ifull == 1) {
1203     goto L620;
1204   }
1205 L600:
1206   i__1 = *n;
1207   for (i__ = 1; i__ <= i__1; ++i__) {
1208     x[i__] = sim[i__ + np * sim_dim1];
1209   }
1210   f = datmat[mp + np * datmat_dim1];
1211   resmax = datmat[*mpp + np * datmat_dim1];
1212 L620:
1213   *minf = f;
1214   if (*iprint >= 1) {
1215     fprintf(stderr, "cobyla: NFVALS = %4d, F =%13.6E, MAXCV =%13.6E\n",
1216             stop->nevals, f, resmax);
1217     i__1 = iptem;
1218     fprintf(stderr, "cobyla: X =");
1219     for (i__ = 1; i__ <= i__1; ++i__) {
1220       if (i__>1) fprintf(stderr, "  ");
1221       fprintf(stderr, "%13.6E", x[i__]);
1222     }
1223     if (iptem < *n) {
1224       i__1 = *n;
1225       for (i__ = iptemp; i__ <= i__1; ++i__) {
1226         if (!((i__-1) % 4)) fprintf(stderr, "\ncobyla:  ");
1227         fprintf(stderr, "%15.6E", x[i__]);
1228       }
1229     }
1230     fprintf(stderr, "\n");
1231   }
1232   return rc;
1233 } /* cobylb */
1234
1235 /* ------------------------------------------------------------------------- */
1236 static nlopt_result trstlp(int *n, int *m, double *a, 
1237     double *b, double *rho, double *dx, int *ifull, 
1238     int *iact, double *z__, double *zdota, double *vmultc,
1239      double *sdirn, double *dxnew, double *vmultd)
1240 {
1241   /* System generated locals */
1242   int a_dim1, a_offset, z_dim1, z_offset, i__1, i__2;
1243   double d__1, d__2;
1244
1245   /* Local variables */
1246   double alpha, tempa;
1247   double beta;
1248   double optnew, stpful, sum, tot, acca, accb;
1249   double ratio, vsave, zdotv, zdotw, dd;
1250   double sd;
1251   double sp, ss, resold = 0.0, zdvabs, zdwabs, sumabs, resmax, optold;
1252   double spabs;
1253   double temp, step;
1254   int icount;
1255   int iout, i__, j, k;
1256   int isave;
1257   int kk;
1258   int kl, kp, kw;
1259   int nact, icon = 0, mcon;
1260   int nactx = 0;
1261
1262
1263 /* This subroutine calculates an N-component vector DX by applying the */
1264 /* following two stages. In the first stage, DX is set to the shortest */
1265 /* vector that minimizes the greatest violation of the constraints */
1266 /*   A(1,K)*DX(1)+A(2,K)*DX(2)+...+A(N,K)*DX(N) .GE. B(K), K=2,3,...,M, */
1267 /* subject to the Euclidean length of DX being at most RHO. If its length is */
1268 /* strictly less than RHO, then we use the resultant freedom in DX to */
1269 /* minimize the objective function */
1270 /*      -A(1,M+1)*DX(1)-A(2,M+1)*DX(2)-...-A(N,M+1)*DX(N) */
1271 /* subject to no increase in any greatest constraint violation. This */
1272 /* notation allows the gradient of the objective function to be regarded as */
1273 /* the gradient of a constraint. Therefore the two stages are distinguished */
1274 /* by MCON .EQ. M and MCON .GT. M respectively. It is possible that a */
1275 /* degeneracy may prevent DX from attaining the target length RHO. Then the */
1276 /* value IFULL=0 would be set, but usually IFULL=1 on return. */
1277
1278 /* In general NACT is the number of constraints in the active set and */
1279 /* IACT(1),...,IACT(NACT) are their indices, while the remainder of IACT */
1280 /* contains a permutation of the remaining constraint indices. Further, Z is */
1281 /* an orthogonal matrix whose first NACT columns can be regarded as the */
1282 /* result of Gram-Schmidt applied to the active constraint gradients. For */
1283 /* J=1,2,...,NACT, the number ZDOTA(J) is the scalar product of the J-th */
1284 /* column of Z with the gradient of the J-th active constraint. DX is the */
1285 /* current vector of variables and here the residuals of the active */
1286 /* constraints should be zero. Further, the active constraints have */
1287 /* nonnegative Lagrange multipliers that are held at the beginning of */
1288 /* VMULTC. The remainder of this vector holds the residuals of the inactive */
1289 /* constraints at DX, the ordering of the components of VMULTC being in */
1290 /* agreement with the permutation of the indices of the constraints that is */
1291 /* in IACT. All these residuals are nonnegative, which is achieved by the */
1292 /* shift RESMAX that makes the least residual zero. */
1293
1294 /* Initialize Z and some other variables. The value of RESMAX will be */
1295 /* appropriate to DX=0, while ICON will be the index of a most violated */
1296 /* constraint if RESMAX is positive. Usually during the first stage the */
1297 /* vector SDIRN gives a search direction that reduces all the active */
1298 /* constraint violations by one simultaneously. */
1299
1300   /* Parameter adjustments */
1301   z_dim1 = *n;
1302   z_offset = 1 + z_dim1 * 1;
1303   z__ -= z_offset;
1304   a_dim1 = *n;
1305   a_offset = 1 + a_dim1 * 1;
1306   a -= a_offset;
1307   --b;
1308   --dx;
1309   --iact;
1310   --zdota;
1311   --vmultc;
1312   --sdirn;
1313   --dxnew;
1314   --vmultd;
1315
1316   /* Function Body */
1317   *ifull = 1;
1318   mcon = *m;
1319   nact = 0;
1320   resmax = 0.;
1321   i__1 = *n;
1322   for (i__ = 1; i__ <= i__1; ++i__) {
1323     i__2 = *n;
1324     for (j = 1; j <= i__2; ++j) {
1325       z__[i__ + j * z_dim1] = 0.;
1326     }
1327     z__[i__ + i__ * z_dim1] = 1.;
1328     dx[i__] = 0.;
1329   }
1330   if (*m >= 1) {
1331     i__1 = *m;
1332     for (k = 1; k <= i__1; ++k) {
1333       if (b[k] > resmax) {
1334         resmax = b[k];
1335         icon = k;
1336       }
1337     }
1338     i__1 = *m;
1339     for (k = 1; k <= i__1; ++k) {
1340       iact[k] = k;
1341       vmultc[k] = resmax - b[k];
1342     }
1343   }
1344   if (resmax == 0.) {
1345     goto L480;
1346   }
1347   i__1 = *n;
1348   for (i__ = 1; i__ <= i__1; ++i__) {
1349     sdirn[i__] = 0.;
1350   }
1351
1352 /* End the current stage of the calculation if 3 consecutive iterations */
1353 /* have either failed to reduce the best calculated value of the objective */
1354 /* function or to increase the number of active constraints since the best */
1355 /* value was calculated. This strategy prevents cycling, but there is a */
1356 /* remote possibility that it will cause premature termination. */
1357
1358 L60:
1359   optold = 0.;
1360   icount = 0;
1361 L70:
1362   if (mcon == *m) {
1363     optnew = resmax;
1364   } else {
1365     optnew = 0.;
1366     i__1 = *n;
1367     for (i__ = 1; i__ <= i__1; ++i__) {
1368       optnew -= dx[i__] * a[i__ + mcon * a_dim1];
1369     }
1370   }
1371   if (icount == 0 || optnew < optold) {
1372     optold = optnew;
1373     nactx = nact;
1374     icount = 3;
1375   } else if (nact > nactx) {
1376     nactx = nact;
1377     icount = 3;
1378   } else {
1379     --icount;
1380     if (icount == 0) {
1381       goto L490;
1382     }
1383   }
1384
1385 /* If ICON exceeds NACT, then we add the constraint with index IACT(ICON) to */
1386 /* the active set. Apply Givens rotations so that the last N-NACT-1 columns */
1387 /* of Z are orthogonal to the gradient of the new constraint, a scalar */
1388 /* product being set to zero if its nonzero value could be due to computer */
1389 /* rounding errors. The array DXNEW is used for working space. */
1390
1391   if (icon <= nact) {
1392     goto L260;
1393   }
1394   kk = iact[icon];
1395   i__1 = *n;
1396   for (i__ = 1; i__ <= i__1; ++i__) {
1397     dxnew[i__] = a[i__ + kk * a_dim1];
1398   }
1399   tot = 0.;
1400   k = *n;
1401 L100:
1402   if (k > nact) {
1403     sp = 0.;
1404     spabs = 0.;
1405     i__1 = *n;
1406     for (i__ = 1; i__ <= i__1; ++i__) {
1407       temp = z__[i__ + k * z_dim1] * dxnew[i__];
1408       sp += temp;
1409       spabs += abs(temp);
1410     }
1411     acca = spabs + abs(sp) * .1;
1412     accb = spabs + abs(sp) * .2;
1413     if (spabs >= acca || acca >= accb) {
1414       sp = 0.;
1415     }
1416     if (tot == 0.) {
1417       tot = sp;
1418     } else {
1419       kp = k + 1;
1420       temp = sqrt(sp * sp + tot * tot);
1421       alpha = sp / temp;
1422       beta = tot / temp;
1423       tot = temp;
1424       i__1 = *n;
1425       for (i__ = 1; i__ <= i__1; ++i__) {
1426         temp = alpha * z__[i__ + k * z_dim1] + beta * z__[i__ + kp * 
1427             z_dim1];
1428         z__[i__ + kp * z_dim1] = alpha * z__[i__ + kp * z_dim1] - 
1429             beta * z__[i__ + k * z_dim1];
1430         z__[i__ + k * z_dim1] = temp;
1431       }
1432     }
1433     --k;
1434     goto L100;
1435   }
1436
1437 /* Add the new constraint if this can be done without a deletion from the */
1438 /* active set. */
1439
1440   if (tot != 0.) {
1441     ++nact;
1442     zdota[nact] = tot;
1443     vmultc[icon] = vmultc[nact];
1444     vmultc[nact] = 0.;
1445     goto L210;
1446   }
1447
1448 /* The next instruction is reached if a deletion has to be made from the */
1449 /* active set in order to make room for the new active constraint, because */
1450 /* the new constraint gradient is a linear combination of the gradients of */
1451 /* the old active constraints. Set the elements of VMULTD to the multipliers */
1452 /* of the linear combination. Further, set IOUT to the index of the */
1453 /* constraint to be deleted, but branch if no suitable index can be found. */
1454
1455   ratio = -1.;
1456   k = nact;
1457 L130:
1458   zdotv = 0.;
1459   zdvabs = 0.;
1460   i__1 = *n;
1461   for (i__ = 1; i__ <= i__1; ++i__) {
1462     temp = z__[i__ + k * z_dim1] * dxnew[i__];
1463     zdotv += temp;
1464     zdvabs += abs(temp);
1465   }
1466   acca = zdvabs + abs(zdotv) * .1;
1467   accb = zdvabs + abs(zdotv) * .2;
1468   if (zdvabs < acca && acca < accb) {
1469     temp = zdotv / zdota[k];
1470     if (temp > 0. && iact[k] <= *m) {
1471       tempa = vmultc[k] / temp;
1472       if (ratio < 0. || tempa < ratio) {
1473         ratio = tempa;
1474         iout = k;
1475       }
1476     }
1477     if (k >= 2) {
1478       kw = iact[k];
1479       i__1 = *n;
1480       for (i__ = 1; i__ <= i__1; ++i__) {
1481         dxnew[i__] -= temp * a[i__ + kw * a_dim1];
1482       }
1483     }
1484     vmultd[k] = temp;
1485   } else {
1486     vmultd[k] = 0.;
1487   }
1488   --k;
1489   if (k > 0) {
1490     goto L130;
1491   }
1492   if (ratio < 0.) {
1493     goto L490;
1494   }
1495
1496 /* Revise the Lagrange multipliers and reorder the active constraints so */
1497 /* that the one to be replaced is at the end of the list. Also calculate the */
1498 /* new value of ZDOTA(NACT) and branch if it is not acceptable. */
1499
1500   i__1 = nact;
1501   for (k = 1; k <= i__1; ++k) {
1502     d__1 = 0., d__2 = vmultc[k] - ratio * vmultd[k];
1503     vmultc[k] = max(d__1,d__2);
1504   }
1505   if (icon < nact) {
1506     isave = iact[icon];
1507     vsave = vmultc[icon];
1508     k = icon;
1509 L170:
1510     kp = k + 1;
1511     kw = iact[kp];
1512     sp = 0.;
1513     i__1 = *n;
1514     for (i__ = 1; i__ <= i__1; ++i__) {
1515       sp += z__[i__ + k * z_dim1] * a[i__ + kw * a_dim1];
1516     }
1517     d__1 = zdota[kp];
1518     temp = sqrt(sp * sp + d__1 * d__1);
1519     alpha = zdota[kp] / temp;
1520     beta = sp / temp;
1521     zdota[kp] = alpha * zdota[k];
1522     zdota[k] = temp;
1523     i__1 = *n;
1524     for (i__ = 1; i__ <= i__1; ++i__) {
1525       temp = alpha * z__[i__ + kp * z_dim1] + beta * z__[i__ + k * 
1526           z_dim1];
1527       z__[i__ + kp * z_dim1] = alpha * z__[i__ + k * z_dim1] - beta * 
1528           z__[i__ + kp * z_dim1];
1529       z__[i__ + k * z_dim1] = temp;
1530     }
1531     iact[k] = kw;
1532     vmultc[k] = vmultc[kp];
1533     k = kp;
1534     if (k < nact) {
1535       goto L170;
1536     }
1537     iact[k] = isave;
1538     vmultc[k] = vsave;
1539   }
1540   temp = 0.;
1541   i__1 = *n;
1542   for (i__ = 1; i__ <= i__1; ++i__) {
1543     temp += z__[i__ + nact * z_dim1] * a[i__ + kk * a_dim1];
1544   }
1545   if (temp == 0.) {
1546     goto L490;
1547   }
1548   zdota[nact] = temp;
1549   vmultc[icon] = 0.;
1550   vmultc[nact] = ratio;
1551
1552 /* Update IACT and ensure that the objective function continues to be */
1553 /* treated as the last active constraint when MCON>M. */
1554
1555 L210:
1556   iact[icon] = iact[nact];
1557   iact[nact] = kk;
1558   if (mcon > *m && kk != mcon) {
1559     k = nact - 1;
1560     sp = 0.;
1561     i__1 = *n;
1562     for (i__ = 1; i__ <= i__1; ++i__) {
1563       sp += z__[i__ + k * z_dim1] * a[i__ + kk * a_dim1];
1564     }
1565     d__1 = zdota[nact];
1566     temp = sqrt(sp * sp + d__1 * d__1);
1567     alpha = zdota[nact] / temp;
1568     beta = sp / temp;
1569     zdota[nact] = alpha * zdota[k];
1570     zdota[k] = temp;
1571     i__1 = *n;
1572     for (i__ = 1; i__ <= i__1; ++i__) {
1573       temp = alpha * z__[i__ + nact * z_dim1] + beta * z__[i__ + k * 
1574           z_dim1];
1575       z__[i__ + nact * z_dim1] = alpha * z__[i__ + k * z_dim1] - beta * 
1576           z__[i__ + nact * z_dim1];
1577       z__[i__ + k * z_dim1] = temp;
1578     }
1579     iact[nact] = iact[k];
1580     iact[k] = kk;
1581     temp = vmultc[k];
1582     vmultc[k] = vmultc[nact];
1583     vmultc[nact] = temp;
1584   }
1585
1586 /* If stage one is in progress, then set SDIRN to the direction of the next */
1587 /* change to the current vector of variables. */
1588
1589   if (mcon > *m) {
1590     goto L320;
1591   }
1592   kk = iact[nact];
1593   temp = 0.;
1594   i__1 = *n;
1595   for (i__ = 1; i__ <= i__1; ++i__) {
1596     temp += sdirn[i__] * a[i__ + kk * a_dim1];
1597   }
1598   temp += -1.;
1599   temp /= zdota[nact];
1600   i__1 = *n;
1601   for (i__ = 1; i__ <= i__1; ++i__) {
1602     sdirn[i__] -= temp * z__[i__ + nact * z_dim1];
1603   }
1604   goto L340;
1605
1606 /* Delete the constraint that has the index IACT(ICON) from the active set. */
1607
1608 L260:
1609   if (icon < nact) {
1610     isave = iact[icon];
1611     vsave = vmultc[icon];
1612     k = icon;
1613 L270:
1614     kp = k + 1;
1615     kk = iact[kp];
1616     sp = 0.;
1617     i__1 = *n;
1618     for (i__ = 1; i__ <= i__1; ++i__) {
1619       sp += z__[i__ + k * z_dim1] * a[i__ + kk * a_dim1];
1620     }
1621     d__1 = zdota[kp];
1622     temp = sqrt(sp * sp + d__1 * d__1);
1623     alpha = zdota[kp] / temp;
1624     beta = sp / temp;
1625     zdota[kp] = alpha * zdota[k];
1626     zdota[k] = temp;
1627     i__1 = *n;
1628     for (i__ = 1; i__ <= i__1; ++i__) {
1629       temp = alpha * z__[i__ + kp * z_dim1] + beta * z__[i__ + k * 
1630           z_dim1];
1631       z__[i__ + kp * z_dim1] = alpha * z__[i__ + k * z_dim1] - beta * 
1632           z__[i__ + kp * z_dim1];
1633       z__[i__ + k * z_dim1] = temp;
1634     }
1635     iact[k] = kk;
1636     vmultc[k] = vmultc[kp];
1637     k = kp;
1638     if (k < nact) {
1639       goto L270;
1640     }
1641     iact[k] = isave;
1642     vmultc[k] = vsave;
1643   }
1644   --nact;
1645
1646 /* If stage one is in progress, then set SDIRN to the direction of the next */
1647 /* change to the current vector of variables. */
1648
1649   if (mcon > *m) {
1650     goto L320;
1651   }
1652   temp = 0.;
1653   i__1 = *n;
1654   for (i__ = 1; i__ <= i__1; ++i__) {
1655     temp += sdirn[i__] * z__[i__ + (nact + 1) * z_dim1];
1656   }
1657   i__1 = *n;
1658   for (i__ = 1; i__ <= i__1; ++i__) {
1659     sdirn[i__] -= temp * z__[i__ + (nact + 1) * z_dim1];
1660   }
1661   goto L340;
1662
1663 /* Pick the next search direction of stage two. */
1664
1665 L320:
1666   temp = 1. / zdota[nact];
1667   i__1 = *n;
1668   for (i__ = 1; i__ <= i__1; ++i__) {
1669     sdirn[i__] = temp * z__[i__ + nact * z_dim1];
1670   }
1671
1672 /* Calculate the step to the boundary of the trust region or take the step */
1673 /* that reduces RESMAX to zero. The two statements below that include the */
1674 /* factor 1.0E-6 prevent some harmless underflows that occurred in a test */
1675 /* calculation. Further, we skip the step if it could be zero within a */
1676 /* reasonable tolerance for computer rounding errors. */
1677
1678 L340:
1679   dd = *rho * *rho;
1680   sd = 0.;
1681   ss = 0.;
1682   i__1 = *n;
1683   for (i__ = 1; i__ <= i__1; ++i__) {
1684     if ((d__1 = dx[i__], abs(d__1)) >= *rho * 1e-6f) {
1685       d__2 = dx[i__];
1686       dd -= d__2 * d__2;
1687     }
1688     sd += dx[i__] * sdirn[i__];
1689     d__1 = sdirn[i__];
1690     ss += d__1 * d__1;
1691   }
1692   if (dd <= 0.) {
1693     goto L490;
1694   }
1695   temp = sqrt(ss * dd);
1696   if (abs(sd) >= temp * 1e-6f) {
1697     temp = sqrt(ss * dd + sd * sd);
1698   }
1699   stpful = dd / (temp + sd);
1700   step = stpful;
1701   if (mcon == *m) {
1702     acca = step + resmax * .1;
1703     accb = step + resmax * .2;
1704     if (step >= acca || acca >= accb) {
1705       goto L480;
1706     }
1707     step = min(step,resmax);
1708   }
1709
1710   /* SGJ, 2010: check for error here */
1711   if (nlopt_isinf(step)) return NLOPT_ROUNDOFF_LIMITED;
1712
1713 /* Set DXNEW to the new variables if STEP is the steplength, and reduce */
1714 /* RESMAX to the corresponding maximum residual if stage one is being done. */
1715 /* Because DXNEW will be changed during the calculation of some Lagrange */
1716 /* multipliers, it will be restored to the following value later. */
1717
1718   i__1 = *n;
1719   for (i__ = 1; i__ <= i__1; ++i__) {
1720     dxnew[i__] = dx[i__] + step * sdirn[i__];
1721   }
1722   if (mcon == *m) {
1723     resold = resmax;
1724     resmax = 0.;
1725     i__1 = nact;
1726     for (k = 1; k <= i__1; ++k) {
1727       kk = iact[k];
1728       temp = b[kk];
1729       i__2 = *n;
1730       for (i__ = 1; i__ <= i__2; ++i__) {
1731         temp -= a[i__ + kk * a_dim1] * dxnew[i__];
1732       }
1733       resmax = max(resmax,temp);
1734     }
1735   }
1736
1737 /* Set VMULTD to the VMULTC vector that would occur if DX became DXNEW. A */
1738 /* device is included to force VMULTD(K)=0.0 if deviations from this value */
1739 /* can be attributed to computer rounding errors. First calculate the new */
1740 /* Lagrange multipliers. */
1741
1742   k = nact;
1743 L390:
1744   zdotw = 0.;
1745   zdwabs = 0.;
1746   i__1 = *n;
1747   for (i__ = 1; i__ <= i__1; ++i__) {
1748     temp = z__[i__ + k * z_dim1] * dxnew[i__];
1749     zdotw += temp;
1750     zdwabs += abs(temp);
1751   }
1752   acca = zdwabs + abs(zdotw) * .1;
1753   accb = zdwabs + abs(zdotw) * .2;
1754   if (zdwabs >= acca || acca >= accb) {
1755     zdotw = 0.;
1756   }
1757   vmultd[k] = zdotw / zdota[k];
1758   if (k >= 2) {
1759     kk = iact[k];
1760     i__1 = *n;
1761     for (i__ = 1; i__ <= i__1; ++i__) {
1762       dxnew[i__] -= vmultd[k] * a[i__ + kk * a_dim1];
1763     }
1764     --k;
1765     goto L390;
1766   }
1767   if (mcon > *m) {
1768     d__1 = 0., d__2 = vmultd[nact];
1769     vmultd[nact] = max(d__1,d__2);
1770   }
1771
1772 /* Complete VMULTC by finding the new constraint residuals. */
1773
1774   i__1 = *n;
1775   for (i__ = 1; i__ <= i__1; ++i__) {
1776     dxnew[i__] = dx[i__] + step * sdirn[i__];
1777   }
1778   if (mcon > nact) {
1779     kl = nact + 1;
1780     i__1 = mcon;
1781     for (k = kl; k <= i__1; ++k) {
1782       kk = iact[k];
1783       sum = resmax - b[kk];
1784       sumabs = resmax + (d__1 = b[kk], abs(d__1));
1785       i__2 = *n;
1786       for (i__ = 1; i__ <= i__2; ++i__) {
1787         temp = a[i__ + kk * a_dim1] * dxnew[i__];
1788         sum += temp;
1789         sumabs += abs(temp);
1790       }
1791       acca = sumabs + abs(sum) * .1f;
1792       accb = sumabs + abs(sum) * .2f;
1793       if (sumabs >= acca || acca >= accb) {
1794         sum = 0.f;
1795       }
1796       vmultd[k] = sum;
1797     }
1798   }
1799
1800 /* Calculate the fraction of the step from DX to DXNEW that will be taken. */
1801
1802   ratio = 1.;
1803   icon = 0;
1804   i__1 = mcon;
1805   for (k = 1; k <= i__1; ++k) {
1806     if (vmultd[k] < 0.) {
1807       temp = vmultc[k] / (vmultc[k] - vmultd[k]);
1808       if (temp < ratio) {
1809         ratio = temp;
1810         icon = k;
1811       }
1812     }
1813   }
1814
1815 /* Update DX, VMULTC and RESMAX. */
1816
1817   temp = 1. - ratio;
1818   i__1 = *n;
1819   for (i__ = 1; i__ <= i__1; ++i__) {
1820     dx[i__] = temp * dx[i__] + ratio * dxnew[i__];
1821   }
1822   i__1 = mcon;
1823   for (k = 1; k <= i__1; ++k) {
1824     d__1 = 0., d__2 = temp * vmultc[k] + ratio * vmultd[k];
1825     vmultc[k] = max(d__1,d__2);
1826   }
1827   if (mcon == *m) {
1828     resmax = resold + ratio * (resmax - resold);
1829   }
1830
1831 /* If the full step is not acceptable then begin another iteration. */
1832 /* Otherwise switch to stage two or end the calculation. */
1833
1834   if (icon > 0) {
1835     goto L70;
1836   }
1837   if (step == stpful) {
1838     goto L500;
1839   }
1840 L480:
1841   mcon = *m + 1;
1842   icon = mcon;
1843   iact[mcon] = mcon;
1844   vmultc[mcon] = 0.;
1845   goto L60;
1846
1847 /* We employ any freedom that may be available to reduce the objective */
1848 /* function before returning a DX whose length is less than RHO. */
1849
1850 L490:
1851   if (mcon == *m) {
1852     goto L480;
1853   }
1854   *ifull = 0;
1855 L500:
1856   return NLOPT_SUCCESS;
1857 } /* trstlp */