Switch over to new structured Compute system
[openmx:openmx.git] / R / MxModelFunctions.R
1 #
2 #   Copyright 2007-2013 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 generateMatrixList <- function(model) {
18         matvalues <- lapply(model@matrices, generateMatrixValuesHelper)
19         matnames  <- names(model@matrices)
20         names(matvalues) <- matnames
21         references <- generateMatrixReferences(model)
22         retval <- mapply(function(x,y) { c(list(x), y) }, 
23                         matvalues, references, SIMPLIFY = FALSE)
24         return(retval)
25 }
26
27 generateAlgebraList <- function(model) {
28         mNames <- names(model@matrices)
29         aNames <- append(names(model@algebras), names(model@fitfunctions))      
30         mNumbers <- as.list(as.integer(-1 : (-length(mNames))))
31         aNumbers <- as.list(as.integer(0 : (length(aNames) - 1)))
32         names(mNumbers) <- mNames
33         names(aNumbers) <- aNames
34         retval <- lapply(model@algebras, generateAlgebraHelper, 
35                 mNumbers, aNumbers)
36     return(retval)
37 }
38
39 findDependencies <- function(triple, flatModel, dependencies) {
40         mNames <- names(flatModel@matrices)
41         matrixNum <- triple[[1]] + 1
42         matrixName <- mNames[[matrixNum]]
43         return(dependencies[[matrixName]])      
44 }
45
46         
47 isExpectation <- function(name) {
48         return(length(grep("expectation", name, fixed=TRUE)) > 0)
49 }
50
51 parameterDependencyList <- function(pList, flatModel, dependencies) {
52         if (length(pList) == 2) {
53                 retval <- list(pList[[1]], pList[[2]], integer())
54                 return(retval)
55         }
56         locations <- pList[3:length(pList)]
57         deps <- lapply(locations, findDependencies, flatModel, dependencies)
58         depnames <- Reduce(union, deps, character())
59         depnames <- Filter(Negate(isExpectation), depnames)
60         depnumbers <- sapply(depnames, doLocateIndex, flatModel, flatModel@name, USE.NAMES=FALSE)
61         depnumbers <- as.integer(depnumbers)
62         retval <- list(pList[[1]], pList[[2]], depnumbers)
63         return(append(retval, locations))
64 }
65
66 generateParameterList <- function(flatModel, dependencies) {
67         result <- list()
68         if (length(flatModel@matrices) == 0) {
69                 return(result)
70         }
71         for(i in 1:length(flatModel@matrices)) {
72                 matrix <- flatModel@matrices[[i]]
73                 result <- generateParameterListHelper(
74                         matrix, result, i - 1L)
75         }
76         result <- lapply(result, parameterDependencyList, flatModel, dependencies)
77         return(result)
78 }
79
80 generateDefinitionList <- function(flatModel, dependencies) {
81         result <- list()
82         defLocations <- generateDefinitionLocations(flatModel@datasets)
83         if (length(flatModel@matrices) == 0) {
84                 return(result)
85         }
86         for(i in 1:length(flatModel@matrices)) {
87                 result <- generateDefinitionListHelper(
88                         flatModel@matrices[[i]], 
89                         result, defLocations, i - 1L)
90         }
91         result <- lapply(result, parameterDependencyList, flatModel, dependencies)
92         return(result)
93 }
94
95 generateValueList <- function(mList, pList) {
96         mList <- lapply(mList, function(x) { x[[1]] })
97         retval <- vector()
98         if (length(pList) == 0) {
99                 return(retval)
100         }
101         for(i in 1:length(pList)) {
102                 parameter <- pList[[i]]
103                 parameter <- parameter[4:length(parameter)] # Remove (min, max, dependencies)
104                 if (length(parameter) > 1) {
105                         values <- sapply(parameter, generateValueHelper, mList)
106                         if (!all(values == values[[1]])) {
107                                 warning(paste('Parameter',i,'has multiple start values.',
108                                         'Selecting', values[[1]]))
109                         }
110                         retval[i] <- values[[1]]
111                 } else {
112                         retval[i] <- generateValueHelper(parameter[[1]], mList)
113                 }
114         }
115         return(retval)  
116 }
117
118 generateValueHelper <- function(triple, mList) {
119         mat <- triple[1] + 1
120         row <- triple[2] + 1
121         col <- triple[3] + 1
122         val <- mList[[mat]][row,col]
123         if (is.na(val)) {
124                 stop(paste("Starting value in ",names(mList)[[mat]],
125                            "[",row,",",col,"] is missing", sep=""))
126         }
127         return(val)
128 }
129
130 imxUpdateModelValues <- function(model, flatModel, pList, values) {
131         if(length(pList) != length(values)) {
132                 stop(paste("This model has", length(pList), 
133                         "parameters, but you have given me", length(values),
134                         "values"))
135         }
136         if (length(pList) == 0) {
137                 return(model)
138         }
139         for(i in 1:length(pList)) {
140                 parameters <- pList[[i]]
141                 parameters <- parameters[4:length(parameters)] # Remove min, max, and dependencies
142                 model <- updateModelValuesHelper(parameters, values[[i]], flatModel, model)
143     }
144         return(model)
145 }
146
147 updateModelValuesHelper <- function(triples, value, flatModel, model) {
148         for(i in 1:length(triples)) {
149                 triple <- triples[[i]]
150                 mat <- triple[1] + 1
151                 row <- triple[2] + 1
152                 col <- triple[3] + 1
153                 name <- flatModel@matrices[[mat]]@name
154                 model[[name]]@values[row,col] <- value
155         }
156         return(model)
157 }
158
159 removeTail <- function(lst, tailSize) {
160     newEnd <- length(lst) - tailSize
161     if (newEnd == 0) {
162         return(list())
163     } else {
164         return(lst[1 : newEnd])
165     }
166 }
167
168 updateModelMatrices <- function(model, flatModel, values) {
169         mList <- names(flatModel@matrices)
170         if (length(mList) != length(values)) {
171                 stop(paste("This model has", length(mList), 
172                         "matrices, but the backend has returned", length(values),
173                         "values"))
174         }
175         if (length(values) == 0) {
176                 return(model)
177         }
178         model <- updateModelEntitiesHelper(mList, values, model)
179         return(model)
180 }
181
182
183 updateModelAlgebras <- function(model, flatModel, values) {
184         aNames <- names(flatModel@algebras)
185         oNames <- names(flatModel@fitfunctions)
186         aList <- append(aNames, oNames)
187         if(length(aList) != length(values)) {
188                 stop(paste("This model has", length(aList), 
189                         "algebras, but the backend has returned", length(values),
190                         "values"))
191         }
192         if (length(aList) == 0) {
193                 return(model)
194         }
195         model <- updateModelEntitiesHelper(aList, values, model)
196         return(model)
197 }
198
199
200 updateModelEntitiesTargetModel <- function(model, entNames, values, modelNameMapping) {
201     nextName <- model@name
202     selectEnt <- entNames[modelNameMapping == nextName]
203     selectVal <- values[modelNameMapping == nextName]
204     if (length(selectEnt) > 0) {
205                 for(i in 1:length(selectEnt)) {
206                         name <- selectEnt[[i]]
207                         candidate <- model[[name]]
208                         value <- selectVal[[i]]
209                         if (!is.null(candidate) && (length(value) > 0)
210                                 && !is.nan(value)) {
211                                 if (is(candidate, "MxAlgebra")) {
212                                         dimnames(value) <- dimnames(candidate)
213                                         candidate@result <- value
214                                 } else if (is(candidate,"MxFitFunction")) {
215                                         candidate <- fitFunctionReadAttributes(candidate, value)
216                                 } else if(is(candidate, "MxMatrix")) {
217                                         dimnames(value) <- dimnames(candidate)
218                                         candidate@values <- value
219                                 }
220                                 model[[name]] <- candidate
221                         }
222                 }
223         }
224     if (length(model@submodels) > 0) {
225         model@submodels <- lapply(model@submodels, 
226             updateModelEntitiesTargetModel, entNames, values, modelNameMapping)
227     }
228         return(model)
229 }
230
231 updateModelEntitiesHelper <- function(entNames, values, model) {
232     modelNameMapping <- sapply(entNames, getModelNameString)
233     model <- updateModelEntitiesTargetModel(model, entNames, 
234                 values, modelNameMapping)
235     return(model)
236 }
237
238 imxLocateIndex <- function(model, name, referant) {
239         if (length(name) == 0) return(name)
240         if (is.na(name)) { return(as.integer(name)) }
241         mNames <- names(model@matrices)
242         aNames <- names(model@algebras)
243         fNames <- names(model@fitfunctions)
244         eNames <- names(model@expectations)
245         oNames <- names(model@computes)
246         dNames <- names(model@datasets)         
247         matrixNumber <- match(name, mNames)
248         algebraNumber <- match(name, append(aNames, fNames))
249         dataNumber <- match(name, dNames)
250         expectationNumber <- match(name, eNames)
251         computeNumber <- match(name, oNames)
252         if (is.na(matrixNumber) && is.na(algebraNumber) 
253                 && is.na(dataNumber) && is.na(expectationNumber) &&
254             is.na(computeNumber)) {
255                 msg <- paste("The reference", omxQuotes(name),
256                         "does not exist.  It is used by the named entity",
257                         omxQuotes(referant),".")
258                 stop(msg, call.=FALSE)
259         } else if (!is.na(matrixNumber)) {
260                 return(- matrixNumber)
261         } else if (!is.na(dataNumber)) {
262                 return(dataNumber - 1L)
263         } else if (!is.na(expectationNumber)) {
264                 return(expectationNumber - 1L)
265         } else if (!is.na(computeNumber)) {
266                 return(computeNumber - 1L)
267         } else {
268                 return(algebraNumber - 1L)
269         }
270 }
271
272 imxPreprocessModel <- function(model) {
273         model@matrices <- lapply(model@matrices, findSquareBrackets)
274         model@submodels <- lapply(model@submodels, imxPreprocessModel)
275         return(model)
276 }
277
278
279 imxCheckMatrices <- function(model) {
280         matrices <- model@matrices
281         lapply(matrices, imxVerifyMatrix)
282         submodels <- imxDependentModels(model)
283         lapply(submodels, imxCheckMatrices)
284 }