Print algebra name when operator has too few or too many arguments.
[openmx:openmx.git] / R / MxAlgebra.R
1 #
2 #   Copyright 2007-2010 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("MxListOrNull", c("list", "NULL"))
17 setClassUnion("MxAlgebraFormula", c("call", "name", "language", "logical", "numeric"))
18
19 setClass(Class = "MxAlgebra",
20         representation = representation(
21                 formula = "MxAlgebraFormula",
22                 name = "character",
23                 dirty = "logical",
24                 .dimnames = "MxListOrNull",
25                 initial = "matrix",
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 mxAlgebra <- function(expression, name = NA, dimnames = NA) {
56         if (single.na(name)) {
57                 name <- imxUntitledName()
58         }
59         imxVerifyName(name, 0)
60         retval <- new("MxAlgebra", NA, name)
61         retval@formula <- match.call()$expression
62         if(!(length(dimnames) == 1 && is.na(dimnames))) {
63                 dimnames(retval) <- dimnames
64         }
65         return(retval)  
66 }
67
68 defStringsAsFactors <- getOption('stringsAsFactors')
69 options(stringsAsFactors = FALSE)
70 data(omxSymbolTable)
71 options(stringsAsFactors = defStringsAsFactors)
72
73
74 formulaList <- function(x) {
75         retval <- as.list(x)
76         retval <- lapply(retval, function(x) {
77                 if(is.call(x)) {formulaList(x)} else {x}
78         })
79         return(retval)
80 }
81
82 algebraSymbolCheck <- function(formula, name) {
83         formula <- unlist(formulaList(formula))
84         test <- sapply(formula, function(x) {!is.numeric(x) && !is.character(x)})
85         if(length(formula[test]) == 1) {
86                 msg <- paste("The reference", omxQuotes(formula[test]),
87                         "is unknown in the algebra named", omxQuotes(name))
88                 stop(msg, call. = FALSE)
89         } else if (length(formula[test]) > 1) {
90                 msg <- paste("The references", omxQuotes(formula[test]),
91                         "are unknown in the algebra named", omxQuotes(name))
92                 stop(msg, call. = FALSE)                
93         }
94 }
95
96 generateAlgebraHelper <- function(algebra, matrixNames, algebraNames) {
97         retval <- algebra@formula
98         matrixNumbers <- as.list(as.integer(-1 : (-length(matrixNames))))
99         algebraNumbers <- as.list(as.integer(0 : (length(algebraNames) - 1)))
100         names(matrixNumbers) <- matrixNames
101         names(algebraNumbers) <- algebraNames
102         retval <- eval(substitute(substitute(e, matrixNumbers), list(e = retval)))
103         retval <- eval(substitute(substitute(e, algebraNumbers), list(e = retval)))
104         retval <- substituteOperators(as.list(retval), algebra@name)
105         algebraSymbolCheck(retval, algebra@name)
106         return(list(algebra@initial, retval))
107 }
108
109 substituteOperators <- function(algebra, name) {
110         if ((length(algebra) == 1) && (is.list(algebra))) {
111                 algebra <- list(0L, algebra[[1]])
112         } else if ((length(algebra) > 1) && (!is.numeric(algebra[[1]]))) {
113                 if (as.character(algebra[[1]]) == '(') {
114                         return(substituteOperators(as.list(algebra[[2]]), name))
115                 }
116                 names <- omxSymbolTable["R.name"] == as.character(algebra[[1]])
117         variableSymbols <- omxSymbolTable["Number.of.arguments"] == -1
118                 result <- omxSymbolTable[names & variableSymbols, "Num"]
119                 if (length(result) > 1) {
120                                 msg <- paste("In algebra", omxQuotes(name), 
121                                         "ambiguous function with name", algebra[[1]],
122                                         "and", (length(algebra) - 1), "arguments.")
123                                 stop(msg, call. = FALSE)
124                 } else if(length(result) == 1) {
125                         head <- as.integer(result[[1]])
126                         tail <- lapply(algebra[-1], substituteOperators, name)
127                         result <- append(tail, head, after=0)
128                         return(result)
129                 } else {
130                         length <- omxSymbolTable["Number.of.arguments"] == (length(algebra) - 1)
131                         result <- omxSymbolTable[names & length, "Num"]
132                         if (length(result) == 0) {
133                                 msg <- paste("In algebra", omxQuotes(name),
134                                         "could not find function with name", algebra[[1]],
135                                         "and", (length(algebra) - 1), "arguments.")
136                                 stop(msg, call. = FALSE)
137                         } else if (length(result) > 1) {
138                                 msg <- paste("In algebra", omxQuotes(name),
139                                         "ambiguous function with name", algebra[[1]],
140                                         "and", (length(algebra) - 1), "arguments.")
141                                 stop(msg, call. = FALSE)
142                         } else {
143                                 head <- as.integer(result[[1]])
144                             tail <- lapply(algebra[-1], substituteOperators, name)
145                                 result <- append(tail, head, after=0)
146                                 return(result)
147                         }
148         }
149         }
150         return(algebra)
151 }
152
153 checkEvaluation <- function(model, flatModel) {
154         labelsData <- imxGenerateLabels(model)
155         checkMatrixEvaluation(model, flatModel, labelsData)
156         flatModel <- checkAlgebraEvaluation(model, flatModel, labelsData)
157         checkConstraintEvaluation(model, flatModel, labelsData)
158         return(flatModel)
159 }
160
161 checkMatrixEvaluation <- function(model, flatModel, labelsData) {
162         if(length(flatModel@matrices) == 0) { return() }
163         for(i in 1:length(flatModel@matrices)) {
164                 matrix <- flatModel@matrices[[i]]
165                 evaluateMxObject(matrix@name, flatModel, labelsData)
166         }
167 }
168
169 checkAlgebraEvaluation <- function(model, flatModel, labelsData) {
170         if(length(flatModel@algebras) == 0) { return(flatModel) }
171         for(i in 1:length(flatModel@algebras)) {
172                 algebra <- flatModel@algebras[[i]]
173                 result <- evaluateMxObject(algebra@name, flatModel, labelsData)
174                 algebra <- flatModel[[algebra@name]]
175                 algebra@initial <- as.matrix(result)
176                 flatModel[[algebra@name]] <- algebra
177         }
178         return(flatModel)
179 }
180
181 checkConstraintEvaluation <- function(model, flatModel, labelsData) {
182         if(length(flatModel@constraints) == 0) { return() }
183         for(i in 1:length(flatModel@constraints)) {
184                 constraint <- flatModel@constraints[[i]]                
185                 lhsContext <- paste("the left-hand side of constraint", omxQuotes(constraint@name))
186                 rhsContext <- paste("the right-hand side of constraint", omxQuotes(constraint@name))            
187                 lhs <- evaluateAlgebraWithContext(flatModel[[constraint@alg1]], lhsContext, flatModel, labelsData)
188                 rhs <- evaluateAlgebraWithContext(flatModel[[constraint@alg2]], rhsContext, flatModel, labelsData)
189                 if (!all(dim(lhs) == dim(rhs))) {
190                         lhsName <- constraint@formula[[2]]
191                         rhsName <- constraint@formula[[3]]
192                         if (length(lhsName) == 1) {
193                                 lhsName <- simplifyName(deparse(lhsName), model@name)
194                         } else {
195                                 lhsName <- deparse(lhsName)
196                         }
197                         if (length(rhsName) == 1) {
198                                 rhsName <- simplifyName(deparse(rhsName), model@name)
199                         } else {
200                                 rhsName <- deparse(rhsName)
201                         }
202                         stop(paste("The algebras/matrices", 
203                                 omxQuotes(c(lhsName, rhsName)),
204                                 "in model", omxQuotes(model@name),
205                                 "are in constraint", omxQuotes(simplifyName(constraint@name, model@name)),
206                                 "and are not of identical dimensions. The left-hand side is",
207                                 nrow(lhs), "x", ncol(lhs), "and the right-hand side is",
208                                 nrow(rhs), "x", paste(ncol(rhs), ".", sep = '')), call. = FALSE)
209                 }
210         }               
211 }
212
213 displayAlgebra <- function(mxAlgebra) {
214         cat("mxAlgebra", omxQuotes(mxAlgebra@name), '\n')
215         cat("@formula: ", deparse(mxAlgebra@formula, width.cutoff=500L), '\n')
216         if (length(mxAlgebra@result) == 0) {
217                 cat("@result: (not yet computed) ")
218         } else {
219                 cat("@result:\n")
220         }
221         print(mxAlgebra@result)
222         if (is.null(dimnames(mxAlgebra))) {
223                         cat("dimnames: NULL\n")
224         } else {
225                 cat("dimnames:\n")
226                 print(dimnames(mxAlgebra))
227         }
228 }
229
230 setMethod("print", "MxAlgebra", function(x,...) { displayAlgebra(x) })
231 setMethod("show", "MxAlgebra", function(object) { displayAlgebra(object) })