The R Project SVN R

Rev

Rev 19233 | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 19233 Rev 21689
1
/*
1
/*
2
 *  R : A Computer Language for Statistical Data Analysis
2
 *  R : A Computer Language for Statistical Data Analysis
3
 *  Copyright (C) 1999-2002  the R Development Core Team
3
 *  Copyright (C) 1999-2002  the R Development Core Team
4
 *
4
 *
5
 *  This program is free software; you can redistribute it and/or modify
5
 *  This program is free software; you can redistribute it and/or modify
6
 *  it under the terms of the GNU General Public License as published by
6
 *  it under the terms of the GNU General Public License as published by
7
 *  the Free Software Foundation; either version 2 of the License, or
7
 *  the Free Software Foundation; either version 2 of the License, or
8
 *  (at your option) any later version.
8
 *  (at your option) any later version.
9
 *
9
 *
10
 *  This program is distributed in the hope that it will be useful,
10
 *  This program is distributed in the hope that it will be useful,
11
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 *  GNU General Public License for more details.
13
 *  GNU General Public License for more details.
14
 *
14
 *
15
 *  You should have received a copy of the GNU General Public License
15
 *  You should have received a copy of the GNU General Public License
16
 *  along with this program; if not, write to the Free Software
16
 *  along with this program; if not, write to the Free Software
17
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18
 */
18
 */
19
 
19
 
20
#include <Defn.h>
20
#include <Defn.h>
21
#include <R_ext/Random.h>	/* for the random number generation in
21
#include <R_ext/Random.h>	/* for the random number generation in
22
				   samin() */
22
				   samin() */
23
#include <R_ext/Applic.h>	/* setulb() */
23
#include <R_ext/Applic.h>	/* setulb() */
24
 
24
 
25
static SEXP getListElement(SEXP list, char *str)
25
static SEXP getListElement(SEXP list, char *str)
26
{
26
{
27
    SEXP elmt = R_NilValue, names = getAttrib(list, R_NamesSymbol);
27
    SEXP elmt = R_NilValue, names = getAttrib(list, R_NamesSymbol);
28
    int i;
28
    int i;
29
 
29
 
30
    for (i = 0; i < length(list); i++)
30
    for (i = 0; i < length(list); i++)
31
	if (strcmp(CHAR(STRING_ELT(names, i)), str) == 0) {
31
	if (strcmp(CHAR(STRING_ELT(names, i)), str) == 0) {
32
	    elmt = VECTOR_ELT(list, i);
32
	    elmt = VECTOR_ELT(list, i);
33
	    break;
33
	    break;
34
	}
34
	}
35
    return elmt;
35
    return elmt;
36
}
36
}
37
 
37
 
38
static double * vect(int n)
38
static double * vect(int n)
39
{
39
{
40
    return (double *)R_alloc(n, sizeof(double));
40
    return (double *)R_alloc(n, sizeof(double));
41
}
41
}
42
 
42
 
43
typedef struct opt_struct
43
typedef struct opt_struct
44
{
44
{
45
    SEXP R_fcall;    /* function */
45
    SEXP R_fcall;    /* function */
46
    SEXP R_gcall;    /* gradient */
46
    SEXP R_gcall;    /* gradient */
47
    SEXP R_env;      /* where to evaluate the calls */
47
    SEXP R_env;      /* where to evaluate the calls */
48
    double* ndeps;   /* tolerances for numerical derivatives */
48
    double* ndeps;   /* tolerances for numerical derivatives */
49
    double fnscale;  /* scaling for objective */
49
    double fnscale;  /* scaling for objective */
50
    double* parscale;/* scaling for parameters */
50
    double* parscale;/* scaling for parameters */
51
    int usebounds;
51
    int usebounds;
52
    double* lower, *upper;
52
    double* lower, *upper;
53
} opt_struct, *OptStruct;
53
} opt_struct, *OptStruct;
54
 
54
 
55
 
55
 
56
 
56
 
57
static double fminfn(int n, double *p, void *ex)
57
static double fminfn(int n, double *p, void *ex)
58
{
58
{
59
    SEXP s, x;
59
    SEXP s, x;
60
    int i;
60
    int i;
61
    double val;
61
    double val;
62
    OptStruct OS = (OptStruct) ex;
62
    OptStruct OS = (OptStruct) ex;
63
    PROTECT_INDEX ipx;
63
    PROTECT_INDEX ipx;
64
 
64
 
65
    PROTECT(x = allocVector(REALSXP, n));
65
    PROTECT(x = allocVector(REALSXP, n));
66
    for (i = 0; i < n; i++) {
66
    for (i = 0; i < n; i++) {
67
	if (!R_FINITE(p[i])) error("non-finite value supplied by optim");
67
	if (!R_FINITE(p[i])) error("non-finite value supplied by optim");
68
	REAL(x)[i] = p[i] * (OS->parscale[i]);
68
	REAL(x)[i] = p[i] * (OS->parscale[i]);
69
    }
69
    }
70
    SETCADR(OS->R_fcall, x);
70
    SETCADR(OS->R_fcall, x);
71
    PROTECT_WITH_INDEX(s = eval(OS->R_fcall, OS->R_env), &ipx);
71
    PROTECT_WITH_INDEX(s = eval(OS->R_fcall, OS->R_env), &ipx);
72
    REPROTECT(s = coerceVector(s, REALSXP), ipx);
72
    REPROTECT(s = coerceVector(s, REALSXP), ipx);
73
    val = REAL(s)[0]/(OS->fnscale);
73
    val = REAL(s)[0]/(OS->fnscale);
74
    UNPROTECT(2);
74
    UNPROTECT(2);
75
    return val;
75
    return val;
76
}
76
}
77
 
77
 
78
static void fmingr(int n, double *p, double *df, void *ex)
78
static void fmingr(int n, double *p, double *df, void *ex)
79
{
79
{
80
    SEXP s, x;
80
    SEXP s, x;
81
    int i;
81
    int i;
82
    double val1, val2, eps, epsused, tmp;
82
    double val1, val2, eps, epsused, tmp;
83
    OptStruct OS = (OptStruct) ex;
83
    OptStruct OS = (OptStruct) ex;
84
    PROTECT_INDEX ipx;
84
    PROTECT_INDEX ipx;
85
 
85
 
86
    if (!isNull(OS->R_gcall)) { /* analytical derivatives */
86
    if (!isNull(OS->R_gcall)) { /* analytical derivatives */
87
	PROTECT(x = allocVector(REALSXP, n));
87
	PROTECT(x = allocVector(REALSXP, n));
88
	for (i = 0; i < n; i++) {
88
	for (i = 0; i < n; i++) {
89
	    if (!R_FINITE(p[i])) error("non-finite value supplied by optim");
89
	    if (!R_FINITE(p[i])) error("non-finite value supplied by optim");
90
	    REAL(x)[i] = p[i] * (OS->parscale[i]);
90
	    REAL(x)[i] = p[i] * (OS->parscale[i]);
91
	}
91
	}
92
	SETCADR(OS->R_gcall, x);
92
	SETCADR(OS->R_gcall, x);
93
	PROTECT_WITH_INDEX(s = eval(OS->R_gcall, OS->R_env), &ipx);
93
	PROTECT_WITH_INDEX(s = eval(OS->R_gcall, OS->R_env), &ipx);
94
	REPROTECT(s = coerceVector(s, REALSXP), ipx);
94
	REPROTECT(s = coerceVector(s, REALSXP), ipx);
95
	if(LENGTH(s) != n)
95
	if(LENGTH(s) != n)
96
	    error("gradient in optim evaluated to length %d not %d",
96
	    error("gradient in optim evaluated to length %d not %d",
97
		  LENGTH(s), n);
97
		  LENGTH(s), n);
98
	for (i = 0; i < n; i++)
98
	for (i = 0; i < n; i++)
99
	    df[i] = REAL(s)[i] * (OS->parscale[i])/(OS->fnscale);
99
	    df[i] = REAL(s)[i] * (OS->parscale[i])/(OS->fnscale);
100
	UNPROTECT(2);
100
	UNPROTECT(2);
101
    } else { /* numerical derivatives */
101
    } else { /* numerical derivatives */
102
	PROTECT(x = allocVector(REALSXP, n));
102
	PROTECT(x = allocVector(REALSXP, n));
103
	for (i = 0; i < n; i++) REAL(x)[i] = p[i] * (OS->parscale[i]);
103
	for (i = 0; i < n; i++) REAL(x)[i] = p[i] * (OS->parscale[i]);
104
	SETCADR(OS->R_fcall, x);
104
	SETCADR(OS->R_fcall, x);
105
	if(OS->usebounds == 0) {
105
	if(OS->usebounds == 0) {
106
	    for (i = 0; i < n; i++) {
106
	    for (i = 0; i < n; i++) {
107
		eps = OS->ndeps[i];
107
		eps = OS->ndeps[i];
108
		REAL(x)[i] = (p[i] + eps) * (OS->parscale[i]);
108
		REAL(x)[i] = (p[i] + eps) * (OS->parscale[i]);
109
		SETCADR(OS->R_fcall, x);
109
		SETCADR(OS->R_fcall, x);
110
		PROTECT_WITH_INDEX(s = eval(OS->R_fcall, OS->R_env), &ipx);
110
		PROTECT_WITH_INDEX(s = eval(OS->R_fcall, OS->R_env), &ipx);
111
		REPROTECT(s = coerceVector(s, REALSXP), ipx);
111
		REPROTECT(s = coerceVector(s, REALSXP), ipx);
112
		val1 = REAL(s)[0]/(OS->fnscale);
112
		val1 = REAL(s)[0]/(OS->fnscale);
113
		REAL(x)[i] = (p[i] - eps) * (OS->parscale[i]);
113
		REAL(x)[i] = (p[i] - eps) * (OS->parscale[i]);
114
		SETCADR(OS->R_fcall, x);
114
		SETCADR(OS->R_fcall, x);
115
		REPROTECT(s = eval(OS->R_fcall, OS->R_env), ipx);
115
		REPROTECT(s = eval(OS->R_fcall, OS->R_env), ipx);
116
		REPROTECT(s = coerceVector(s, REALSXP), ipx);
116
		REPROTECT(s = coerceVector(s, REALSXP), ipx);
117
		val2 = REAL(s)[0]/(OS->fnscale);
117
		val2 = REAL(s)[0]/(OS->fnscale);
118
		df[i] = (val1 - val2)/(2 * eps);
118
		df[i] = (val1 - val2)/(2 * eps);
119
#define DO_df_x 							\
119
#define DO_df_x 							\
120
		if(!R_FINITE(df[i])) 					\
120
		if(!R_FINITE(df[i])) 					\
121
		    error("non-finite finite-difference value [%d]", i);\
121
		    error("non-finite finite-difference value [%d]", i);\
122
		REAL(x)[i] = p[i] * (OS->parscale[i])
122
		REAL(x)[i] = p[i] * (OS->parscale[i])
123
 
123
 
124
		DO_df_x;
124
		DO_df_x;
125
		UNPROTECT(1);
125
		UNPROTECT(1);
126
	    }
126
	    }
127
	} else { /* usebounds */
127
	} else { /* usebounds */
128
	    for (i = 0; i < n; i++) {
128
	    for (i = 0; i < n; i++) {
129
		epsused = eps = OS->ndeps[i];
129
		epsused = eps = OS->ndeps[i];
130
		tmp = p[i] + eps;
130
		tmp = p[i] + eps;
131
		if (tmp > OS->upper[i]) {
131
		if (tmp > OS->upper[i]) {
132
		    tmp = OS->upper[i];
132
		    tmp = OS->upper[i];
133
		    epsused = tmp - p[i] ;
133
		    epsused = tmp - p[i] ;
134
		}
134
		}
135
		REAL(x)[i] = tmp * (OS->parscale[i]);
135
		REAL(x)[i] = tmp * (OS->parscale[i]);
136
		SETCADR(OS->R_fcall, x);
136
		SETCADR(OS->R_fcall, x);
137
		PROTECT_WITH_INDEX(s = eval(OS->R_fcall, OS->R_env), &ipx);
137
		PROTECT_WITH_INDEX(s = eval(OS->R_fcall, OS->R_env), &ipx);
138
		REPROTECT(s = coerceVector(s, REALSXP), ipx);
138
		REPROTECT(s = coerceVector(s, REALSXP), ipx);
139
		val1 = REAL(s)[0]/(OS->fnscale);
139
		val1 = REAL(s)[0]/(OS->fnscale);
140
		tmp = p[i] - eps;
140
		tmp = p[i] - eps;
141
		if (tmp < OS->lower[i]) {
141
		if (tmp < OS->lower[i]) {
142
		    tmp = OS->lower[i];
142
		    tmp = OS->lower[i];
143
		    eps = p[i] - tmp;
143
		    eps = p[i] - tmp;
144
		}
144
		}
145
		REAL(x)[i] = tmp * (OS->parscale[i]);
145
		REAL(x)[i] = tmp * (OS->parscale[i]);
146
		SETCADR(OS->R_fcall, x);
146
		SETCADR(OS->R_fcall, x);
147
		REPROTECT(s = eval(OS->R_fcall, OS->R_env), ipx);
147
		REPROTECT(s = eval(OS->R_fcall, OS->R_env), ipx);
148
		REPROTECT(s = coerceVector(s, REALSXP), ipx);
148
		REPROTECT(s = coerceVector(s, REALSXP), ipx);
149
		val2 = REAL(s)[0]/(OS->fnscale);
149
		val2 = REAL(s)[0]/(OS->fnscale);
150
		df[i] = (val1 - val2)/(epsused + eps);
150
		df[i] = (val1 - val2)/(epsused + eps);
151
 
151
 
152
		DO_df_x;
152
		DO_df_x;
153
		UNPROTECT(1);
153
		UNPROTECT(1);
154
	    }
154
	    }
155
	}
155
	}
156
	UNPROTECT(1); /* x */
156
	UNPROTECT(1); /* x */
157
    }
157
    }
158
}
158
}
159
 
159
 
-
 
160
static void genptry(int n, double *p, double *ptry, double scale, void *ex)
-
 
161
{    
-
 
162
    SEXP s, x;
-
 
163
    int i;
-
 
164
    OptStruct OS = (OptStruct) ex;
-
 
165
    PROTECT_INDEX ipx;
-
 
166
 
-
 
167
    if (!isNull(OS->R_gcall)) {  
-
 
168
	/* user defined generation of candidate point */
-
 
169
      	PROTECT(x = allocVector(REALSXP, n));
-
 
170
	for (i = 0; i < n; i++) {
-
 
171
	    if (!R_FINITE(p[i])) error("non-finite value supplied by optim");
-
 
172
	    REAL(x)[i] = p[i] * (OS->parscale[i]);
-
 
173
	}
-
 
174
	SETCADR(OS->R_gcall, x);
-
 
175
	PROTECT_WITH_INDEX(s = eval(OS->R_gcall, OS->R_env), &ipx);
-
 
176
	REPROTECT(s = coerceVector(s, REALSXP), ipx);
-
 
177
	if(LENGTH(s) != n)
-
 
178
	    error("candidate point in optim evaluated to length %d not %d",
-
 
179
		  LENGTH(s), n);
-
 
180
	for (i = 0; i < n; i++)
-
 
181
	    ptry[i] = REAL(s)[i] / (OS->parscale[i]);
-
 
182
	UNPROTECT(2);
-
 
183
    } 
-
 
184
    else {  /* default Gaussian Markov kernel */
-
 
185
        for (i = 0; i < n; i++)
-
 
186
            ptry[i] = p[i] + scale * norm_rand();  /* new candidate point */
-
 
187
    }
-
 
188
}
-
 
189
 
160
/* par fn gr method options */
190
/* par fn gr method options */
161
SEXP do_optim(SEXP call, SEXP op, SEXP args, SEXP rho)
191
SEXP do_optim(SEXP call, SEXP op, SEXP args, SEXP rho)
162
{
192
{
163
    SEXP par, fn, gr, method, options, tmp, slower, supper;
193
    SEXP par, fn, gr, method, options, tmp, slower, supper;
164
    SEXP res, value, counts, conv;
194
    SEXP res, value, counts, conv;
165
    int i, npar=0, *mask, trace, maxit, fncount, grcount, nREPORT, tmax;
195
    int i, npar=0, *mask, trace, maxit, fncount, grcount, nREPORT, tmax;
166
    int ifail = 0;
196
    int ifail = 0;
167
    double *dpar, *opar, val, abstol, reltol, temp;
197
    double *dpar, *opar, val, abstol, reltol, temp;
168
    char *tn;
198
    char *tn;
169
    OptStruct OS;
199
    OptStruct OS;
170
    char *vmax;
200
    char *vmax;
171
 
201
 
172
    checkArity(op, args);
202
    checkArity(op, args);
173
    vmax = vmaxget();
203
    vmax = vmaxget();
174
    OS = (OptStruct) R_alloc(1, sizeof(opt_struct));
204
    OS = (OptStruct) R_alloc(1, sizeof(opt_struct));
175
    OS->usebounds = 0;
205
    OS->usebounds = 0;
176
    OS->R_env = rho;
206
    OS->R_env = rho;
177
    par = CAR(args);
207
    par = CAR(args);
178
    args = CDR(args); fn = CAR(args);
208
    args = CDR(args); fn = CAR(args);
179
    if (!isFunction(fn)) errorcall(call, "fn is not a function");
209
    if (!isFunction(fn)) errorcall(call, "fn is not a function");
180
    args = CDR(args); gr = CAR(args);
210
    args = CDR(args); gr = CAR(args);
181
    args = CDR(args); method = CAR(args);
211
    args = CDR(args); method = CAR(args);
182
    if (!isString(method)|| LENGTH(method) != 1)
212
    if (!isString(method)|| LENGTH(method) != 1)
183
	errorcall(call, "invalid method argument");
213
	errorcall(call, "invalid method argument");
184
    tn = CHAR(STRING_ELT(method, 0));
214
    tn = CHAR(STRING_ELT(method, 0));
185
    args = CDR(args); options = CAR(args);
215
    args = CDR(args); options = CAR(args);
186
    PROTECT(OS->R_fcall = lang2(fn, R_NilValue));
216
    PROTECT(OS->R_fcall = lang2(fn, R_NilValue));
187
    PROTECT(par = coerceVector(duplicate(par), REALSXP));
217
    PROTECT(par = coerceVector(duplicate(par), REALSXP));
188
    npar = LENGTH(par);
218
    npar = LENGTH(par);
189
    dpar = vect(npar);
219
    dpar = vect(npar);
190
    opar = vect(npar);
220
    opar = vect(npar);
191
    trace = asInteger(getListElement(options, "trace"));
221
    trace = asInteger(getListElement(options, "trace"));
192
    OS->fnscale = asReal(getListElement(options, "fnscale"));
222
    OS->fnscale = asReal(getListElement(options, "fnscale"));
193
    tmp = getListElement(options, "parscale");
223
    tmp = getListElement(options, "parscale");
194
    if (LENGTH(tmp) != npar)
224
    if (LENGTH(tmp) != npar)
195
	errorcall(call, "parscale is of the wrong length");
225
	errorcall(call, "parscale is of the wrong length");
196
    PROTECT(tmp = coerceVector(tmp, REALSXP));
226
    PROTECT(tmp = coerceVector(tmp, REALSXP));
197
    OS->parscale = vect(npar);
227
    OS->parscale = vect(npar);
198
    for (i = 0; i < npar; i++) OS->parscale[i] = REAL(tmp)[i];
228
    for (i = 0; i < npar; i++) OS->parscale[i] = REAL(tmp)[i];
199
    UNPROTECT(1);
229
    UNPROTECT(1);
200
    for (i = 0; i < npar; i++)
230
    for (i = 0; i < npar; i++)
201
	dpar[i] = REAL(par)[i] / (OS->parscale[i]);
231
	dpar[i] = REAL(par)[i] / (OS->parscale[i]);
202
    PROTECT(res = allocVector(VECSXP, 5));
232
    PROTECT(res = allocVector(VECSXP, 5));
203
    PROTECT(value = allocVector(REALSXP, 1));
233
    PROTECT(value = allocVector(REALSXP, 1));
204
    PROTECT(counts = allocVector(INTSXP, 2));
234
    PROTECT(counts = allocVector(INTSXP, 2));
205
    PROTECT(conv = allocVector(INTSXP, 1));
235
    PROTECT(conv = allocVector(INTSXP, 1));
206
    abstol = asReal(getListElement(options, "abstol"));
236
    abstol = asReal(getListElement(options, "abstol"));
207
    reltol = asReal(getListElement(options, "reltol"));
237
    reltol = asReal(getListElement(options, "reltol"));
208
    maxit = asInteger(getListElement(options, "maxit"));
238
    maxit = asInteger(getListElement(options, "maxit"));
209
    if (maxit == NA_INTEGER) error("maxit is not an integer");
239
    if (maxit == NA_INTEGER) error("maxit is not an integer");
210
 
240
 
211
    if (strcmp(tn, "Nelder-Mead") == 0) {
241
    if (strcmp(tn, "Nelder-Mead") == 0) {
212
	double alpha, beta, gamm;
242
	double alpha, beta, gamm;
213
 
243
 
214
	alpha = asReal(getListElement(options, "alpha"));
244
	alpha = asReal(getListElement(options, "alpha"));
215
	beta = asReal(getListElement(options, "beta"));
245
	beta = asReal(getListElement(options, "beta"));
216
	gamm = asReal(getListElement(options, "gamma"));
246
	gamm = asReal(getListElement(options, "gamma"));
217
	nmmin(npar, dpar, opar, &val, fminfn, &ifail, abstol, reltol,
247
	nmmin(npar, dpar, opar, &val, fminfn, &ifail, abstol, reltol,
218
	      (void *)OS, alpha, beta, gamm, trace, &fncount, maxit);
248
	      (void *)OS, alpha, beta, gamm, trace, &fncount, maxit);
219
	for (i = 0; i < npar; i++)
249
	for (i = 0; i < npar; i++)
220
	    REAL(par)[i] = opar[i] * (OS->parscale[i]);
250
	    REAL(par)[i] = opar[i] * (OS->parscale[i]);
221
	grcount = NA_INTEGER;
251
	grcount = NA_INTEGER;
222
 
252
 
223
    }
253
    }
224
    else if (strcmp(tn, "SANN") == 0) {
254
    else if (strcmp(tn, "SANN") == 0) {	
225
      tmax = asInteger(getListElement(options, "tmax"));
255
        tmax = asInteger(getListElement(options, "tmax"));
226
      temp = asReal(getListElement(options, "temp"));
256
        temp = asReal(getListElement(options, "temp"));
227
      if (tmax == NA_INTEGER) error("tmax is not an integer");
257
        if (tmax == NA_INTEGER) error("tmax is not an integer");
-
 
258
        if (!isNull(gr)) {
-
 
259
            if (!isFunction(gr)) error("gr is not a function");
-
 
260
                PROTECT(OS->R_gcall = lang2(gr, R_NilValue));
-
 
261
        } else {
-
 
262
	    PROTECT(OS->R_gcall = R_NilValue); /* for balance */
-
 
263
        }
228
      samin (npar, dpar, &val, fminfn, maxit, tmax, temp, trace, (void *)OS);
264
        samin (npar, dpar, &val, fminfn, maxit, tmax, temp, trace, (void *)OS);
229
      for (i = 0; i < npar; i++)
265
        for (i = 0; i < npar; i++)
230
	  REAL(par)[i] = dpar[i] * (OS->parscale[i]);
266
            REAL(par)[i] = dpar[i] * (OS->parscale[i]);
231
      fncount = maxit;
267
        fncount = maxit;
232
      grcount = NA_INTEGER;
268
        grcount = NA_INTEGER;
-
 
269
        UNPROTECT(1);  /* OS->R_gcall */
233
 
270
 
234
    } else if (strcmp(tn, "BFGS") == 0) {
271
    } else if (strcmp(tn, "BFGS") == 0) {
235
	SEXP ndeps;
272
	SEXP ndeps;
236
 
273
 
237
	nREPORT = asInteger(getListElement(options, "REPORT"));
274
	nREPORT = asInteger(getListElement(options, "REPORT"));
238
	if (!isNull(gr)) {
275
	if (!isNull(gr)) {
239
	    if (!isFunction(gr)) error("gr is not a function");
276
	    if (!isFunction(gr)) error("gr is not a function");
240
	    PROTECT(OS->R_gcall = lang2(gr, R_NilValue));
277
	    PROTECT(OS->R_gcall = lang2(gr, R_NilValue));
241
	} else {
278
	} else {
242
	    PROTECT(OS->R_gcall = R_NilValue); /* for balance */
279
	    PROTECT(OS->R_gcall = R_NilValue); /* for balance */
243
	    ndeps = getListElement(options, "ndeps");
280
	    ndeps = getListElement(options, "ndeps");
244
	    if (LENGTH(ndeps) != npar) error("ndeps is of the wrong length");
281
	    if (LENGTH(ndeps) != npar) error("ndeps is of the wrong length");
245
	    OS->ndeps = vect(npar);
282
	    OS->ndeps = vect(npar);
246
	    PROTECT(ndeps = coerceVector(ndeps, REALSXP));
283
	    PROTECT(ndeps = coerceVector(ndeps, REALSXP));
247
	    for (i = 0; i < npar; i++) OS->ndeps[i] = REAL(ndeps)[i];
284
	    for (i = 0; i < npar; i++) OS->ndeps[i] = REAL(ndeps)[i];
248
	    UNPROTECT(1);
285
	    UNPROTECT(1);
249
	}
286
	}
250
	mask = (int *) R_alloc(npar, sizeof(int));
287
	mask = (int *) R_alloc(npar, sizeof(int));
251
	for (i = 0; i < npar; i++) mask[i] = 1;
288
	for (i = 0; i < npar; i++) mask[i] = 1;
252
	vmmin(npar, dpar, &val, fminfn, fmingr, maxit, trace, mask, abstol,
289
	vmmin(npar, dpar, &val, fminfn, fmingr, maxit, trace, mask, abstol,
253
	      reltol, nREPORT, (void *)OS, &fncount, &grcount, &ifail);
290
	      reltol, nREPORT, (void *)OS, &fncount, &grcount, &ifail);
254
	for (i = 0; i < npar; i++)
291
	for (i = 0; i < npar; i++)
255
	    REAL(par)[i] = dpar[i] * (OS->parscale[i]);
292
	    REAL(par)[i] = dpar[i] * (OS->parscale[i]);
256
	UNPROTECT(1); /* OS->R_gcall */
293
	UNPROTECT(1); /* OS->R_gcall */
257
    } else if (strcmp(tn, "CG") == 0) {
294
    } else if (strcmp(tn, "CG") == 0) {
258
	int type;
295
	int type;
259
	SEXP ndeps;
296
	SEXP ndeps;
260
 
297
 
261
	type = asInteger(getListElement(options, "type"));
298
	type = asInteger(getListElement(options, "type"));
262
	if (!isNull(gr)) {
299
	if (!isNull(gr)) {
263
	    if (!isFunction(gr)) error("gr is not a function");
300
	    if (!isFunction(gr)) error("gr is not a function");
264
	    PROTECT(OS->R_gcall = lang2(gr, R_NilValue));
301
	    PROTECT(OS->R_gcall = lang2(gr, R_NilValue));
265
	} else {
302
	} else {
266
	    PROTECT(OS->R_gcall = R_NilValue); /* for balance */
303
	    PROTECT(OS->R_gcall = R_NilValue); /* for balance */
267
	    ndeps = getListElement(options, "ndeps");
304
	    ndeps = getListElement(options, "ndeps");
268
	    if (LENGTH(ndeps) != npar) error("ndeps is of the wrong length");
305
	    if (LENGTH(ndeps) != npar) error("ndeps is of the wrong length");
269
	    OS->ndeps = vect(npar);
306
	    OS->ndeps = vect(npar);
270
	    PROTECT(ndeps = coerceVector(ndeps, REALSXP));
307
	    PROTECT(ndeps = coerceVector(ndeps, REALSXP));
271
	    for (i = 0; i < npar; i++) OS->ndeps[i] = REAL(ndeps)[i];
308
	    for (i = 0; i < npar; i++) OS->ndeps[i] = REAL(ndeps)[i];
272
	    UNPROTECT(1);
309
	    UNPROTECT(1);
273
	}
310
	}
274
	cgmin(npar, dpar, opar, &val, fminfn, fmingr, &ifail, abstol,
311
	cgmin(npar, dpar, opar, &val, fminfn, fmingr, &ifail, abstol,
275
	      reltol, (void *)OS, type, trace, &fncount, &grcount, maxit);
312
	      reltol, (void *)OS, type, trace, &fncount, &grcount, maxit);
276
	for (i = 0; i < npar; i++)
313
	for (i = 0; i < npar; i++)
277
	    REAL(par)[i] = opar[i] * (OS->parscale[i]);
314
	    REAL(par)[i] = opar[i] * (OS->parscale[i]);
278
	UNPROTECT(1); /* OS->R_gcall */
315
	UNPROTECT(1); /* OS->R_gcall */
279
 
316
 
280
    } else if (strcmp(tn, "L-BFGS-B") == 0) {
317
    } else if (strcmp(tn, "L-BFGS-B") == 0) {
281
	SEXP ndeps, smsg;
318
	SEXP ndeps, smsg;
282
	double *lower = vect(npar), *upper = vect(npar);
319
	double *lower = vect(npar), *upper = vect(npar);
283
	int lmm, *nbd = (int *) R_alloc(npar, sizeof(int));
320
	int lmm, *nbd = (int *) R_alloc(npar, sizeof(int));
284
	double factr, pgtol;
321
	double factr, pgtol;
285
	char msg[60];
322
	char msg[60];
286
 
323
 
287
	nREPORT = asInteger(getListElement(options, "REPORT"));
324
	nREPORT = asInteger(getListElement(options, "REPORT"));
288
	factr = asReal(getListElement(options, "factr"));
325
	factr = asReal(getListElement(options, "factr"));
289
	pgtol = asReal(getListElement(options, "pgtol"));
326
	pgtol = asReal(getListElement(options, "pgtol"));
290
	lmm = asInteger(getListElement(options, "lmm"));
327
	lmm = asInteger(getListElement(options, "lmm"));
291
	if (!isNull(gr)) {
328
	if (!isNull(gr)) {
292
	    if (!isFunction(gr)) error("gr is not a function");
329
	    if (!isFunction(gr)) error("gr is not a function");
293
	    PROTECT(OS->R_gcall = lang2(gr, R_NilValue));
330
	    PROTECT(OS->R_gcall = lang2(gr, R_NilValue));
294
	} else {
331
	} else {
295
	    PROTECT(OS->R_gcall = R_NilValue); /* for balance */
332
	    PROTECT(OS->R_gcall = R_NilValue); /* for balance */
296
	    ndeps = getListElement(options, "ndeps");
333
	    ndeps = getListElement(options, "ndeps");
297
	    if (LENGTH(ndeps) != npar) error("ndeps is of the wrong length");
334
	    if (LENGTH(ndeps) != npar) error("ndeps is of the wrong length");
298
	    OS->ndeps = vect(npar);
335
	    OS->ndeps = vect(npar);
299
	    PROTECT(ndeps = coerceVector(ndeps, REALSXP));
336
	    PROTECT(ndeps = coerceVector(ndeps, REALSXP));
300
	    for (i = 0; i < npar; i++) OS->ndeps[i] = REAL(ndeps)[i];
337
	    for (i = 0; i < npar; i++) OS->ndeps[i] = REAL(ndeps)[i];
301
	    UNPROTECT(1);
338
	    UNPROTECT(1);
302
	}
339
	}
303
	args = CDR(args); slower = CAR(args); /* coerce in calling code */
340
	args = CDR(args); slower = CAR(args); /* coerce in calling code */
304
	args = CDR(args); supper = CAR(args);
341
	args = CDR(args); supper = CAR(args);
305
	for (i = 0; i < npar; i++) {
342
	for (i = 0; i < npar; i++) {
306
	    lower[i] = REAL(slower)[i] / (OS->parscale[i]);
343
	    lower[i] = REAL(slower)[i] / (OS->parscale[i]);
307
	    upper[i] = REAL(supper)[i] / (OS->parscale[i]);
344
	    upper[i] = REAL(supper)[i] / (OS->parscale[i]);
308
	    if (!R_FINITE(lower[i])) {
345
	    if (!R_FINITE(lower[i])) {
309
		if (!R_FINITE(upper[i])) nbd[i] = 0; else nbd[i] = 3;
346
		if (!R_FINITE(upper[i])) nbd[i] = 0; else nbd[i] = 3;
310
	    } else {
347
	    } else {
311
		if (!R_FINITE(upper[i])) nbd[i] = 1; else nbd[i] = 2;
348
		if (!R_FINITE(upper[i])) nbd[i] = 1; else nbd[i] = 2;
312
	    }
349
	    }
313
	}
350
	}
314
	OS->usebounds = 1;
351
	OS->usebounds = 1;
315
	OS->lower = lower;
352
	OS->lower = lower;
316
	OS->upper = upper;
353
	OS->upper = upper;
317
	lbfgsb(npar, lmm, dpar, lower, upper, nbd, &val, fminfn, fmingr,
354
	lbfgsb(npar, lmm, dpar, lower, upper, nbd, &val, fminfn, fmingr,
318
	       &ifail, (void *)OS, factr, pgtol, &fncount, &grcount,
355
	       &ifail, (void *)OS, factr, pgtol, &fncount, &grcount,
319
	       maxit, msg, trace, nREPORT);
356
	       maxit, msg, trace, nREPORT);
320
	for (i = 0; i < npar; i++)
357
	for (i = 0; i < npar; i++)
321
	    REAL(par)[i] = dpar[i] * (OS->parscale[i]);
358
	    REAL(par)[i] = dpar[i] * (OS->parscale[i]);
322
	UNPROTECT(1); /* OS->R_gcall */
359
	UNPROTECT(1); /* OS->R_gcall */
323
	PROTECT(smsg = allocVector(STRSXP, 1));
360
	PROTECT(smsg = allocVector(STRSXP, 1));
324
	SET_STRING_ELT(smsg, 0, mkChar(msg));
361
	SET_STRING_ELT(smsg, 0, mkChar(msg));
325
	SET_VECTOR_ELT(res, 4, smsg);
362
	SET_VECTOR_ELT(res, 4, smsg);
326
	UNPROTECT(1);
363
	UNPROTECT(1);
327
    } else
364
    } else
328
	errorcall(call, "unknown method");
365
	errorcall(call, "unknown method");
329
 
366
 
330
    REAL(value)[0] = val * (OS->fnscale);
367
    REAL(value)[0] = val * (OS->fnscale);
331
    SET_VECTOR_ELT(res, 0, par); SET_VECTOR_ELT(res, 1, value);
368
    SET_VECTOR_ELT(res, 0, par); SET_VECTOR_ELT(res, 1, value);
332
    INTEGER(counts)[0] = fncount; INTEGER(counts)[1] = grcount;
369
    INTEGER(counts)[0] = fncount; INTEGER(counts)[1] = grcount;
333
    SET_VECTOR_ELT(res, 2, counts);
370
    SET_VECTOR_ELT(res, 2, counts);
334
    INTEGER(conv)[0] = ifail;
371
    INTEGER(conv)[0] = ifail;
335
    SET_VECTOR_ELT(res, 3, conv);
372
    SET_VECTOR_ELT(res, 3, conv);
336
    vmaxset(vmax);
373
    vmaxset(vmax);
337
    UNPROTECT(6);
374
    UNPROTECT(6);
338
    return res;
375
    return res;
339
}
376
}
340
 
377
 
341
/* par fn gr options */
378
/* par fn gr options */
342
SEXP do_optimhess(SEXP call, SEXP op, SEXP args, SEXP rho)
379
SEXP do_optimhess(SEXP call, SEXP op, SEXP args, SEXP rho)
343
{
380
{
344
    SEXP par, fn, gr, options, tmp, ndeps, ans;
381
    SEXP par, fn, gr, options, tmp, ndeps, ans;
345
    OptStruct OS;
382
    OptStruct OS;
346
    int npar, i , j;
383
    int npar, i , j;
347
    double *dpar, *df1, *df2, eps;
384
    double *dpar, *df1, *df2, eps;
348
    char *vmax;
385
    char *vmax;
349
 
386
 
350
    checkArity(op, args);
387
    checkArity(op, args);
351
    vmax = vmaxget();
388
    vmax = vmaxget();
352
    OS = (OptStruct) R_alloc(1, sizeof(opt_struct));
389
    OS = (OptStruct) R_alloc(1, sizeof(opt_struct));
353
    OS->usebounds = 0;
390
    OS->usebounds = 0;
354
    OS->R_env = rho;
391
    OS->R_env = rho;
355
    par = CAR(args);
392
    par = CAR(args);
356
    npar = LENGTH(par);
393
    npar = LENGTH(par);
357
    args = CDR(args); fn = CAR(args);
394
    args = CDR(args); fn = CAR(args);
358
    if (!isFunction(fn)) errorcall(call, "fn is not a function");
395
    if (!isFunction(fn)) errorcall(call, "fn is not a function");
359
    args = CDR(args); gr = CAR(args);
396
    args = CDR(args); gr = CAR(args);
360
    args = CDR(args); options = CAR(args);
397
    args = CDR(args); options = CAR(args);
361
    OS->fnscale = asReal(getListElement(options, "fnscale"));
398
    OS->fnscale = asReal(getListElement(options, "fnscale"));
362
    tmp = getListElement(options, "parscale");
399
    tmp = getListElement(options, "parscale");
363
    if (LENGTH(tmp) != npar)
400
    if (LENGTH(tmp) != npar)
364
	errorcall(call, "parscale is of the wrong length");
401
	errorcall(call, "parscale is of the wrong length");
365
    PROTECT(tmp = coerceVector(tmp, REALSXP));
402
    PROTECT(tmp = coerceVector(tmp, REALSXP));
366
    OS->parscale = vect(npar);
403
    OS->parscale = vect(npar);
367
    for (i = 0; i < npar; i++) OS->parscale[i] = REAL(tmp)[i];
404
    for (i = 0; i < npar; i++) OS->parscale[i] = REAL(tmp)[i];
368
    UNPROTECT(1);
405
    UNPROTECT(1);
369
    PROTECT(OS->R_fcall = lang2(fn, R_NilValue));
406
    PROTECT(OS->R_fcall = lang2(fn, R_NilValue));
370
    PROTECT(par = coerceVector(par, REALSXP));
407
    PROTECT(par = coerceVector(par, REALSXP));
371
    if (!isNull(gr)) {
408
    if (!isNull(gr)) {
372
	if (!isFunction(gr)) error("gr is not a function");
409
	if (!isFunction(gr)) error("gr is not a function");
373
	PROTECT(OS->R_gcall = lang2(gr, R_NilValue));
410
	PROTECT(OS->R_gcall = lang2(gr, R_NilValue));
374
    } else {
411
    } else {
375
	PROTECT(OS->R_gcall = R_NilValue); /* for balance */
412
	PROTECT(OS->R_gcall = R_NilValue); /* for balance */
376
    }
413
    }
377
    ndeps = getListElement(options, "ndeps");
414
    ndeps = getListElement(options, "ndeps");
378
    if (LENGTH(ndeps) != npar) error("ndeps is of the wrong length");
415
    if (LENGTH(ndeps) != npar) error("ndeps is of the wrong length");
379
    OS->ndeps = vect(npar);
416
    OS->ndeps = vect(npar);
380
    PROTECT(ndeps = coerceVector(ndeps, REALSXP));
417
    PROTECT(ndeps = coerceVector(ndeps, REALSXP));
381
    for (i = 0; i < npar; i++) OS->ndeps[i] = REAL(ndeps)[i];
418
    for (i = 0; i < npar; i++) OS->ndeps[i] = REAL(ndeps)[i];
382
    UNPROTECT(1);
419
    UNPROTECT(1);
383
    PROTECT(ans = allocMatrix(REALSXP, npar, npar));
420
    PROTECT(ans = allocMatrix(REALSXP, npar, npar));
384
    dpar = vect(npar);
421
    dpar = vect(npar);
385
    for (i = 0; i < npar; i++)
422
    for (i = 0; i < npar; i++)
386
	dpar[i] = REAL(par)[i] / (OS->parscale[i]);
423
	dpar[i] = REAL(par)[i] / (OS->parscale[i]);
387
    df1 = vect(npar);
424
    df1 = vect(npar);
388
    df2 = vect(npar);
425
    df2 = vect(npar);
389
    for (i = 0; i < npar; i++) {
426
    for (i = 0; i < npar; i++) {
390
	eps = OS->ndeps[i]/(OS->parscale[i]);
427
	eps = OS->ndeps[i]/(OS->parscale[i]);
391
	dpar[i] = dpar[i] + eps;
428
	dpar[i] = dpar[i] + eps;
392
	fmingr(npar, dpar, df1, (void *)OS);
429
	fmingr(npar, dpar, df1, (void *)OS);
393
	dpar[i] = dpar[i] - 2 * eps;
430
	dpar[i] = dpar[i] - 2 * eps;
394
	fmingr(npar, dpar, df2, (void *)OS);
431
	fmingr(npar, dpar, df2, (void *)OS);
395
	for (j = 0; j < npar; j++)
432
	for (j = 0; j < npar; j++)
396
	    REAL(ans)[i * npar + j] = (OS->fnscale) * (df1[j] - df2[j])/
433
	    REAL(ans)[i * npar + j] = (OS->fnscale) * (df1[j] - df2[j])/
397
		(2 * eps * (OS->parscale[i]) * (OS->parscale[j]));
434
		(2 * eps * (OS->parscale[i]) * (OS->parscale[j]));
398
	dpar[i] = dpar[i] + eps;
435
	dpar[i] = dpar[i] + eps;
399
    }
436
    }
400
    vmaxset(vmax);
437
    vmaxset(vmax);
401
    UNPROTECT(4);
438
    UNPROTECT(4);
402
    return ans;
439
    return ans;
403
}
440
}
404
 
441
 
405
 
442
 
406
static double ** matrix(int nrh, int nch)
443
static double ** matrix(int nrh, int nch)
407
{
444
{
408
    int   i;
445
    int   i;
409
    double **m;
446
    double **m;
410
 
447
 
411
    m = (double **) R_alloc((nrh + 1), sizeof(double *));
448
    m = (double **) R_alloc((nrh + 1), sizeof(double *));
412
    for (i = 0; i <= nrh; i++)
449
    for (i = 0; i <= nrh; i++)
413
	m[i] = (double*) R_alloc((nch + 1), sizeof(double));
450
	m[i] = (double*) R_alloc((nch + 1), sizeof(double));
414
    return m;
451
    return m;
415
}
452
}
416
 
453
 
417
static double ** Lmatrix(int n)
454
static double ** Lmatrix(int n)
418
{
455
{
419
    int   i;
456
    int   i;
420
    double **m;
457
    double **m;
421
 
458
 
422
    m = (double **) R_alloc(n, sizeof(double *));
459
    m = (double **) R_alloc(n, sizeof(double *));
423
    for (i = 0; i < n; i++)
460
    for (i = 0; i < n; i++)
424
	m[i] = (double *) R_alloc((i + 1), sizeof(double));
461
	m[i] = (double *) R_alloc((i + 1), sizeof(double));
425
    return m;
462
    return m;
426
}
463
}
427
 
464
 
428
 
465
 
429
 
466
 
430
#define stepredn	0.2
467
#define stepredn	0.2
431
#define acctol		0.0001
468
#define acctol		0.0001
432
#define reltest		10.0
469
#define reltest		10.0
433
 
470
 
434
 
471
 
435
/*  BFGS variable-metric method, based on Pascal code
472
/*  BFGS variable-metric method, based on Pascal code
436
in J.C. Nash, `Compact Numerical Methods for Computers', 2nd edition,
473
in J.C. Nash, `Compact Numerical Methods for Computers', 2nd edition,
437
converted by p2c then re-crafted by B.D. Ripley */
474
converted by p2c then re-crafted by B.D. Ripley */
438
 
475
 
439
void
476
void
440
vmmin(int n0, double *b, double *Fmin, optimfn fminfn, optimgr fmingr,
477
vmmin(int n0, double *b, double *Fmin, optimfn fminfn, optimgr fmingr,
441
      int maxit, int trace, int *mask,
478
      int maxit, int trace, int *mask,
442
      double abstol, double reltol, int nREPORT, void *ex,
479
      double abstol, double reltol, int nREPORT, void *ex,
443
      int *fncount, int *grcount, int *fail)
480
      int *fncount, int *grcount, int *fail)
444
{
481
{
445
    Rboolean accpoint, enough;
482
    Rboolean accpoint, enough;
446
    double *g, *t, *X, *c, **B;
483
    double *g, *t, *X, *c, **B;
447
    int   count, funcount, gradcount;
484
    int   count, funcount, gradcount;
448
    double f, gradproj;
485
    double f, gradproj;
449
    int   i, j, ilast, iter = 0;
486
    int   i, j, ilast, iter = 0;
450
    double s, steplength;
487
    double s, steplength;
451
    double D1, D2;
488
    double D1, D2;
452
    int   n, *l;
489
    int   n, *l;
453
 
490
 
454
    if (maxit <= 0) {
491
    if (maxit <= 0) {
455
	*fail = 0;
492
	*fail = 0;
456
	*Fmin = fminfn(n0, b, ex);
493
	*Fmin = fminfn(n0, b, ex);
457
	*fncount = *grcount = 0;
494
	*fncount = *grcount = 0;
458
	return;
495
	return;
459
    }
496
    }
460
 
497
 
461
    if (nREPORT <= 0)
498
    if (nREPORT <= 0)
462
	error("REPORT must be > 0 (method = \"BFGS\")");
499
	error("REPORT must be > 0 (method = \"BFGS\")");
463
    l = (int *) R_alloc(n0, sizeof(int));
500
    l = (int *) R_alloc(n0, sizeof(int));
464
    n = 0;
501
    n = 0;
465
    for (i = 0; i < n0; i++) if (mask[i]) l[n++] = i;
502
    for (i = 0; i < n0; i++) if (mask[i]) l[n++] = i;
466
    g = vect(n0);
503
    g = vect(n0);
467
    t = vect(n);
504
    t = vect(n);
468
    X = vect(n);
505
    X = vect(n);
469
    c = vect(n);
506
    c = vect(n);
470
    B = Lmatrix(n);
507
    B = Lmatrix(n);
471
    f = fminfn(n0, b, ex);
508
    f = fminfn(n0, b, ex);
472
    if (!R_FINITE(f))
509
    if (!R_FINITE(f))
473
	error("initial value in vmmin is not finite");
510
	error("initial value in vmmin is not finite");
474
    if (trace) Rprintf("initial  value %f \n", f);
511
    if (trace) Rprintf("initial  value %f \n", f);
475
    *Fmin = f;
512
    *Fmin = f;
476
    funcount = gradcount = 1;
513
    funcount = gradcount = 1;
477
    fmingr(n0, b, g, ex);
514
    fmingr(n0, b, g, ex);
478
    iter++;
515
    iter++;
479
    ilast = gradcount;
516
    ilast = gradcount;
480
 
517
 
481
    do {
518
    do {
482
	if (ilast == gradcount) {
519
	if (ilast == gradcount) {
483
	    for (i = 0; i < n; i++) {
520
	    for (i = 0; i < n; i++) {
484
		for (j = 0; j < i; j++) B[i][j] = 0.0;
521
		for (j = 0; j < i; j++) B[i][j] = 0.0;
485
		B[i][i] = 1.0;
522
		B[i][i] = 1.0;
486
	    }
523
	    }
487
	}
524
	}
488
	for (i = 0; i < n; i++) {
525
	for (i = 0; i < n; i++) {
489
	    X[i] = b[l[i]];
526
	    X[i] = b[l[i]];
490
	    c[i] = g[l[i]];
527
	    c[i] = g[l[i]];
491
	}
528
	}
492
	gradproj = 0.0;
529
	gradproj = 0.0;
493
	for (i = 0; i < n; i++) {
530
	for (i = 0; i < n; i++) {
494
	    s = 0.0;
531
	    s = 0.0;
495
	    for (j = 0; j <= i; j++) s -= B[i][j] * g[l[j]];
532
	    for (j = 0; j <= i; j++) s -= B[i][j] * g[l[j]];
496
	    for (j = i + 1; j < n; j++) s -= B[j][i] * g[l[j]];
533
	    for (j = i + 1; j < n; j++) s -= B[j][i] * g[l[j]];
497
	    t[i] = s;
534
	    t[i] = s;
498
	    gradproj += s * g[l[i]];
535
	    gradproj += s * g[l[i]];
499
	}
536
	}
500
 
537
 
501
	if (gradproj < 0.0) {	/* search direction is downhill */
538
	if (gradproj < 0.0) {	/* search direction is downhill */
502
	    steplength = 1.0;
539
	    steplength = 1.0;
503
	    accpoint = FALSE;
540
	    accpoint = FALSE;
504
	    do {
541
	    do {
505
		count = 0;
542
		count = 0;
506
		for (i = 0; i < n; i++) {
543
		for (i = 0; i < n; i++) {
507
		    b[l[i]] = X[i] + steplength * t[i];
544
		    b[l[i]] = X[i] + steplength * t[i];
508
		    if (reltest + X[i] == reltest + b[l[i]]) /* no change */
545
		    if (reltest + X[i] == reltest + b[l[i]]) /* no change */
509
			count++;
546
			count++;
510
		}
547
		}
511
		if (count < n) {
548
		if (count < n) {
512
		    f = fminfn(n0, b, ex);
549
		    f = fminfn(n0, b, ex);
513
		    funcount++;
550
		    funcount++;
514
		    accpoint = R_FINITE(f) &&
551
		    accpoint = R_FINITE(f) &&
515
			(f <= *Fmin + gradproj * steplength * acctol);
552
			(f <= *Fmin + gradproj * steplength * acctol);
516
		    if (!accpoint) {
553
		    if (!accpoint) {
517
			steplength *= stepredn;
554
			steplength *= stepredn;
518
		    }
555
		    }
519
		}
556
		}
520
	    } while (!(count == n || accpoint));
557
	    } while (!(count == n || accpoint));
521
	    enough = (f > abstol) &&
558
	    enough = (f > abstol) &&
522
		fabs(f - *Fmin) > reltol * (fabs(*Fmin) + reltol);
559
		fabs(f - *Fmin) > reltol * (fabs(*Fmin) + reltol);
523
	    /* stop if value if small or if relative change is low */
560
	    /* stop if value if small or if relative change is low */
524
	    if (!enough) {
561
	    if (!enough) {
525
		count = n;
562
		count = n;
526
		*Fmin = f;
563
		*Fmin = f;
527
	    }
564
	    }
528
	    if (count < n) {/* making progress */
565
	    if (count < n) {/* making progress */
529
		*Fmin = f;
566
		*Fmin = f;
530
		fmingr(n0, b, g, ex);
567
		fmingr(n0, b, g, ex);
531
		gradcount++;
568
		gradcount++;
532
		iter++;
569
		iter++;
533
		D1 = 0.0;
570
		D1 = 0.0;
534
		for (i = 0; i < n; i++) {
571
		for (i = 0; i < n; i++) {
535
		    t[i] = steplength * t[i];
572
		    t[i] = steplength * t[i];
536
		    c[i] = g[l[i]] - c[i];
573
		    c[i] = g[l[i]] - c[i];
537
		    D1 += t[i] * c[i];
574
		    D1 += t[i] * c[i];
538
		}
575
		}
539
		if (D1 > 0) {
576
		if (D1 > 0) {
540
		    D2 = 0.0;
577
		    D2 = 0.0;
541
		    for (i = 0; i < n; i++) {
578
		    for (i = 0; i < n; i++) {
542
			s = 0.0;
579
			s = 0.0;
543
			for (j = 0; j <= i; j++)
580
			for (j = 0; j <= i; j++)
544
			    s += B[i][j] * c[j];
581
			    s += B[i][j] * c[j];
545
			for (j = i + 1; j < n; j++)
582
			for (j = i + 1; j < n; j++)
546
			    s += B[j][i] * c[j];
583
			    s += B[j][i] * c[j];
547
			X[i] = s;
584
			X[i] = s;
548
			D2 += s * c[i];
585
			D2 += s * c[i];
549
		    }
586
		    }
550
		    D2 = 1.0 + D2 / D1;
587
		    D2 = 1.0 + D2 / D1;
551
		    for (i = 0; i < n; i++) {
588
		    for (i = 0; i < n; i++) {
552
			for (j = 0; j <= i; j++)
589
			for (j = 0; j <= i; j++)
553
			    B[i][j] += (D2 * t[i] * t[j]
590
			    B[i][j] += (D2 * t[i] * t[j]
554
					- X[i] * t[j] - t[i] * X[j]) / D1;
591
					- X[i] * t[j] - t[i] * X[j]) / D1;
555
		    }
592
		    }
556
		} else {	/* D1 < 0 */
593
		} else {	/* D1 < 0 */
557
		    ilast = gradcount;
594
		    ilast = gradcount;
558
		}
595
		}
559
	    } else {	/* no progress */
596
	    } else {	/* no progress */
560
		if (ilast < gradcount) {
597
		if (ilast < gradcount) {
561
		    count = 0;
598
		    count = 0;
562
		    ilast = gradcount;
599
		    ilast = gradcount;
563
		}
600
		}
564
	    }
601
	    }
565
	} else {		/* uphill search */
602
	} else {		/* uphill search */
566
	    count = 0;
603
	    count = 0;
567
	    if (ilast == gradcount) count = n;
604
	    if (ilast == gradcount) count = n;
568
	    else ilast = gradcount;
605
	    else ilast = gradcount;
569
	    /* Resets unless has just been reset */
606
	    /* Resets unless has just been reset */
570
	}
607
	}
571
	if (trace && (iter % nREPORT == 0))
608
	if (trace && (iter % nREPORT == 0))
572
	    Rprintf("iter%4d value %f\n", iter, f);
609
	    Rprintf("iter%4d value %f\n", iter, f);
573
	if (iter >= maxit) break;
610
	if (iter >= maxit) break;
574
	if (gradcount - ilast > 2 * n)
611
	if (gradcount - ilast > 2 * n)
575
	    ilast = gradcount;	/* periodic restart */
612
	    ilast = gradcount;	/* periodic restart */
576
    } while (count != n || ilast != gradcount);
613
    } while (count != n || ilast != gradcount);
577
    if (trace) {
614
    if (trace) {
578
	Rprintf("final  value %f \n", *Fmin);
615
	Rprintf("final  value %f \n", *Fmin);
579
	if (iter < maxit) Rprintf("converged\n");
616
	if (iter < maxit) Rprintf("converged\n");
580
	else Rprintf("stopped after %i iterations\n", iter);
617
	else Rprintf("stopped after %i iterations\n", iter);
581
    }
618
    }
582
    *fail = (iter < maxit) ? 0 : 1;
619
    *fail = (iter < maxit) ? 0 : 1;
583
    *fncount = funcount;
620
    *fncount = funcount;
584
    *grcount = gradcount;
621
    *grcount = gradcount;
585
}
622
}
586
 
623
 
587
 
624
 
588
#define big             1.0e+35   /*a very large number*/
625
#define big             1.0e+35   /*a very large number*/
589
 
626
 
590
 
627
 
591
/* Nelder-Mead */
628
/* Nelder-Mead */
592
void nmmin(int n, double *Bvec, double *X, double *Fmin, optimfn fminfn,
629
void nmmin(int n, double *Bvec, double *X, double *Fmin, optimfn fminfn,
593
	   int *fail, double abstol, double intol, void *ex,
630
	   int *fail, double abstol, double intol, void *ex,
594
	   double alpha, double bet, double gamm, int trace,
631
	   double alpha, double bet, double gamm, int trace,
595
	   int *fncount, int maxit)
632
	   int *fncount, int maxit)
596
{
633
{
597
    char action[50];
634
    char action[50];
598
    int C;
635
    int C;
599
    Rboolean calcvert, shrinkfail = FALSE;
636
    Rboolean calcvert, shrinkfail = FALSE;
600
    double convtol, f;
637
    double convtol, f;
601
    int funcount=0, H, i, j, L=0;
638
    int funcount=0, H, i, j, L=0;
602
    int n1=0;
639
    int n1=0;
603
    double oldsize;
640
    double oldsize;
604
    double **P;
641
    double **P;
605
    double size, step, temp, trystep;
642
    double size, step, temp, trystep;
606
    char tstr[6];
643
    char tstr[6];
607
    double VH, VL, VR;
644
    double VH, VL, VR;
608
 
645
 
609
    if (maxit <= 0) {
646
    if (maxit <= 0) {
610
	*Fmin = fminfn(n, Bvec, ex);
647
	*Fmin = fminfn(n, Bvec, ex);
611
	*fncount = 0;
648
	*fncount = 0;
612
	*fail = 0;
649
	*fail = 0;
613
	return;
650
	return;
614
    }
651
    }
615
    if (trace)
652
    if (trace)
616
	Rprintf("  Nelder-Mead direct search function minimizer\n");
653
	Rprintf("  Nelder-Mead direct search function minimizer\n");
617
    P = matrix(n, n+1);
654
    P = matrix(n, n+1);
618
    *fail = FALSE;
655
    *fail = FALSE;
619
    f = fminfn(n, Bvec, ex);
656
    f = fminfn(n, Bvec, ex);
620
    if (!R_FINITE(f)) {
657
    if (!R_FINITE(f)) {
621
	error("Function cannot be evaluated at initial parameters");
658
	error("Function cannot be evaluated at initial parameters");
622
	*fail = TRUE;
659
	*fail = TRUE;
623
    } else {
660
    } else {
624
	if (trace) Rprintf("Function value for initial parameters = %f\n", f);
661
	if (trace) Rprintf("Function value for initial parameters = %f\n", f);
625
	funcount = 1;
662
	funcount = 1;
626
	convtol = intol * (fabs(f) + intol);
663
	convtol = intol * (fabs(f) + intol);
627
	if (trace) Rprintf("  Scaled convergence tolerance is %g\n", convtol);
664
	if (trace) Rprintf("  Scaled convergence tolerance is %g\n", convtol);
628
	n1 = n + 1;
665
	n1 = n + 1;
629
	C = n + 2;
666
	C = n + 2;
630
	P[n1 - 1][0] = f;
667
	P[n1 - 1][0] = f;
631
	for (i = 0; i < n; i++)
668
	for (i = 0; i < n; i++)
632
	    P[i][0] = Bvec[i];
669
	    P[i][0] = Bvec[i];
633
 
670
 
634
	L = 1;
671
	L = 1;
635
	size = 0.0;
672
	size = 0.0;
636
 
673
 
637
	step = 0.0;
674
	step = 0.0;
638
	for (i = 0; i < n; i++) {
675
	for (i = 0; i < n; i++) {
639
	    if (0.1 * fabs(Bvec[i]) > step)
676
	    if (0.1 * fabs(Bvec[i]) > step)
640
		step = 0.1 * fabs(Bvec[i]);
677
		step = 0.1 * fabs(Bvec[i]);
641
	}
678
	}
642
	if (step == 0.0) step = 0.1;
679
	if (step == 0.0) step = 0.1;
643
	if (trace) Rprintf("Stepsize computed as %f\n", step);
680
	if (trace) Rprintf("Stepsize computed as %f\n", step);
644
	for (j = 2; j <= n1; j++) {
681
	for (j = 2; j <= n1; j++) {
645
	    strcpy(action, "BUILD          ");
682
	    strcpy(action, "BUILD          ");
646
	    for (i = 0; i < n; i++)
683
	    for (i = 0; i < n; i++)
647
		P[i][j - 1] = Bvec[i];
684
		P[i][j - 1] = Bvec[i];
648
 
685
 
649
	    trystep = step;
686
	    trystep = step;
650
	    while (P[j - 2][j - 1] == Bvec[j - 2]) {
687
	    while (P[j - 2][j - 1] == Bvec[j - 2]) {
651
		P[j - 2][j - 1] = Bvec[j - 2] + trystep;
688
		P[j - 2][j - 1] = Bvec[j - 2] + trystep;
652
		trystep *= 10;
689
		trystep *= 10;
653
	    }
690
	    }
654
	    size += trystep;
691
	    size += trystep;
655
	}
692
	}
656
	oldsize = size;
693
	oldsize = size;
657
	calcvert = TRUE;
694
	calcvert = TRUE;
658
	shrinkfail = FALSE;
695
	shrinkfail = FALSE;
659
	do {
696
	do {
660
	    if (calcvert) {
697
	    if (calcvert) {
661
		for (j = 0; j < n1; j++) {
698
		for (j = 0; j < n1; j++) {
662
		    if (j + 1 != L) {
699
		    if (j + 1 != L) {
663
			for (i = 0; i < n; i++)
700
			for (i = 0; i < n; i++)
664
			    Bvec[i] = P[i][j];
701
			    Bvec[i] = P[i][j];
665
			f = fminfn(n, Bvec, ex);
702
			f = fminfn(n, Bvec, ex);
666
			if (!R_FINITE(f)) f = big;
703
			if (!R_FINITE(f)) f = big;
667
			funcount++;
704
			funcount++;
668
			P[n1 - 1][j] = f;
705
			P[n1 - 1][j] = f;
669
		    }
706
		    }
670
		}
707
		}
671
		calcvert = FALSE;
708
		calcvert = FALSE;
672
	    }
709
	    }
673
 
710
 
674
	    VL = P[n1 - 1][L - 1];
711
	    VL = P[n1 - 1][L - 1];
675
	    VH = VL;
712
	    VH = VL;
676
	    H = L;
713
	    H = L;
677
 
714
 
678
	    for (j = 1; j <= n1; j++) {
715
	    for (j = 1; j <= n1; j++) {
679
		if (j != L) {
716
		if (j != L) {
680
		    f = P[n1 - 1][j - 1];
717
		    f = P[n1 - 1][j - 1];
681
		    if (f < VL) {
718
		    if (f < VL) {
682
			L = j;
719
			L = j;
683
			VL = f;
720
			VL = f;
684
		    }
721
		    }
685
		    if (f > VH) {
722
		    if (f > VH) {
686
			H = j;
723
			H = j;
687
			VH = f;
724
			VH = f;
688
		    }
725
		    }
689
		}
726
		}
690
	    }
727
	    }
691
 
728
 
692
	    if (VH > VL + convtol && VL > abstol) {
729
	    if (VH > VL + convtol && VL > abstol) {
693
		sprintf(tstr, "%5d", funcount);
730
		sprintf(tstr, "%5d", funcount);
694
		if (trace) Rprintf("%s%s %f %f\n", action, tstr, VH, VL);
731
		if (trace) Rprintf("%s%s %f %f\n", action, tstr, VH, VL);
695
 
732
 
696
		for (i = 0; i < n; i++) {
733
		for (i = 0; i < n; i++) {
697
		    temp = -P[i][H - 1];
734
		    temp = -P[i][H - 1];
698
		    for (j = 0; j < n1; j++)
735
		    for (j = 0; j < n1; j++)
699
			temp += P[i][j];
736
			temp += P[i][j];
700
		    P[i][C - 1] = temp / n;
737
		    P[i][C - 1] = temp / n;
701
		}
738
		}
702
		for (i = 0; i < n; i++)
739
		for (i = 0; i < n; i++)
703
		    Bvec[i] = (1.0 + alpha) * P[i][C - 1] - alpha * P[i][H - 1];
740
		    Bvec[i] = (1.0 + alpha) * P[i][C - 1] - alpha * P[i][H - 1];
704
		f = fminfn(n, Bvec, ex);
741
		f = fminfn(n, Bvec, ex);
705
		if (!R_FINITE(f)) f = big;
742
		if (!R_FINITE(f)) f = big;
706
		funcount++;
743
		funcount++;
707
		strcpy(action, "REFLECTION     ");
744
		strcpy(action, "REFLECTION     ");
708
		VR = f;
745
		VR = f;
709
		if (VR < VL) {
746
		if (VR < VL) {
710
		    P[n1 - 1][C - 1] = f;
747
		    P[n1 - 1][C - 1] = f;
711
		    for (i = 0; i < n; i++) {
748
		    for (i = 0; i < n; i++) {
712
			f = gamm * Bvec[i] + (1 - gamm) * P[i][C - 1];
749
			f = gamm * Bvec[i] + (1 - gamm) * P[i][C - 1];
713
			P[i][C - 1] = Bvec[i];
750
			P[i][C - 1] = Bvec[i];
714
			Bvec[i] = f;
751
			Bvec[i] = f;
715
		    }
752
		    }
716
		    f = fminfn(n, Bvec, ex);
753
		    f = fminfn(n, Bvec, ex);
717
		    if (!R_FINITE(f)) f = big;
754
		    if (!R_FINITE(f)) f = big;
718
		    funcount++;
755
		    funcount++;
719
		    if (f < VR) {
756
		    if (f < VR) {
720
			for (i = 0; i < n; i++)
757
			for (i = 0; i < n; i++)
721
			    P[i][H - 1] = Bvec[i];
758
			    P[i][H - 1] = Bvec[i];
722
			P[n1 - 1][H - 1] = f;
759
			P[n1 - 1][H - 1] = f;
723
			strcpy(action, "EXTENSION      ");
760
			strcpy(action, "EXTENSION      ");
724
		    } else {
761
		    } else {
725
			for (i = 0; i < n; i++)
762
			for (i = 0; i < n; i++)
726
			    P[i][H - 1] = P[i][C - 1];
763
			    P[i][H - 1] = P[i][C - 1];
727
			P[n1 - 1][H - 1] = VR;
764
			P[n1 - 1][H - 1] = VR;
728
		    }
765
		    }
729
		} else {
766
		} else {
730
		    strcpy(action, "HI-REDUCTION   ");
767
		    strcpy(action, "HI-REDUCTION   ");
731
		    if (VR < VH) {
768
		    if (VR < VH) {
732
			for (i = 0; i < n; i++)
769
			for (i = 0; i < n; i++)
733
			    P[i][H - 1] = Bvec[i];
770
			    P[i][H - 1] = Bvec[i];
734
			P[n1 - 1][H - 1] = VR;
771
			P[n1 - 1][H - 1] = VR;
735
			strcpy(action, "LO-REDUCTION   ");
772
			strcpy(action, "LO-REDUCTION   ");
736
		    }
773
		    }
737
 
774
 
738
		    for (i = 0; i < n; i++)
775
		    for (i = 0; i < n; i++)
739
			Bvec[i] = (1 - bet) * P[i][H - 1] + bet * P[i][C - 1];
776
			Bvec[i] = (1 - bet) * P[i][H - 1] + bet * P[i][C - 1];
740
		    f = fminfn(n, Bvec, ex);
777
		    f = fminfn(n, Bvec, ex);
741
		    if (!R_FINITE(f)) f = big;
778
		    if (!R_FINITE(f)) f = big;
742
		    funcount++;
779
		    funcount++;
743
 
780
 
744
		    if (f < P[n1 - 1][H - 1]) {
781
		    if (f < P[n1 - 1][H - 1]) {
745
			for (i = 0; i < n; i++)
782
			for (i = 0; i < n; i++)
746
			    P[i][H - 1] = Bvec[i];
783
			    P[i][H - 1] = Bvec[i];
747
			P[n1 - 1][H - 1] = f;
784
			P[n1 - 1][H - 1] = f;
748
		    } else {
785
		    } else {
749
			if (VR >= VH) {
786
			if (VR >= VH) {
750
			    strcpy(action, "SHRINK         ");
787
			    strcpy(action, "SHRINK         ");
751
			    calcvert = TRUE;
788
			    calcvert = TRUE;
752
			    size = 0.0;
789
			    size = 0.0;
753
			    for (j = 0; j < n1; j++) {
790
			    for (j = 0; j < n1; j++) {
754
				if (j + 1 != L) {
791
				if (j + 1 != L) {
755
				    for (i = 0; i < n; i++) {
792
				    for (i = 0; i < n; i++) {
756
					P[i][j] = bet * (P[i][j] - P[i][L - 1])
793
					P[i][j] = bet * (P[i][j] - P[i][L - 1])
757
					    + P[i][L - 1];
794
					    + P[i][L - 1];
758
					size += fabs(P[i][j] - P[i][L - 1]);
795
					size += fabs(P[i][j] - P[i][L - 1]);
759
				    }
796
				    }
760
				}
797
				}
761
			    }
798
			    }
762
			    if (size < oldsize) {
799
			    if (size < oldsize) {
763
				shrinkfail = FALSE;
800
				shrinkfail = FALSE;
764
				oldsize = size;
801
				oldsize = size;
765
			    } else {
802
			    } else {
766
				if (trace)
803
				if (trace)
767
				    Rprintf("Polytope size measure not decreased in shrink\n");
804
				    Rprintf("Polytope size measure not decreased in shrink\n");
768
				shrinkfail = TRUE;
805
				shrinkfail = TRUE;
769
			    }
806
			    }
770
			}
807
			}
771
		    }
808
		    }
772
		}
809
		}
773
	    }
810
	    }
774
 
811
 
775
	} while (!(VH <= VL + convtol || VL <= abstol ||
812
	} while (!(VH <= VL + convtol || VL <= abstol ||
776
		   shrinkfail || funcount > maxit));
813
		   shrinkfail || funcount > maxit));
777
 
814
 
778
    }
815
    }
779
 
816
 
780
    if (trace) {
817
    if (trace) {
781
	Rprintf("Exiting from Nelder Mead minimizer\n");
818
	Rprintf("Exiting from Nelder Mead minimizer\n");
782
	Rprintf("    %d function evaluations used\n", funcount);
819
	Rprintf("    %d function evaluations used\n", funcount);
783
    }
820
    }
784
    *Fmin = P[n1 - 1][L - 1];
821
    *Fmin = P[n1 - 1][L - 1];
785
    for (i = 0; i < n; i++) X[i] = P[i][L - 1];
822
    for (i = 0; i < n; i++) X[i] = P[i][L - 1];
786
    if (shrinkfail) *fail = 10;
823
    if (shrinkfail) *fail = 10;
787
    if (funcount > maxit) *fail = 1;
824
    if (funcount > maxit) *fail = 1;
788
    *fncount = funcount;
825
    *fncount = funcount;
789
}
826
}
790
 
827
 
791
void cgmin(int n, double *Bvec, double *X, double *Fmin,
828
void cgmin(int n, double *Bvec, double *X, double *Fmin,
792
	   optimfn fminfn, optimgr fmingr, int *fail,
829
	   optimfn fminfn, optimgr fmingr, int *fail,
793
	   double abstol, double intol, void *ex, int type, int trace,
830
	   double abstol, double intol, void *ex, int type, int trace,
794
	   int *fncount, int *grcount, int maxit)
831
	   int *fncount, int *grcount, int maxit)
795
{
832
{
796
    Rboolean accpoint;
833
    Rboolean accpoint;
797
    double *c, *g, *t;
834
    double *c, *g, *t;
798
    int count, cycle, cyclimit;
835
    int count, cycle, cyclimit;
799
    double f;
836
    double f;
800
    double G1, G2, G3, gradproj;
837
    double G1, G2, G3, gradproj;
801
    int funcount=0, gradcount=0, i;
838
    int funcount=0, gradcount=0, i;
802
    double newstep, oldstep, setstep, steplength=1.0;
839
    double newstep, oldstep, setstep, steplength=1.0;
803
    double tol;
840
    double tol;
804
 
841
 
805
    if (maxit <= 0) {
842
    if (maxit <= 0) {
806
	*Fmin = fminfn(n, Bvec, ex);
843
	*Fmin = fminfn(n, Bvec, ex);
807
	*fncount = *grcount = 0;
844
	*fncount = *grcount = 0;
808
	*fail = FALSE;
845
	*fail = FALSE;
809
	return;
846
	return;
810
    }
847
    }
811
    if (trace) {
848
    if (trace) {
812
	Rprintf("  Conjugate gradients function minimiser\n");
849
	Rprintf("  Conjugate gradients function minimiser\n");
813
	switch (type) {
850
	switch (type) {
814
	case 1:	    Rprintf("Method: Fletcher Reeves\n");	break;
851
	case 1:	    Rprintf("Method: Fletcher Reeves\n");	break;
815
	case 2:	    Rprintf("Method: Polak Ribiere\n");		break;
852
	case 2:	    Rprintf("Method: Polak Ribiere\n");		break;
816
	case 3:	    Rprintf("Method: Beale Sorenson\n");	break;
853
	case 3:	    Rprintf("Method: Beale Sorenson\n");	break;
817
	default:
854
	default:
818
	    error("unknown type in CG method of optim");
855
	    error("unknown type in CG method of optim");
819
	}
856
	}
820
    }
857
    }
821
    c = vect(n); g = vect(n); t = vect(n);
858
    c = vect(n); g = vect(n); t = vect(n);
822
 
859
 
823
    setstep = 1.7;
860
    setstep = 1.7;
824
    *fail = 0;
861
    *fail = 0;
825
    cyclimit = n;
862
    cyclimit = n;
826
    tol = intol * n * sqrt(intol);
863
    tol = intol * n * sqrt(intol);
827
 
864
 
828
    if (trace) Rprintf("tolerance used in gradient test=%g\n", tol);
865
    if (trace) Rprintf("tolerance used in gradient test=%g\n", tol);
829
    f = fminfn(n, Bvec, ex);
866
    f = fminfn(n, Bvec, ex);
830
    if (!R_FINITE(f)) {
867
    if (!R_FINITE(f)) {
831
	error("Function cannot be evaluated at initial parameters");
868
	error("Function cannot be evaluated at initial parameters");
832
    } else {
869
    } else {
833
	*Fmin = f;
870
	*Fmin = f;
834
	funcount = 1;
871
	funcount = 1;
835
	gradcount = 0;
872
	gradcount = 0;
836
	do {
873
	do {
837
	    for (i = 0; i < n; i++) {
874
	    for (i = 0; i < n; i++) {
838
		t[i] = 0.0;
875
		t[i] = 0.0;
839
		c[i] = 0.0;
876
		c[i] = 0.0;
840
	    }
877
	    }
841
	    cycle = 0;
878
	    cycle = 0;
842
	    oldstep = 1.0;
879
	    oldstep = 1.0;
843
	    count = 0;
880
	    count = 0;
844
	    do {
881
	    do {
845
		cycle++;
882
		cycle++;
846
		if (trace) {
883
		if (trace) {
847
		    Rprintf("%d %d %f\n", gradcount, funcount, *Fmin);
884
		    Rprintf("%d %d %f\n", gradcount, funcount, *Fmin);
848
		    Rprintf("parameters ");
885
		    Rprintf("parameters ");
849
		    for (i = 1; i <= n; i++) {
886
		    for (i = 1; i <= n; i++) {
850
			Rprintf("%10.5f ", Bvec[i - 1]);
887
			Rprintf("%10.5f ", Bvec[i - 1]);
851
			if (i / 7 * 7 == i && i < n)
888
			if (i / 7 * 7 == i && i < n)
852
			    Rprintf("\n");
889
			    Rprintf("\n");
853
		    }
890
		    }
854
		    Rprintf("\n");
891
		    Rprintf("\n");
855
		}
892
		}
856
		gradcount++;
893
		gradcount++;
857
		if (gradcount > maxit) {
894
		if (gradcount > maxit) {
858
		    *fncount = funcount;
895
		    *fncount = funcount;
859
		    *grcount = gradcount;
896
		    *grcount = gradcount;
860
		    *fail = 1;
897
		    *fail = 1;
861
		    return;
898
		    return;
862
		}
899
		}
863
		fmingr(n, Bvec, g, ex);
900
		fmingr(n, Bvec, g, ex);
864
		G1 = 0.0;
901
		G1 = 0.0;
865
		G2 = 0.0;
902
		G2 = 0.0;
866
		for (i = 0; i < n; i++) {
903
		for (i = 0; i < n; i++) {
867
		    X[i] = Bvec[i];
904
		    X[i] = Bvec[i];
868
		    switch (type) {
905
		    switch (type) {
869
 
906
 
870
		    case 1: /* Fletcher-Reeves */
907
		    case 1: /* Fletcher-Reeves */
871
			G1 += g[i] * g[i];
908
			G1 += g[i] * g[i];
872
			G2 += c[i] * c[i];
909
			G2 += c[i] * c[i];
873
			break;
910
			break;
874
 
911
 
875
		    case 2: /* Polak-Ribiere */
912
		    case 2: /* Polak-Ribiere */
876
			G1 += g[i] * (g[i] - c[i]);
913
			G1 += g[i] * (g[i] - c[i]);
877
			G2 += c[i] * c[i];
914
			G2 += c[i] * c[i];
878
			break;
915
			break;
879
 
916
 
880
		    case 3: /* Beale-Sorenson */
917
		    case 3: /* Beale-Sorenson */
881
			G1 += g[i] * (g[i] - c[i]);
918
			G1 += g[i] * (g[i] - c[i]);
882
			G2 += t[i] * (g[i] - c[i]);
919
			G2 += t[i] * (g[i] - c[i]);
883
			break;
920
			break;
884
 
921
 
885
		    default:
922
		    default:
886
			error("unknown type in CG method of optim");
923
			error("unknown type in CG method of optim");
887
		    }
924
		    }
888
		    c[i] = g[i];
925
		    c[i] = g[i];
889
		}
926
		}
890
		if (G1 > tol) {
927
		if (G1 > tol) {
891
		    if (G2 > 0.0)
928
		    if (G2 > 0.0)
892
			G3 = G1 / G2;
929
			G3 = G1 / G2;
893
		    else
930
		    else
894
			G3 = 1.0;
931
			G3 = 1.0;
895
		    gradproj = 0.0;
932
		    gradproj = 0.0;
896
		    for (i = 0; i < n; i++) {
933
		    for (i = 0; i < n; i++) {
897
			t[i] = t[i] * G3 - g[i];
934
			t[i] = t[i] * G3 - g[i];
898
			gradproj += t[i] * g[i];
935
			gradproj += t[i] * g[i];
899
		    }
936
		    }
900
		    steplength = oldstep;
937
		    steplength = oldstep;
901
 
938
 
902
		    accpoint = FALSE;
939
		    accpoint = FALSE;
903
		    do {
940
		    do {
904
			count = 0;
941
			count = 0;
905
			for (i = 0; i < n; i++) {
942
			for (i = 0; i < n; i++) {
906
			    Bvec[i] = X[i] + steplength * t[i];
943
			    Bvec[i] = X[i] + steplength * t[i];
907
			    if (reltest + X[i] == reltest + Bvec[i])
944
			    if (reltest + X[i] == reltest + Bvec[i])
908
				count++;
945
				count++;
909
			}
946
			}
910
			if (count < n) {
947
			if (count < n) {
911
			    f = fminfn(n, Bvec, ex);
948
			    f = fminfn(n, Bvec, ex);
912
			    funcount++;
949
			    funcount++;
913
			    accpoint = (R_FINITE(f) &&
950
			    accpoint = (R_FINITE(f) &&
914
					f <= *Fmin + gradproj * steplength * acctol);
951
					f <= *Fmin + gradproj * steplength * acctol);
915
 
952
 
916
			    if (!accpoint) {
953
			    if (!accpoint) {
917
				steplength *= stepredn;
954
				steplength *= stepredn;
918
				if (trace) Rprintf("*");
955
				if (trace) Rprintf("*");
919
			    }
956
			    }
920
			}
957
			}
921
		    } while (!(count == n || accpoint));
958
		    } while (!(count == n || accpoint));
922
		    if (count < n) {
959
		    if (count < n) {
923
			newstep = 2 * (f - *Fmin - gradproj * steplength);
960
			newstep = 2 * (f - *Fmin - gradproj * steplength);
924
			if (newstep > 0) {
961
			if (newstep > 0) {
925
			    newstep = -(gradproj * steplength * steplength / newstep);
962
			    newstep = -(gradproj * steplength * steplength / newstep);
926
			    for (i = 0; i < n; i++)
963
			    for (i = 0; i < n; i++)
927
				Bvec[i] = X[i] + newstep * t[i];
964
				Bvec[i] = X[i] + newstep * t[i];
928
			    *Fmin = f;
965
			    *Fmin = f;
929
			    f = fminfn(n, Bvec, ex);
966
			    f = fminfn(n, Bvec, ex);
930
			    funcount++;
967
			    funcount++;
931
			    if (f < *Fmin) {
968
			    if (f < *Fmin) {
932
				*Fmin = f;
969
				*Fmin = f;
933
				if (trace) Rprintf(" i< ");
970
				if (trace) Rprintf(" i< ");
934
			    } else {
971
			    } else {
935
				if (trace) Rprintf(" i> ");
972
				if (trace) Rprintf(" i> ");
936
				for (i = 0; i < n; i++)
973
				for (i = 0; i < n; i++)
937
				    Bvec[i] = X[i] + steplength * t[i];
974
				    Bvec[i] = X[i] + steplength * t[i];
938
			    }
975
			    }
939
			}
976
			}
940
		    }
977
		    }
941
		}
978
		}
942
		oldstep = setstep * steplength;
979
		oldstep = setstep * steplength;
943
		if (oldstep > 1.0)
980
		if (oldstep > 1.0)
944
		    oldstep = 1.0;
981
		    oldstep = 1.0;
945
	    } while ((count != n) && (G1 > tol) && (cycle != cyclimit));
982
	    } while ((count != n) && (G1 > tol) && (cycle != cyclimit));
946
 
983
 
947
	} while ((cycle != 1) ||
984
	} while ((cycle != 1) ||
948
		 ((count != n) && (G1 > tol) && *Fmin > abstol));
985
		 ((count != n) && (G1 > tol) && *Fmin > abstol));
949
 
986
 
950
    }
987
    }
951
    if (trace) {
988
    if (trace) {
952
	Rprintf("Exiting from conjugate gradients minimizer\n");
989
	Rprintf("Exiting from conjugate gradients minimizer\n");
953
	Rprintf("    %d function evaluations used\n", funcount);
990
	Rprintf("    %d function evaluations used\n", funcount);
954
	Rprintf("    %d gradient evaluations used\n", gradcount);
991
	Rprintf("    %d gradient evaluations used\n", gradcount);
955
    }
992
    }
956
    *fncount = funcount;
993
    *fncount = funcount;
957
    *grcount = gradcount;
994
    *grcount = gradcount;
958
}
995
}
959
 
996
 
960
void lbfgsb(int n, int m, double *x, double *l, double *u, int *nbd,
997
void lbfgsb(int n, int m, double *x, double *l, double *u, int *nbd,
961
	    double *Fmin, optimfn fminfn, optimgr fmingr, int *fail,
998
	    double *Fmin, optimfn fminfn, optimgr fmingr, int *fail,
962
	    void *ex, double factr, double pgtol,
999
	    void *ex, double factr, double pgtol,
963
	    int *fncount, int *grcount, int maxit, char *msg,
1000
	    int *fncount, int *grcount, int maxit, char *msg,
964
	    int trace, int nREPORT)
1001
	    int trace, int nREPORT)
965
{
1002
{
966
    char task[60];
1003
    char task[60];
967
    double f, *g, dsave[29], *wa;
1004
    double f, *g, dsave[29], *wa;
968
    int tr = -1, iter = 0, *iwa, isave[44], lsave[4];
1005
    int tr = -1, iter = 0, *iwa, isave[44], lsave[4];
969
 
1006
 
970
    if (nREPORT <= 0)
1007
    if (nREPORT <= 0)
971
	error("REPORT must be > 0 (method = \"L-BFGS-B\")");
1008
	error("REPORT must be > 0 (method = \"L-BFGS-B\")");
972
    switch(trace) {
1009
    switch(trace) {
973
    case 2: tr = 0; break;
1010
    case 2: tr = 0; break;
974
    case 3: tr = nREPORT; break;
1011
    case 3: tr = nREPORT; break;
975
    case 4: tr = 99; break;
1012
    case 4: tr = 99; break;
976
    case 5: tr = 100; break;
1013
    case 5: tr = 100; break;
977
    case 6: tr = 101; break;
1014
    case 6: tr = 101; break;
978
    default: tr = -1; break;
1015
    default: tr = -1; break;
979
    }
1016
    }
980
 
1017
 
981
    *fail = 0;
1018
    *fail = 0;
982
    g = vect(n);
1019
    g = vect(n);
983
    wa = vect(2*m*n+4*n+11*m*m+8*m);
1020
    wa = vect(2*m*n+4*n+11*m*m+8*m);
984
    iwa = (int *) R_alloc(3*n, sizeof(int));
1021
    iwa = (int *) R_alloc(3*n, sizeof(int));
985
    strcpy(task, "START");
1022
    strcpy(task, "START");
986
    while(1) {
1023
    while(1) {
987
	/* Main workhorse setulb() from ../appl/lbfgsb.c : */
1024
	/* Main workhorse setulb() from ../appl/lbfgsb.c : */
988
	setulb(n, m, x, l, u, nbd, &f, g, factr, &pgtol, wa, iwa, task,
1025
	setulb(n, m, x, l, u, nbd, &f, g, factr, &pgtol, wa, iwa, task,
989
	       tr, lsave, isave, dsave);
1026
	       tr, lsave, isave, dsave);
990
/*	Rprintf("in lbfgsb - %s\n", task);*/
1027
/*	Rprintf("in lbfgsb - %s\n", task);*/
991
	if (strncmp(task, "FG", 2) == 0) {
1028
	if (strncmp(task, "FG", 2) == 0) {
992
	    f = fminfn(n, x, ex);
1029
	    f = fminfn(n, x, ex);
993
	    if (!R_FINITE(f))
1030
	    if (!R_FINITE(f))
994
		error("L-BFGS-B needs finite values of fn");
1031
		error("L-BFGS-B needs finite values of fn");
995
	    fmingr(n, x, g, ex);
1032
	    fmingr(n, x, g, ex);
996
	} else if (strncmp(task, "NEW_X", 5) == 0) {
1033
	} else if (strncmp(task, "NEW_X", 5) == 0) {
997
	    if(trace == 1 && (iter % nREPORT == 0)) {
1034
	    if(trace == 1 && (iter % nREPORT == 0)) {
998
		Rprintf("iter %4d value %f\n", iter, f);
1035
		Rprintf("iter %4d value %f\n", iter, f);
999
	    }
1036
	    }
1000
	    if (++iter > maxit) {
1037
	    if (++iter > maxit) {
1001
		*fail = 1;
1038
		*fail = 1;
1002
		break;
1039
		break;
1003
	    }
1040
	    }
1004
	} else if (strncmp(task, "WARN", 4) == 0) {
1041
	} else if (strncmp(task, "WARN", 4) == 0) {
1005
	    *fail = 51;
1042
	    *fail = 51;
1006
	    break;
1043
	    break;
1007
	} else if (strncmp(task, "CONV", 4) == 0) {
1044
	} else if (strncmp(task, "CONV", 4) == 0) {
1008
	    break;
1045
	    break;
1009
	} else if (strncmp(task, "ERROR", 5) == 0) {
1046
	} else if (strncmp(task, "ERROR", 5) == 0) {
1010
	    *fail = 52;
1047
	    *fail = 52;
1011
	    break;
1048
	    break;
1012
	} else { /* some other condition that is not supposed to happen */
1049
	} else { /* some other condition that is not supposed to happen */
1013
	    *fail = 52;
1050
	    *fail = 52;
1014
	    break;
1051
	    break;
1015
	}
1052
	}
1016
    }
1053
    }
1017
    *Fmin = f;
1054
    *Fmin = f;
1018
    *fncount = *grcount = isave[33];
1055
    *fncount = *grcount = isave[33];
1019
    if (trace) {
1056
    if (trace) {
1020
	Rprintf("final  value %f \n", *Fmin);
1057
	Rprintf("final  value %f \n", *Fmin);
1021
	if (iter < maxit && *fail == 0) Rprintf("converged\n");
1058
	if (iter < maxit && *fail == 0) Rprintf("converged\n");
1022
	else Rprintf("stopped after %i iterations\n", iter);
1059
	else Rprintf("stopped after %i iterations\n", iter);
1023
    }
1060
    }
1024
    strcpy(msg, task);
1061
    strcpy(msg, task);
1025
}
1062
}
1026
 
1063
 
1027
 
1064
 
1028
#define E1 1.7182818  /* exp(1.0)-1.0 */
1065
#define E1 1.7182818  /* exp(1.0)-1.0 */
1029
#define STEPS 100
1066
#define STEPS 100
1030
 
1067
 
1031
void samin(int n, double *pb, double *yb, optimfn fminfn, int maxit,
1068
void samin(int n, double *pb, double *yb, optimfn fminfn, int maxit,
1032
	   int tmax, double ti, int trace, void *ex)
1069
	   int tmax, double ti, int trace, void *ex)
1033
 
1070
 
1034
/* Given a starting point pb[0..n-1], simulated annealing minimization
1071
/* Given a starting point pb[0..n-1], simulated annealing minimization
1035
   is performed on the function fminfn. The starting temperature
1072
   is performed on the function fminfn. The starting temperature
1036
   is input as ti. To make sann work silently set trace to zero.
1073
   is input as ti. To make sann work silently set trace to zero.
1037
   sann makes in total maxit function evaluations, tmax
1074
   sann makes in total maxit function evaluations, tmax
1038
   evaluations at each temperature. Returned quantities are pb
1075
   evaluations at each temperature. Returned quantities are pb
1039
   (the location of the minimum), and yb (the minimum value of
1076
   (the location of the minimum), and yb (the minimum value of
1040
   the function func).  Author: Adrian Trapletti
1077
   the function func).  Author: Adrian Trapletti
1041
*/
1078
*/
1042
{
1079
{
1043
    long i, j;
1080
    long j;
1044
    int k, its, itdoc;
1081
    int k, its, itdoc;
1045
    double t, y, dy, ytry, scale;
1082
    double t, y, dy, ytry, scale;
1046
    double *p, *dp, *ptry;
1083
    double *p, *dp, *ptry;
1047
 
1084
 
1048
    p = vect (n); dp = vect (n); ptry = vect (n);
1085
    p = vect (n); dp = vect (n); ptry = vect (n);
1049
    GetRNGstate();
1086
    GetRNGstate();
1050
    *yb = fminfn (n, pb, ex);  /* init best system state pb, *yb */
1087
    *yb = fminfn (n, pb, ex);  /* init best system state pb, *yb */
1051
    if (!R_FINITE(*yb)) *yb = big;
1088
    if (!R_FINITE(*yb)) *yb = big;
1052
    for (j = 0; j < n; j++) p[j] = pb[j];
1089
    for (j = 0; j < n; j++) p[j] = pb[j];
1053
    y = *yb;  /* init system state p, y */
1090
    y = *yb;  /* init system state p, y */
1054
    if (trace)
1091
    if (trace)
1055
    {
1092
    {
1056
	Rprintf ("sann objective function values\n");
1093
	Rprintf ("sann objective function values\n");
1057
	Rprintf ("initial       value %f\n", *yb);
1094
	Rprintf ("initial       value %f\n", *yb);
1058
    }
1095
    }
1059
    scale = 1.0/ti;
1096
    scale = 1.0/ti;
1060
    its = itdoc = 1;
1097
    its = itdoc = 1;
1061
    while (its < maxit) { /* cool down system */
1098
    while (its < maxit) {  /* cool down system */
1062
	t = ti/log((double)its + E1);  /* temperature annealing schedule */
1099
	t = ti/log((double)its + E1);  /* temperature annealing schedule */
1063
	k = 1;
1100
	k = 1;
1064
	while ((k <= tmax) && (its < maxit))  /* iterate at constant temperature */
1101
	while ((k <= tmax) && (its < maxit))  /* iterate at constant temperature */
1065
	{
1102
	{
1066
	    for (i = 0; i < n; i++)
-
 
1067
		dp[i] = scale * t * norm_rand();  /* random perturbation */
-
 
1068
	    for (i = 0; i < n; i++)
-
 
1069
		ptry[i] = p[i] + dp[i];  /* new candidate point */
1103
            genptry(n, p, ptry, scale * t, ex);  /* generate new candidate point */
1070
	    ytry = fminfn (n, ptry, ex);
1104
	    ytry = fminfn (n, ptry, ex);
1071
	    if (!R_FINITE(ytry)) ytry = big;
1105
	    if (!R_FINITE(ytry)) ytry = big;
1072
	    dy = ytry - y;
1106
	    dy = ytry - y;
1073
	    if ((dy <= 0.0) || (unif_rand() < exp(-dy/t))) {  /* accept new point? */
1107
	    if ((dy <= 0.0) || (unif_rand() < exp(-dy/t))) {  /* accept new point? */
1074
		for (j = 0; j < n; j++) p[j] = ptry[j];
1108
		for (j = 0; j < n; j++) p[j] = ptry[j];
1075
		y = ytry;  /* update system state p, y */
1109
		y = ytry;  /* update system state p, y */
1076
		if (y <= *yb)  /* if system state is best, then update best system state pb, *yb */
1110
		if (y <= *yb)  /* if system state is best, then update best system state pb, *yb */
1077
		{
1111
		{
1078
		    for (j = 0; j < n; j++) pb[j] = p[j];
1112
		    for (j = 0; j < n; j++) pb[j] = p[j];
1079
		    *yb = y;
1113
		    *yb = y;
1080
		}
1114
		}
1081
	    }
1115
	    }
1082
	    its++; k++;
1116
	    its++; k++;
1083
	}
1117
	}
1084
	if ((trace) && ((itdoc % STEPS) == 0))
1118
	if ((trace) && ((itdoc % STEPS) == 0))
1085
	    Rprintf("iter %8d value %f\n", its - 1, *yb);
1119
	    Rprintf("iter %8d value %f\n", its - 1, *yb);
1086
	itdoc++;
1120
	itdoc++;
1087
    }
1121
    }
1088
    if (trace)
1122
    if (trace)
1089
    {
1123
    {
1090
	Rprintf ("final         value %f\n", *yb);
1124
	Rprintf ("final         value %f\n", *yb);
1091
	Rprintf ("sann stopped after %d iterations\n", its - 1);
1125
	Rprintf ("sann stopped after %d iterations\n", its - 1);
1092
    }
1126
    }
1093
    PutRNGstate();
1127
    PutRNGstate();
1094
}
1128
}
1095
 
1129
 
1096
#undef E1
1130
#undef E1
1097
#undef STEPS
1131
#undef STEPS