Merging model type implementation into the trunk.
[openmx:openmx.git] / R / MxModel.R
1 #
2 #   Copyright 2007-2009 The OpenMx Project
3 #
4 #   Licensed under the Apache License, Version 2.0 (the "License");
5 #   you may not use this file except in compliance with the License.
6 #   You may obtain a copy of the License at
7
8 #        http://www.apache.org/licenses/LICENSE-2.0
9
10 #   Unless required by applicable law or agreed to in writing, software
11 #   distributed under the License is distributed on an "AS IS" BASIS,
12 #   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 #   See the License for the specific language governing permissions and
14 #   limitations under the License.
15
16
17 setClass(Class = "MxModel",\r
18         representation = representation(
19                 name = "character",
20                 matrices = "list",
21                 algebras = "list",
22                 constraints = "list",
23                 latentVars = "character",\r
24                 manifestVars = "character",\r
25                 data = "MxData",
26                 submodels = "list",
27                 objective = "MxObjective",
28                 independent = "logical",
29                 output = "list"
30 ))
31
32 omxModelTypes[['raw']] <- "MxModel"
33 \r
34 setMethod("initialize", "MxModel",\r
35         function(.Object, name = omxUntitledName(),  
36                 latentVars = character(), manifestVars = character(), 
37                 matrices = list(), algebras = list(), 
38                 constraints = list(), data = NULL, submodels = list(), 
39                 objective = NULL, independent = FALSE) {
40                 .Object@name <- name\r
41                 .Object@latentVars <- latentVars\r
42                 .Object@manifestVars <- manifestVars\r
43                 .Object@matrices <- matrices\r
44                 .Object@algebras <- algebras
45                 .Object@constraints <- constraints
46                 .Object@data <- data
47                 .Object@submodels <- submodels
48                 .Object@objective <- objective
49                 .Object@independent <- independent
50                 .Object@output <- list()
51                 .Object <- omxInitModel(.Object)
52                 return(.Object)\r
53         }\r
54 )\r
55
56 # Begin declaration of generics
57
58 setGeneric("omxInitModel", function(model) {
59         return(standardGeneric("omxInitModel")) } )
60
61 setGeneric("omxModelBuilder", function(model, lst, name, 
62         manifestVars, latentVars, remove, independent) {
63         return(standardGeneric("omxModelBuilder")) } )
64
65 setGeneric("omxTypeName", function(model) { \r
66         return(standardGeneric("omxTypeName")) \r
67 })
68
69 # End declaration of generics
70
71 setMethod("[[", "MxModel",\r
72         function(x, i, j, ..., drop = FALSE) {\r
73                 return(omxExtractMethod(x, i))\r
74         }\r
75 )
76 \r
77 setReplaceMethod("[[", "MxModel",\r
78         function(x, i, j, value) {
79                 return(omxReplaceMethod(x, i, value))
80         }\r
81 )
82
83 omxExtractMethod <- function(model, index) {
84         first <- model@matrices[[index]]
85         second <- model@algebras[[index]]
86         third <- model@submodels[[index]]
87         fourth <- model@constraints[[index]]
88         if (!is.null(model@objective) && index == model@objective@name) {
89                 return(model@objective)
90         } else if (!is.null(model@data) && index == model@data@name) {
91                 return(model@data)
92         } else if (!is.null(first)) {
93                 return(first)
94         } else if (!is.null(second)) {
95                 return(second)
96         } else if (!is.null(third)) {
97                 return(third)
98         } else {
99                 return(fourth)
100         }
101 }
102
103 omxReplaceMethod <- function(model, index, value) {
104         current <- model[[index]]
105         if (is.null(current) && is.null(value)) {
106                 return(model)
107         }
108         if(index == model@name) {
109                 stop(paste(omxQuotes(index), 
110                         "is already used as the name of the model"), call. = FALSE)
111         }
112         if(!is.null(current) && !is.null(value) && 
113                         !omxSameType(current, value)) {
114                 stop(paste("There already exists an object", 
115                                 omxQuotes(index), 
116                                 "in this model of different type"), call. = FALSE)
117         }
118         if(!is.null(value)) {
119                 value@name <- index
120                 test <- value
121         } else {
122                 test <- current
123         }
124         if (is(test,"MxMatrix")) {
125                 model@matrices[[index]] <- value
126         } else if (is(test,"MxAlgebra")) {
127                 model@algebras[[index]] <- value
128         } else if (is(test,"MxModel")) {
129                 model@submodels[[index]] <- value       
130         } else if (is(test,"MxObjective")) {
131                 model@objective <- value
132         } else if (is(test,"MxData")) {
133                 model@data <- value
134         } else if (is(test,"MxConstraint")) {
135                 model@constraints[[index]] <- value
136         } else {
137                 stop(paste(test, "is of unknown value for replacement using name",
138                         index, "in model", model@name), call. = FALSE)
139         }
140         return(model)
141 }
142
143 omxSameType <- function(a, b) {
144         return( (is(a, "MxModel") && is(b, "MxModel")) ||
145                         (is(a, "MxMatrix") && is(b, "MxMatrix")) ||
146                         (is(a, "MxAlgebra") && is(b, "MxAlgebra")) ||
147                         (is(a, "MxObjective") && is(b, "MxObjective")) ||
148                         (is(a, "MxConstraint") && is(b, "MxConstraint")) ||
149                         (is(a, "MxData") && is(b, "MxData")))
150 }\r
151 \r
152 mxModel <- function(model = NA, ..., manifestVars = NA, latentVars = NA,
153         remove = FALSE, independent = NA, type = NA, name = NA) {
154         retval <- firstArgument(model)
155         first <- retval[[1]]
156         model <- retval[[2]]
157         model <- typeArgument(model, type)
158         lst <- c(first, list(...))
159         lst <- mappendHelper(lst, list())
160         model <- omxModelBuilder(model, lst, name, manifestVars,
161                 latentVars, remove, independent)
162         return(model)\r
163 }\r
164 firstArgument <- function(model) {
165         first <- NULL
166         defaultType <- omxModelTypes[[getOption("mxDefaultType")]]
167         if (typeof(model) != "S4" && is.na(model)) {\r
168                 model <- new(defaultType)       \r
169         } else if (typeof(model) == "character") {
170                 model <- new(defaultType, name = model)
171         } else if(!is(model, "MxModel")) {
172                 if(isS4(model)) {
173                         first <- model
174                 } else {
175                         first <- list(model)
176                 }
177                 model <- new(defaultType)
178         }
179         return(list(first, model))
180 }
181
182 typeArgument <- function(model, type) {
183         if (!is.na(type)) {
184                 if (is.null(omxModelTypes[[type]])) {
185                         stop(paste("The model type", omxQuotes(type), 
186                                 "is not in the the list of acceptable types:",
187                                 omxQuotes(names(omxModelTypes))), call. = FALSE)
188                 }
189                 typename <- omxModelTypes[[type]]
190                 class(model) <- typename
191                 model <- omxInitModel(model)
192         }
193         return(model)
194 }
195
196 omxGenericModelBuilder <- function(model, lst, name, 
197         manifestVars, latentVars, remove, independent) {
198         model <- variablesArgument(model, manifestVars, latentVars, remove)
199         model <- listArgument(model, lst, remove)
200         model <- independentArgument(model, independent)
201         model <- nameArgument(model, name)
202         return(model)
203 }
204
205 variablesArgument <- function(model, manifestVars, latentVars, remove) {
206         if (single.na(manifestVars)) {
207                 manifestVars <- character()
208         }
209         if (single.na(latentVars)) {
210                 latentVars <- character()
211         }
212         if (remove == TRUE) {
213
214         } else if (length(manifestVars) + length(latentVars) > 0) {
215                 latentVars <- as.character(latentVars)
216                 manifestVars <- as.character(manifestVars)
217                 omxCheckVariables(model, latentVars, manifestVars)
218                 model <- omxAddVariables(model, latentVars, manifestVars)
219         }
220         return(model)
221 }
222
223 listArgument <- function(model, lst, remove) {
224         if(remove == TRUE) {
225                 model <- omxRemoveEntries(model, lst)\r
226         } else {
227                 model <- omxAddEntries(model, lst)
228         }
229         return(model)
230 }
231
232 independentArgument <- function(model, independent) {
233         if(!is.na(independent)) {
234                 model@independent <- independent
235         }
236         return(model)
237 }
238
239 nameArgument <- function(model, name) {
240         if(!is.na(name)) {
241                 model@name <- name
242         }
243         return(model)
244 }
245
246 omxCheckVariables <- function(model, latentVars, manifestVars) {
247         common <- intersect(latentVars, manifestVars)
248         if (length(common) > 0) {
249                 stop(paste("The following variables cannot",
250                         "be both latent and manifest:",
251                         omxQuotes(common)), call. = FALSE)
252         }
253         common <- intersect(model@latentVars, manifestVars)
254         if (length(common) > 0) {
255                 stop(paste("The following variables cannot",
256                         "be both latent and manifest:",
257                         omxQuotes(common)), call. = FALSE)
258         }
259         common <- intersect(model@manifestVars, latentVars)
260         if (length(common) > 0) {
261                 stop(paste("The following variables cannot",
262                         "be both latent and manifest",
263                         omxQuotes(common)), call. = FALSE)
264         }
265         if (any(is.na(latentVars))) {
266                 stop("NA is not allowed as a latent variable", call. = FALSE)
267         }
268         if (any(is.na(manifestVars))) {
269                 stop("NA is not allowed as a manifest variable", call. = FALSE)
270         }
271 }
272
273 # Begin implementation of generics
274
275 setMethod("omxModelBuilder", "MxModel", omxGenericModelBuilder)
276
277 setMethod("omxInitModel", "MxModel", function(model) { 
278         return(model)
279 })
280
281 setMethod("omxTypeName", "MxModel", function(model) { 
282         return("unspecified")
283 })
284
285 # End implementation of generics
286
287 omxAddVariables <- function(model, latent, manifest) {
288         model@latentVars   <- union(model@latentVars, latent)
289         model@manifestVars <- union(model@manifestVars, manifest)
290         return(model)
291 }
292         \r
293 omxAddEntries <- function(model, entries) {\r
294         if (length(entries) == 0) {\r
295                 return(model)\r
296         }
297         tuple <- omxModelAddFilter(model, entries, list(), list())\r
298         namedEntities <- tuple[[1]]
299         bounds        <- tuple[[2]]\r
300         if (length(namedEntities) > 0) for(i in 1:length(namedEntities)) {\r
301                 model <- omxAddSingleNamedEntity(model, namedEntities[[i]])\r
302         }
303         model <- omxAddBounds(model, bounds)\r
304         return(model)\r
305 }\r
306 \r
307 omxRemoveEntries <- function(model, entries) {\r
308         if (length(entries) == 0) {\r
309                 return(model)\r
310         }\r
311         tuple <- omxModelRemoveFilter(model, entries, list(), list())
312         namedEntities <- tuple[[1]]
313         bounds        <- tuple[[2]]\r
314         if (length(namedEntities) > 0) for(i in 1:length(namedEntities)) {\r
315                 model <- omxRemoveSingleNamedEntity(model, namedEntities[[i]])\r
316         }
317         model <- omxRemoveBounds(model, bounds)\r
318         return(model)\r
319 }
320
321 mappendHelper <- function(lst, result) {\r
322         if (length(lst) == 0) {\r
323                 return(result)\r
324         } else if (length(lst) == 1) {
325                 len <- length(result)
326                 addition <- lst[[1]]
327                 if (is.list(addition)) {
328                         result <- append(result, addition)
329                 } else {
330                         result[[len + 1]] <- addition
331                 }
332                 return(result)\r
333         } else {
334                 len <- length(result)
335                 addition <- lst[[1]]
336                 if (is.list(addition)) {
337                         result <- append(result, addition)
338                 } else {
339                         result[[len + 1]] <- addition
340                 }
341                 return(mappendHelper(lst[2:length(lst)], result))\r
342         }
343 }
344
345 omxModelAddFilter <- function(model, entries, namedEntities, bounds) {\r
346         if (length(entries) == 0) {\r
347                 return(list(namedEntities, bounds))\r
348         }\r
349         head <- entries[[1]]
350         nLength <- length(namedEntities)
351         bLength <- length(bounds)
352         if (is.null(head)) {
353         } else if(isS4(head) && ("name" %in% slotNames(head))) {
354                 namedEntities[[nLength + 1]] <- head
355         } else if(is(head, "MxBounds")) {
356                 bounds[[bLength + 1]] <- head
357         } else if(omxIsPath(head)) {
358                 stop(paste("The model type of model",
359                         omxQuotes(model@name), "does not recognize paths."),
360                         call. = FALSE)
361         } else {\r
362                 stop(paste("Cannot add the following item into the model:", 
363                         head), call. = FALSE)\r
364         }\r
365         return(omxModelAddFilter(model, entries[-1], namedEntities, bounds))\r
366 }\r
367
368 omxModelRemoveFilter <- function(model, entries, names, bounds) {\r
369         if (length(entries) == 0) {\r
370                 return(list(names, bounds))\r
371         }\r
372         head <- entries[[1]]
373         nLength <- length(names)
374         bLength <- length(bounds)
375         if (is.null(head)) {
376         } else if(is.character(head) && (length(head) == 1)) {
377                 names[[nLength + 1]] <- head
378         } else if(is(head, "MxBounds")) {
379                 bounds[[bLength + 1]] <- head
380         } else if(omxIsPath(head)) {
381                 stop(paste("The model type of model",
382                         omxQuotes(model@name), "does not recognize paths."),
383                         call. = FALSE)
384         } else {\r
385                 stop(paste("Cannot remove the following item from the model:", 
386                         head), call. = FALSE)\r
387         }\r
388         return(omxModelRemoveFilter(model, entries[-1], names, bounds))\r
389 }
390
391 omxAddSingleNamedEntity <- function(model, entity) {
392         model[[entity@name]] <- entity
393         return(model)
394 }\r
395
396 omxRemoveSingleNamedEntity <- function(model, name) {
397         model[[name]] <- NULL
398         return(model)
399 }