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