Centralize definitions of generic class unions
[openmx:openmx.git] / R / MxAlgebra.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 setClassUnion("MxAlgebraFormula", c("call", "name", "language", "logical", "numeric"))
17
18 setClass(Class = "MxAlgebra",
19         representation = representation(
20                 formula = "MxAlgebraFormula",
21                 name = "character",
22                 dirty = "logical",
23                 .dimnames = "MxListOrNull",
24                 initial = "matrix",
25                 dependencies = "integer",
26                 result = "matrix"))
27                 
28 setMethod("initialize", "MxAlgebra",
29         function(.Object, formula, name) {
30                 .Object@formula <- sys.call(which=-3)[[3]]
31                 .Object@name <- name
32                 .Object@dirty <- FALSE
33                 .Object@.dimnames <- NULL
34                 return(.Object)
35         }
36 )
37
38 setMethod("dimnames", "MxAlgebra",
39         function(x) { x@.dimnames }
40 )
41
42 setReplaceMethod("dimnames", "MxAlgebra",
43         function(x, value) {
44                 if (is.null(value)) {
45                 } else if (!is.list(value)) {
46                         stop("dimnames of MxAlgebra object must be either NULL or list of length 2")
47                 } else if (length(value) != 2) {
48                         stop("dimnames of MxAlgebra object must be either NULL or list of length 2")
49                 }
50                 x@.dimnames <- value
51                 return(x)
52         }
53 )
54
55
56
57 mxAlgebra <- function(expression, name = NA, dimnames = NA) {
58         if (single.na(name)) {
59                 name <- imxUntitledName()
60         }
61         imxVerifyName(name, 0)
62         retval <- new("MxAlgebra", NA, name)
63         retval@formula <- match.call()$expression
64     algebraErrorChecking(retval@formula, "mxAlgebra")
65         if(!(length(dimnames) == 1 && is.na(dimnames))) {
66                 dimnames(retval) <- dimnames
67         }
68         return(retval)  
69 }
70
71 algebraErrorChecking <- function(formula, context) {
72         if(length(formula) < 2) {
73                 return()
74         }
75         operator <- as.character(formula[[1]])
76         if (identical(operator, "(")) {
77         } else if (operator %in% omxSymbolTable[,'R.name']) {
78         } else {
79                 msg <- paste("Unknown matrix operator or function",
80                         omxQuotes(operator), "in",
81                         deparse(width.cutoff = 400L, imxLocateFunction(context)))
82                 stop(msg, call. = FALSE)
83         }
84         lapply(formula[-1], algebraErrorChecking, context)
85 }
86
87 defStringsAsFactors <- getOption('stringsAsFactors')
88 options(stringsAsFactors = FALSE)
89 data(omxSymbolTable)
90 options(stringsAsFactors = defStringsAsFactors)
91
92
93 formulaList <- function(x) {
94         retval <- as.list(x)
95         retval <- lapply(retval, function(x) {
96                 if(is.call(x)) {formulaList(x)} else {x}
97         })
98         return(retval)
99 }
100
101 algebraSymbolCheck <- function(formula, name) {
102         formula <- unlist(formulaList(formula))
103         test <- sapply(formula, function(x) {!is.numeric(x) && !is.character(x)})
104         if(length(formula[test]) == 1) {
105                 msg <- paste("The reference", omxQuotes(formula[test]),
106                         "is unknown in the algebra named", omxQuotes(name))
107                 stop(msg, call. = FALSE)
108         } else if (length(formula[test]) > 1) {
109                 msg <- paste("The references", omxQuotes(formula[test]),
110                         "are unknown in the algebra named", omxQuotes(name))
111                 stop(msg, call. = FALSE)                
112         }
113 }
114
115 generateAlgebraHelper <- function(algebra, matrixNumbers, algebraNumbers) {
116         retval <- algebra@formula
117         retval <- eval(substitute(substitute(e, matrixNumbers), list(e = retval)))
118         retval <- eval(substitute(substitute(e, algebraNumbers), list(e = retval)))
119         retval <- substituteOperators(as.list(retval), algebra@name)
120         algebraSymbolCheck(retval, algebra@name)
121         return(list(algebra@initial, retval, algebra@dependencies))
122 }
123
124 substituteOperators <- function(algebra, name) {
125         if ((length(algebra) == 1) && (is.list(algebra))) {
126                 algebra <- list(0L, algebra[[1]])
127         } else if ((length(algebra) > 1) && (!is.numeric(algebra[[1]]))) {
128                 if (as.character(algebra[[1]]) == '(') {
129                         return(substituteOperators(as.list(algebra[[2]]), name))
130                 }
131                 names <- omxSymbolTable["R.name"] == as.character(algebra[[1]])
132         variableSymbols <- omxSymbolTable["Number.of.arguments"] == -1
133                 result <- omxSymbolTable[names & variableSymbols, "Num"]
134                 if (length(result) > 1) {
135                                 msg <- paste("In algebra", omxQuotes(name), 
136                                         "ambiguous function with name", algebra[[1]],
137                                         "and", (length(algebra) - 1), "arguments.")
138                                 stop(msg, call. = FALSE)
139                 } else if(length(result) == 1) {
140                         head <- as.integer(result[[1]])
141                         tail <- lapply(algebra[-1], substituteOperators, name)
142                         result <- append(tail, head, after=0)
143                         return(result)
144                 } else {
145                         length <- omxSymbolTable["Number.of.arguments"] == (length(algebra) - 1)
146                         result <- omxSymbolTable[names & length, "Num"]
147                         if (length(result) == 0) {
148                                 msg <- paste("In algebra", omxQuotes(name),
149                                         "could not find function with name", algebra[[1]],
150                                         "and", (length(algebra) - 1), "arguments.")
151                                 stop(msg, call. = FALSE)
152                         } else if (length(result) > 1) {
153                                 msg <- paste("In algebra", omxQuotes(name),
154                                         "ambiguous function with name", algebra[[1]],
155                                         "and", (length(algebra) - 1), "arguments.")
156                                 stop(msg, call. = FALSE)
157                         } else {
158                                 head <- as.integer(result[[1]])
159                             tail <- lapply(algebra[-1], substituteOperators, name)
160                                 result <- append(tail, head, after=0)
161                                 return(result)
162                         }
163         }
164         }
165         return(algebra)
166 }
167
168 checkEvaluation <- function(model, flatModel) {
169         labelsData <- imxGenerateLabels(model)
170         cache <- new.env(parent = emptyenv())
171         cache <- checkMatrixEvaluation(model, flatModel, labelsData, cache)
172         tuple <- checkAlgebraEvaluation(model, flatModel, labelsData, cache)
173         flatModel <- tuple[[1]]
174         cache <- tuple[[2]]
175         checkConstraintEvaluation(model, flatModel, labelsData, cache)
176         return(flatModel)
177 }
178
179 checkMatrixEvaluation <- function(model, flatModel, labelsData, cache) {
180         if(length(flatModel@matrices) == 0) { return(cache) }
181         for(i in 1:length(flatModel@matrices)) {
182                 matrix <- flatModel@matrices[[i]]
183                 tuple <- evaluateMxObject(matrix@name, flatModel, labelsData, cache)
184                 cache <- tuple[[2]]
185         }
186         return(cache)
187 }
188
189 checkAlgebraEvaluation <- function(model, flatModel, labelsData, cache) {
190         if(length(flatModel@algebras) == 0) { return(list(flatModel, cache)) }
191         for(i in 1:length(flatModel@algebras)) {
192                 algebra <- flatModel@algebras[[i]]
193                 tuple <- evaluateMxObject(algebra@name, flatModel, labelsData, cache)
194                 result <- tuple[[1]]
195                 cache <- tuple[[2]]
196                 algebra@initial <- as.matrix(result)
197                 flatModel@algebras[[i]] <- algebra
198         }
199         return(list(flatModel, cache))
200 }
201
202 checkConstraintEvaluation <- function(model, flatModel, labelsData, cache) {
203         if(length(flatModel@constraints) == 0) { return() }
204         for(i in 1:length(flatModel@constraints)) {
205                 constraint <- flatModel@constraints[[i]]                
206                 lhsContext <- paste("the left-hand side of constraint", omxQuotes(constraint@name))
207                 rhsContext <- paste("the right-hand side of constraint", omxQuotes(constraint@name))            
208                 tuple <- evaluateAlgebraWithContext(flatModel[[constraint@alg1]], lhsContext, flatModel, labelsData, cache)
209                 lhs <- tuple[[1]]
210                 cache <- tuple[[2]]
211                 tuple <- evaluateAlgebraWithContext(flatModel[[constraint@alg2]], rhsContext, flatModel, labelsData, cache)
212                 rhs <- tuple[[1]]
213                 cache <- tuple[[2]]
214                 if (!all(dim(lhs) == dim(rhs))) {
215                         lhsName <- constraint@formula[[2]]
216                         rhsName <- constraint@formula[[3]]
217                         if (length(lhsName) == 1) {
218                                 lhsName <- simplifyName(deparse(lhsName), model@name)
219                         } else {
220                                 lhsName <- deparse(lhsName)
221                         }
222                         if (length(rhsName) == 1) {
223                                 rhsName <- simplifyName(deparse(rhsName), model@name)
224                         } else {
225                                 rhsName <- deparse(rhsName)
226                         }
227                         stop(paste("The algebras/matrices", 
228                                 omxQuotes(c(lhsName, rhsName)),
229                                 "in model", omxQuotes(model@name),
230                                 "are in constraint", omxQuotes(simplifyName(constraint@name, model@name)),
231                                 "and are not of identical dimensions. The left-hand side is",
232                                 nrow(lhs), "x", ncol(lhs), "and the right-hand side is",
233                                 nrow(rhs), "x", paste(ncol(rhs), ".", sep = '')), call. = FALSE)
234                 }
235         }               
236 }
237
238 displayAlgebra <- function(mxAlgebra) {
239         cat("mxAlgebra", omxQuotes(mxAlgebra@name), '\n')
240         cat("@formula: ", deparse(mxAlgebra@formula, width.cutoff=500L), '\n')
241         if (length(mxAlgebra@result) == 0) {
242                 cat("@result: (not yet computed) ")
243         } else {
244                 cat("@result:\n")
245         }
246         print(mxAlgebra@result)
247         if (is.null(dimnames(mxAlgebra))) {
248                         cat("dimnames: NULL\n")
249         } else {
250                 cat("dimnames:\n")
251                 print(dimnames(mxAlgebra))
252         }
253 }
254
255 setMethod("print", "MxAlgebra", function(x,...) { displayAlgebra(x) })
256 setMethod("show", "MxAlgebra", function(object) { displayAlgebra(object) })