[dependency-tracking] initial commit of bookkeeping.
[openmx:openmx.git] / R / MxModelFunctions.R
1 #
2 #   Copyright 2007-2012 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@objectives))        
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 parameterDependencyList <- function(pList, flatModel, dependencies) {
47         if (length(pList) == 2) {
48                 retval <- list('min' = pList[['min']], 'max' = pList[['max']], 'dependencies' = integer())
49                 return(retval)
50         }
51         locations <- pList[3:length(pList)]
52         deps <- lapply(locations, findDependencies, flatModel, dependencies)
53         depnames <- Reduce(union, deps, character())
54         depnumbers <- sapply(depnames, doLocateIndex, flatModel, flatModel@name, USE.NAMES=FALSE)
55         depnumbers <- as.integer(depnumbers)
56         retval <- list('min' = pList[['min']], 'max' = pList[['max']], 'dependencies' = depnumbers)
57         return(append(retval, locations))
58 }
59
60 generateParameterList <- function(flatModel, dependencies) {
61         result <- list()
62         if (length(flatModel@matrices) == 0) {
63                 return(result)
64         }
65         for(i in 1:length(flatModel@matrices)) {
66                 matrix <- flatModel@matrices[[i]]
67                 result <- generateParameterListHelper(
68                         matrix, result, i - 1L)
69         }
70         result <- lapply(result, parameterDependencyList, flatModel, dependencies)
71         return(result)
72 }
73
74 generateDefinitionList <- function(flatModel) {
75         result <- list()
76         defLocations <- generateDefinitionLocations(flatModel@datasets)
77         if (length(flatModel@matrices) == 0) {
78                 return(result)
79         }
80         for(i in 1:length(flatModel@matrices)) {
81                 result <- generateDefinitionListHelper(
82                         flatModel@matrices[[i]], 
83                         result, defLocations, i - 1L)
84         }       
85         return(result)
86 }
87
88 generateValueList <- function(mList, pList) {
89         mList <- lapply(mList, function(x) { x[[1]] })
90         retval <- vector()
91         if (length(pList) == 0) {
92                 return(retval)
93         }
94         for(i in 1:length(pList)) {
95                 parameter <- pList[[i]]
96                 parameter <- parameter[4:length(parameter)] # Remove (min, max, dependencies)
97                 if (length(parameter) > 1) {
98                         values <- sapply(parameter, generateValueHelper, mList)
99                         if (!all(values == values[[1]])) {
100                                 warning(paste('Parameter',i,'has multiple start values.',
101                                         'Selecting', values[[1]]))
102                         }
103                         retval[i] <- values[[1]]
104                 } else {
105                         retval[i] <- generateValueHelper(parameter[[1]], mList)
106                 }
107     }
108         return(retval)  
109 }
110
111 generateValueHelper <- function(triple, mList) {
112         mat <- triple[1] + 1
113         row <- triple[2] + 1
114         col <- triple[3] + 1
115         return(mList[[mat]][row,col])
116 }
117
118 getObjectiveIndex <- function(flatModel) {
119         objective <- flatModel@objective
120         if(is.null(objective)) {
121                 return(NULL)
122         } else {
123                 return(imxLocateIndex(flatModel, objective@name, flatModel@name))
124         }
125 }
126
127 imxUpdateModelValues <- function(model, flatModel, pList, values) {
128         if(length(pList) != length(values)) {
129                 stop(paste("This model has", length(pList), 
130                         "parameters, but you have given me", length(values),
131                         "values"))
132         }
133         if (length(pList) == 0) {
134                 return(model)
135         }
136         for(i in 1:length(pList)) {
137                 parameters <- pList[[i]]
138                 parameters <- parameters[4:length(parameters)] # Remove min, max, and dependencies
139                 model <- updateModelValuesHelper(parameters, values[[i]], flatModel, model)
140     }
141         return(model)
142 }
143
144 updateModelValuesHelper <- function(triples, value, flatModel, model) {
145         for(i in 1:length(triples)) {
146                 triple <- triples[[i]]
147                 mat <- triple[1] + 1
148                 row <- triple[2] + 1
149                 col <- triple[3] + 1
150                 name <- flatModel@matrices[[mat]]@name
151                 model[[name]]@values[row,col] <- value
152         }
153         return(model)
154 }
155
156 removeTail <- function(lst, tailSize) {
157     newEnd <- length(lst) - tailSize
158     if (newEnd == 0) {
159         return(list())
160     } else {
161         return(lst[1 : newEnd])
162     }
163 }
164
165 updateModelMatrices <- function(model, flatModel, values) {
166         mList <- names(flatModel@matrices)
167         if (length(mList) != length(values)) {
168                 stop(paste("This model has", length(mList), 
169                         "matrices, but the backend has returned", length(values),
170                         "values"))
171         }
172         if (length(values) == 0) {
173                 return(model)
174         }
175         model <- updateModelEntitiesHelper(mList, values, model)
176         return(model)
177 }
178
179
180 updateModelAlgebras <- function(model, flatModel, values) {
181         aNames <- names(flatModel@algebras)
182         oNames <- names(flatModel@objectives)
183         aList <- append(aNames, oNames)
184         if(length(aList) != length(values)) {
185                 stop(paste("This model has", length(aList), 
186                         "algebras, but the backend has returned", length(values),
187                         "values"))
188         }
189         if (length(aList) == 0) {
190                 return(model)
191         }
192         model <- updateModelEntitiesHelper(aList, values, model)
193         return(model)
194 }
195
196 updateModelEntitiesHelper <- function(entNames, values, model) {
197         for(i in 1:length(entNames)) {
198                 name <- entNames[[i]]
199                 candidate <- model[[name]]
200                 value <- values[[i]]
201                 if (!is.null(candidate) && (length(value) > 0)
202                         && !is.nan(value)) {
203                         if (is(candidate,"MxAlgebra") || is(candidate,"MxObjective")) {
204                                 if (is(candidate, "MxAlgebra")) {
205                                         dimnames(value) <- dimnames(candidate)
206                                         candidate@result <- value
207                                 } else {
208                                         candidate <- objectiveReadAttributes(candidate, value)
209                                 }
210                         } else if(is(candidate, "MxMatrix")) {
211                                 dimnames(value) <- dimnames(candidate)
212                                 candidate@values <- value
213                         }
214                 }
215                 model[[name]] <- candidate
216         }
217         return(model)
218 }
219
220 imxLocateIndex <- function(model, name, referant) {
221         if (is.na(name)) { return(as.integer(name)) }
222         mNames <- names(model@matrices)
223         aNames <- names(model@algebras)
224         oNames <- names(model@objectives)
225         dNames <- names(model@datasets)         
226         matrixNumber <- match(name, mNames)
227         algebraNumber <- match(name, append(aNames, oNames))
228         dataNumber <- match(name, dNames)
229         if (is.na(matrixNumber) && is.na(algebraNumber) && is.na(dataNumber)) {
230                 msg <- paste("The reference", omxQuotes(name),
231                         "does not exist.  It is used by the named entity",
232                         omxQuotes(referant),".")
233                 stop(msg, call.=FALSE)
234         } else if (!is.na(matrixNumber)) {
235                 return(- matrixNumber)
236         } else if (!is.na(dataNumber)) {
237                 return(dataNumber - 1L)
238         } else {
239                 return(algebraNumber - 1L)
240         }
241 }
242
243 omxCheckMatrices <- function(model) {
244         matrices <- model@matrices
245         lapply(matrices, imxVerifyMatrix)
246         submodels <- imxDependentModels(model)
247         lapply(submodels, omxCheckMatrices)
248 }