File: csem.R

package info (click to toggle)
r-cran-sem 3.1.16-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 936 kB
  • sloc: ansic: 2,241; cpp: 1,646; sh: 4; makefile: 2
file content (453 lines) | stat: -rw-r--r-- 16,783 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
# File:   csem.R
# Author: Zhenghua Nie 
# Date:   Mon 26 Dec 2011 23:54:22 EST
#
#
#
# Copyright (C) 2011 Zhenghua Nie. All Rights Reserved.
# This code is published under GNU GENERAL PUBLIC LICENSE.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License,  or
# (at your option) any later version.
#      
# This program is distributed WITHOUT ANY WARRANTY. See the
# GNU General Public License for more details.
#           
# If you do not have a copy of the GNU General Public License,  
# write to the Free Software Foundation, Inc., 
# 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA


# The following function is a wrapper to compute the objective function and its gradient.
# If hessian=TRUE,  csem will return Hessian computed by the numerical method,  but
# is flexible to return Hessian computed by the analytical solution.
CompiledObjective <- function(par, model.description, gradient=TRUE, hessian=FALSE, objective=c("objectiveML", "objectiveGLS", "objectiveFIML", "objectivelogLik"), ...)
{
		if(missing(objective)) objective <- "objectiveML"
		objective <- match.arg(objective)

		res <- csem(model=model.description,  start=par, objective=objective,  opt.flag=0,  gradient=gradient,  opts=list("hessian"=hessian, "check.analyticals"=FALSE), ...)
		ret <- list();
		ret$f <- res$minimum
		ret$parameters <- res$estimate
		ret$C <- res$C
		ret$A <- res$A
		ret$P <- res$P
		ret$gradient <- res$gradient
		ret$hessian <- res$hessian

		return(ret)
}

msemCompiledObjective <- function(par, model.description, gradient=TRUE, hessian=FALSE, objective=c("objectiveML", "objectiveGLS", "objectiveFIML"), ...)
{
		if(missing(objective)) objective <- "objectiveML"
		objective <- match.arg(objective)

		res <- cmsem(model=model.description,  start=par, objective=objective,  opt.flag=0, gradient=gradient,   opts=list("hessian"=hessian, "check.analyticals"=FALSE), ...)
		AA <- PP <- CC <- vector(model.description$G,  mode="list")
		indAP <- 1
		indC <- 1
		ff <- numeric(model.description$G)
		for(g in 1:model.description$G)
		{
				m <- model.description$m[g]
				n <- model.description$n[g]
				AA[[g]] <- matrix(res$A[indAP:(indAP+m*m-1)], m, m);
				PP[[g]] <- matrix(res$P[indAP:(indAP+m*m-1)], m, m);
				indAP <- indAP + m*m;
				CC[[g]] <- matrix(res$C[indC:(indC+n*n-1)], n, n);
				indC <- indC + n*n;
				ff[g] <- as.numeric(res$f[g])
		}
		ret <- list();
		ret$f <- res$minimum
		ret$parameters <- res$estimate
		ret$C <- CC
		ret$A <- AA
		ret$P <- PP
		ret$ff <- ff
		ret$gradient <- res$gradient
		ret$hessian <- res$hessian

		return(ret)
}

# The wrapper function for solving optimization problems. Please note that the objective function is written in C/C++,  we need to know the name.
CompiledSolve <- function(model.description, start, objective=c("objectiveML", "objectiveGLS", "objectiveFIML", "objectivelogLik"),  gradient=TRUE, typsize=rep(1.0, length(start)), debug=FALSE, maxiter=100,...)
{
		if(missing(objective)) objective <- "objectiveML"
		objective <- match.arg(objective)

		stepmax=max(1000.0 * sqrt(sum((start/typsize)^2)),  1000.0)

		res <- csem(model=model.description, start, opt.flag=1, typsize=typsize,objective=objective,  
								gradient=gradient, 
								opts=list("iterlim"=maxiter, "print.level"=if(debug) 2 else 0,
													"hessian"=TRUE, "check.analyticals"=FALSE, "stepmax"=stepmax), ...)

		return(res)
}

# The wrapper function for solving optimization problems. Please note that the objective function is written in C/C++,  we need to know the name.
msemCompiledSolve <- function(model.description, start, objective=c("objectiveML", "objectiveGLS", "objectiveFIML"),  
															gradient=TRUE, 
															typsize=rep(1.0, length(start)), debug=FALSE, maxiter=100,gradtol=1e-6, ...)
{
		if(missing(objective)) objective <- "objectiveML"
		objective <- match.arg(objective)

		stepmax=max(1000.0 * sqrt(sum((start/typsize)^2)),  1000.0)

		res <- cmsem(model=model.description, start, opt.flag=1, typsize=typsize,objective=objective,  
								 gradient=gradient, 
								opts=list("iterlim"=maxiter, "print.level"=if(debug) 2 else 0,"gradtol"=gradtol, 
													"hessian"=TRUE, "check.analyticals"=FALSE, "stepmax"=stepmax), ...)

#reoraginize the matrix A,  P,  C 
		AA <- PP <- CC <- vector(model.description$G,  mode="list")
		indAP <- 1
		indC <- 1
		ff <- numeric(model.description$G)
		for(g in 1:model.description$G)
		{
				m <- as.integer(model.description$m[g])
				n <- as.integer(model.description$n[g])
				AA[[g]] <- matrix(as.numeric(res$A)[indAP:(indAP+m*m-1)], m, m);
				PP[[g]] <- matrix(as.numeric(res$P)[indAP:(indAP+m*m-1)], m, m);
				indAP <- indAP + m*m;
				CC[[g]] <- matrix(as.numeric(res$C)[indC:(indC+n*n-1)], n, n);
				indC <- indC + n*n;
				ff[g] <- as.numeric(res$f[g])
		}

		ret <- list();
		ret$minimum <- res$minimum
		ret$estimate <- res$estimate
		ret$gradient <- res$gradient
		ret$hessian <- res$hessian
		ret$code <- res$code
		ret$iterations <- res$iterations
		ret$C <- CC
		ret$A <- AA
		ret$P <- PP
		ret$ff <- ff

		return(ret)
}

print.f <- function(x,...)
{
		print(x,...);   # call R function "print" 
}

#optimze:0 we only compute the objective function,  gradients or hessian and return them.
# 
csem <- function(model=NULL, start=NULL,opt.flag=1,  typsize=rep(1, model$t), objective=c("objectiveML", "objectiveGLS", "objectiveFIML", "objectivelogLik", "test_objective"),  
								 gradient=TRUE, 
								 opts=list("hessian"=1, "fscale"=1, "gradtol"=1e-6, "steptol"=1e-6, "stepmax"=max(1000 * sqrt(sum((start/typsize)^2)),  1000), "iterlim"=100, 
													 "ndigit"=12,"print.level"=0, "check.analyticals"=1), 
								 csem.environment = new.env(), ...){

		environment(print.f) <- csem.environment; 
 ## Write wrappers around user-defined functions to pass additional
  ## arguments
  print.f.wrapper <- function(x){ print.f(x,...) }

		if(missing(model)) stop("Must provide the model.")
		if(missing(objective)) objective <- "objectiveML"
		objective <- match.arg(objective)
		if(missing(typsize) || is.null(typsize)) typsize <- rep(1, model$t)
		if(missing(start)) start <- rep(0.10, model$t)
		if(length(opts$print.level)==0) 
				print.level <- 0
		else 
				print.level <- as.integer(opts$print.level)
		if(print.level < 0 || print.level > 2) stop("'print.level' must be in {0, 1, 2}")


		## the following is for generating gradient.
		if(objective != "objectivelogLik")
		{
				arrows.1.seq <- model$ram[model$ram[, 1]==1 & model$ram[, 4]!=0,  4] 
				arrows.2.seq <- model$ram[model$ram[, 1]==2 & model$ram[, 4]!=0,  4]
		}

		# this function is modfied from ipoptr developed by Jelmer Ypma (http://www.ucl.ac.uk/~uctpjyy/ipoptr.html).
		# Please reference the license of ipoptr.
		get.option.types <- function(opts) {
				# define types of nlm options,  we should add all options here.
				nlm.option.types <- list(
																 "fscale"="numeric", 
																 "gradtol"="numeric", 
																 "steptol"="numeric", 
																 "stepmax"="numeric", 
																 "hessian"="integer", 
																 "iterlim"="integer", 
																 "ndigit"="integer", 
																 "print.level"="integer", 
																 "check.analyticals"="integer"
																 )


				# initialize list with options sorted by type
				converted.opts <- list( "integer"=list(), "string"=list(), "numeric"=list() )

				is.wholenumber <- function(x, tol = .Machine$double.eps^0.5)  abs(x - round(x)) < tol

				# check if we have at least 1 element in the list, otherwise the 
				# loop runs from 1 to down 0 and we get errors
				if ( length( opts ) > 0 ) {

						# loop over all options and give them the correct type
						for ( i in 1:length( opts ) ) {
								tmp.type <- nlm.option.types[[match( names(opts)[i], names(nlm.option.types) )]]
								if ( is.null( tmp.type ) ) {
										# determine type
										if ( is.character(opts[[i]]) ) {
												tmp.type <- "string"
										} else if ( is.wholenumber(opts[[i]]) ) {
												tmp.type <- "integer"
										} else {
												tmp.type <- "numeric"
										}
										cat( paste( "Warning: ", names(opts)[i], " is not a recognized option, we try to pass it to nlm as ", tmp.type, "\n" ) )
								}

								if ( tmp.type=="string" ) {
										converted.opts$string[[ names(opts)[i] ]] <- as.character(opts[[i]])
								} else if ( tmp.type=="integer" ) {
										converted.opts$integer[[ names(opts)[i] ]] <- as.integer(opts[[i]])
								} else if ( tmp.type=="numeric" ) {
										converted.opts$numeric[[ names(opts)[i] ]] <- as.numeric(opts[[i]])
								} else {
										stop(paste("Type of option ", names(opts)[i], " not recognized"))
								}
						}
				}

				return ( converted.opts )
		}

		if(objective != "objectivelogLik")
		{
				ret <- list( 
										"objective" = objective, 
										"gradient" = as.integer(gradient), 
										"opt.flg" = as.integer(opt.flag), 
										"start" = start, 
										"options" = get.option.types(opts), 
										"data" = model$data, 
										"pattern.number" = model$pattern.number, 
										"valid.data.patterns" = model$valid.data.patterns, 
										"S" = model$S, 
										"logdetS" = as.numeric(model$logdetS), 
										"invS" = model$invS, 
										"N" = as.integer(model$N), 
										"m" = as.integer(model$m), 
										"n" = as.integer(model$n), 
										"t" = as.integer(model$t), 
										"fixed" = model$fixed, 
										"ram" = model$ram, 
										"sel.free" = model$sel.free, 
										"arrows.1" = model$arrows.1, 
										"arrows.1.free" = model$arrows.1.free, 
										"one.head" = model$one.head, 
										"arrows.2t" = model$arrows.2t, 
										"arrows.2" = model$arrows.2, 
										"arrows.2.free" = model$arrows.2.free, 
										"unique.free.1" = model$unique.free.1, 
										"unique.free.2" = model$unique.free.2, 
										"J" = model$J, 
										"correct" = model$correct, 
										"param.names" = model$param.names, 
										"var.names" = model$var.names, 
										"one.free" = model$one.free, 
										"two.free" = model$two.free, 
										"raw" = as.integer(model$raw), 
										"arrows.1.seq" = arrows.1.seq, 
										"arrows.2.seq" = arrows.2.seq, 
										"typsize" = typsize, 
										"print.f" = print.f.wrapper, 
										"csem.environment"=csem.environment)
				attr(ret, "class") <- "csem"
		}
		else
		{
				ret <- list(
										"objective" = objective, 
										"gradient" = as.integer(gradient), 
										"opt.flg" = as.integer(opt.flag), 
										"start" = start, 
										"t" = length(start), 
										"options" = get.option.types(opts), 
										"data" = model$data, 
										"pattern.number" = model$pattern.number, 
										"valid.data.patterns" = model$valid.data.patterns, 
										"tri" = model$tri, 
										"posn.intercept" = model$posn.intercept, 
										"typsize" = typsize, 
										"print.f" = print.f.wrapper, 
										"csem.environment"=csem.environment
										)
		}
		# add the current call to the list
		# ret$call <- match.call()

		solution <- .Call("csemSolve", ret)

		# ret$environment <- NULL
		# ret$solution <- solution

		ret <- solution   #this is for simplifing the interface.
		# add solution variables to object
		#ret$status <- solution$status

		return(ret)
}

cmsem <- function(model=NULL, start=NULL,opt.flag=1,  typsize=rep(1, model$t), objective=c("objectiveML", "objectiveGLS", "objectiveFIML", "test_objective"),  
									gradient=TRUE, 
									opts=list("hessian"=1, "fscale"=1, "gradtol"=1e-6, "steptol"=1e-6, "stepmax"=max(1000 * sqrt(sum((start/typsize)^2)),  1000), "iterlim"=100, 
														"ndigit"=12,"print.level"=0, "check.analyticals"=1), 
									csem.environment = new.env(), ...){

		environment(print.f) <- csem.environment; 
 ## Write wrappers around user-defined functions to pass additional
  ## arguments
  print.f.wrapper <- function(x){ print.f(x,...) }

		if(missing(model)) stop("Must provide the model.")
		if(missing(objective)) objective <- "objectiveML"
		objective <- match.arg(objective)
		if(missing(typsize) || is.null(typsize)) typsize <- rep(1, model$t)
		if(missing(start)) start <- rep(0.10, model$t)
		if(length(opts$print.level)==0) 
				print.level <- 0
		else 
				print.level <- as.integer(opts$print.level)
		if(print.level < 0 || print.level > 2) stop("'print.level' must be in {0, 1, 2}")


		## the following is for generating gradient.
		G <- model$G
		arrows.1.seq <- arrows.2.seq <- vector(G, mode="list")
		for(g in 1:G)
		{
				arrows.1.seq[[g]] <- model$ram[[g]][model$ram[[g]][, 1]==1 & model$ram[[g]][, 4]!=0,  4] 
				arrows.2.seq[[g]] <- model$ram[[g]][model$ram[[g]][, 1]==2 & model$ram[[g]][, 4]!=0,  4]
		}

		get.option.types <- function(opts) {
				# define types of nlm options,  we should add all options here.
				nlm.option.types <- list(
																 "fscale"="numeric", 
																 "gradtol"="numeric", 
																 "steptol"="numeric", 
																 "stepmax"="numeric", 
																 "hessian"="integer", 
																 "iterlim"="integer", 
																 "ndigit"="integer", 
																 "print.level"="integer", 
																 "check.analyticals"="integer"
																 )


				# initialize list with options sorted by type
				converted.opts <- list( "integer"=list(), "string"=list(), "numeric"=list() )

				is.wholenumber <- function(x, tol = .Machine$double.eps^0.5)  abs(x - round(x)) < tol

				# check if we have at least 1 element in the list, otherwise the 
				# loop runs from 1 to down 0 and we get errors
				if ( length( opts ) > 0 ) {

						# loop over all options and give them the correct type
						for ( i in 1:length( opts ) ) {
								tmp.type <- nlm.option.types[[match( names(opts)[i], names(nlm.option.types) )]]
								if ( is.null( tmp.type ) ) {
										# determine type
										if ( is.character(opts[[i]]) ) {
												tmp.type <- "string"
										} else if ( is.wholenumber(opts[[i]]) ) {
												tmp.type <- "integer"
										} else {
												tmp.type <- "numeric"
										}
										cat( paste( "Warning: ", names(opts)[i], " is not a recognized option, we try to pass it to nlm as ", tmp.type, "\n" ) )
								}

								if ( tmp.type=="string" ) {
										converted.opts$string[[ names(opts)[i] ]] <- as.character(opts[[i]])
								} else if ( tmp.type=="integer" ) {
										converted.opts$integer[[ names(opts)[i] ]] <- as.integer(opts[[i]])
								} else if ( tmp.type=="numeric" ) {
										converted.opts$numeric[[ names(opts)[i] ]] <- as.numeric(opts[[i]])
								} else {
										stop(paste("Type of option ", names(opts)[i], " not recognized"))
								}
						}
				}

				return ( converted.opts )
		}

		ret <- list( 
								"objective" = objective, 
								"gradient" = as.integer(gradient), 
								"opt.flg" = as.integer(opt.flag), 
								"start" = start, 
								"options" = get.option.types(opts), 
								"G" = as.integer(model$G), 
								"data" = model$data, 
								"pattern.number" = model$pattern.number, 
								"valid.data.patterns" = model$valid.data.patterns, 
								"S" = model$S, 
								"logdetS" = model$logdetS, 
								"invS" = model$invS, 
								"N" = model$N, 
								"m" = model$m, 
								"n" = model$n, 
								"t" = as.integer(model$t), 
								"fixed" = model$fixed, 
								"ram" = model$ram, 
								"sel.free" = model$sel.free, 
								"arrows.1" = model$arrows.1, 
								"arrows.1.free" = model$arrows.1.free, 
								"one.head" = model$one.head, 
								"arrows.2t" = model$arrows.2t, 
								"arrows.2" = model$arrows.2, 
								"arrows.2.free" = model$arrows.2.free, 
								"unique.free.1" = model$unique.free.1, 
								"unique.free.2" = model$unique.free.2, 
								"J" = model$J, 
								"correct" = model$correct, 
								"param.names" = model$param.names, 
								"var.names" = model$var.names, 
								"one.free" = model$one.free, 
								"two.free" = model$two.free, 
								"raw" = as.integer(model$raw), 
								"arrows.1.seq" = arrows.1.seq, 
								"arrows.2.seq" = arrows.2.seq, 
								"typsize" = typsize, 
								"print.f" = print.f.wrapper, 
								"csem.environment"=csem.environment)
		attr(ret, "class") <- "cmsem"

		# add the current call to the list
		# ret$call <- match.call()

		solution <- .Call("cmsemSolve", ret)

		# ret$environment <- NULL
		# ret$solution <- solution

		ret <- solution   #this is for simplifing the interface.
		# add solution variables to object
		#ret$status <- solution$status

		return(ret)
}