File: sysGmm.R

package info (click to toggle)
r-cran-gmm 1.8-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,592 kB
  • sloc: fortran: 131; ansic: 25; makefile: 2
file content (300 lines) | stat: -rw-r--r-- 11,945 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  A copy of the GNU General Public License is available at
#  http://www.r-project.org/Licenses/


five <- function(g, h, commonCoef = FALSE, data = NULL)
    {
        res  <- sysGmm(g, h, wmatrix = "optimal", vcov = "CondHom", commonCoef=commonCoef, data=data)
        attr(res$dat, "sysInfo")$typeDesc <- "Full-Information IV (FIVE)"
        res$call <- match.call()
        res
    }

threeSLS <- function(g, h, commonCoef = FALSE, data = NULL)
    {
        if (!is(h, "formula"))
            if (length(h) != 1)
                stop("In 3SLS, h is a single equation since the same instruments are used in each equation")
        res <- sysGmm(g, h, vcov = "CondHom", commonCoef=commonCoef, data=data)
        attr(res$dat, "sysInfo")$typeDesc <- "3-stage Least Squares"
        res$call <- match.call()
        res
    }
sur <- function(g, commonCoef = FALSE, data = NULL)
    {
        if (!is.list(g))
            stop("g must be list of formulas")
        if (length(g) == 1)
            stop("For single equation GMM, use the function gmm()")
        if (!all(sapply(1:length(g), function(i) is(g[[i]], "formula"))))
            stop("g must be a list of formulas")
        tm <- lapply(1:length(g), function(i) terms(g[[i]]))
        reg <- lapply(1:length(g), function(i) attr(tm[[i]], "term.labels"))
        reg <- unique(do.call(c,reg))
        h <- paste(reg, collapse = "+")
        if (all(sapply(1:length(g), function(i) attr(tm[[i]], "intercept") == 0)))
            h <- paste(h, "-1")
        h <- as.formula(paste("~", h))
        res <- sysGmm(g, h, vcov = "CondHom", commonCoef=commonCoef, data=data)
        attr(res$dat, "sysInfo")$typeDesc <- "Seemingly Unrelated Regression (SUR)"
        res$call <- match.call()        
        res
        }
            
randEffect <- function(g, data = NULL)
    {
        res <- sur(g, commonCoef = TRUE, data = data)
        attr(res$dat, "sysInfo")$typeDesc <- "Random Effect Estimator"
        res$call <- match.call()        
        res
    }


sysGmm <- function(g, h, wmatrix = c("optimal","ident"),
                   vcov=c("MDS", "HAC", "CondHom", "TrueFixed"), 
                   kernel=c("Quadratic Spectral","Truncated", "Bartlett", "Parzen", "Tukey-Hanning"),
                   crit=10e-7,bw = bwAndrews, prewhite = FALSE, ar.method = "ols", approx="AR(1)",tol = 1e-7,
                   model=TRUE, X=FALSE, Y=FALSE, centeredVcov = TRUE, weightsMatrix = NULL,
                   data, crossEquConst = NULL, commonCoef = FALSE)
    {
        kernel <- match.arg(kernel)
        vcov <- match.arg(vcov)
        wmatrix <- match.arg(wmatrix)
        TypeGmm = "sysGmm"

        if(vcov=="TrueFixed" & is.null(weightsMatrix))
            stop("TrueFixed vcov only for fixed weighting matrix")
        if(!is.null(weightsMatrix))
            wmatrix <- "optimal"
        if(missing(data))
            data<-NULL
        all_args<-list(data = data, g = g, h = h, wmatrix = wmatrix, vcov = vcov, kernel = kernel,
                       crit = crit, bw = bw, prewhite = prewhite, ar.method = ar.method, approx = approx, 
                       weightsMatrix = weightsMatrix, centeredVcov = centeredVcov, tol = tol, 
                       model = model, X = X, Y = Y, call = match.call(), commonCoef=commonCoef, crossEquConst = crossEquConst)
        class(all_args)<-TypeGmm
        Model_info<-getModel(all_args)
        z <- momentEstim(Model_info)
        z <- FinRes(z, Model_info)
        return(z)
    }

.momentFct_Sys <- function(tet, dat)
    {
        q <- length(dat)
        f <- function(i, dat)
            {
                d <- dat[[i]]
                attr(d, "eqConst") <- attr(dat, "eqConst")
                attr(d, "ModelType") <- attr(dat, "ModelType")
                attr(d,"momentfct")  <- attr(dat,"momentfct")
                attr(d, "smooth") <- attr(dat, "smooth")
                .momentFct(tet[[i]], d)
            }
        mom <- lapply(1:q, function(i) f(i, dat))
        do.call(cbind, mom)
    }


.DmomentFct_Sys <- function(tet, dat, pt=NULL)
    {
        q <- length(dat)
        f <- function(i, dat)
            {
                d <- dat[[i]]
                attr(d, "eqConst") <- attr(dat, "eqConst")
                attr(d, "ModelType") <- attr(dat, "ModelType")
                attr(d,"momentfct")  <- attr(dat,"momentfct")
                attr(d, "smooth") <- attr(dat, "smooth")
                .DmomentFct(tet[[i]], d, pt)
            }        
        dmom <- lapply(1:q, function(i) f(i, dat))
        if (attr(dat, "sysInfo")$commonCoef)
            do.call(rbind,dmom)
        else
            .diagMatrix(dmom)
    }

.weightFct_Sys<- function(tet, dat, type=c("MDS", "HAC", "CondHom", "ident", "fct", "fixed")) 
    {
        type <- match.arg(type)
        if (type == "fixed")
            {
                w <- attr(dat, "weight")$w
                attr(w, "inv") <- FALSE
            } else if (type == "ident") {
                w <- diag(attr(dat, "q"))
                attr(w, "inv") <- FALSE
            } else {
                if (type == "HAC")
                    {
                        gt <- .momentFct_Sys(tet,dat)
                        if(attr(dat, "weight")$centeredVcov)
                            gt <- residuals(lm(gt~1))
                        n <- NROW(gt)
                        obj <- attr(dat, "weight")
                        obj$centeredVcov <- FALSE
                        w <- .myKernHAC(gt, obj)
                        attr(w, "inv") <- TRUE
                    }
                if (type == "MDS")
                    {
                        gt <- .momentFct_Sys(tet,dat)
                        n <- NROW(gt)
                        if(attr(dat, "weight")$centeredVcov)
                            gt <- scale(gt, scale=FALSE)
                        w <- crossprod(gt)/n
                        attr(w, "inv") <- TRUE
                    }
                if (type == "CondHom")
                    {
                        e <- lapply(1:length(dat), function(i) .residuals(tet[[i]], dat[[i]])$residuals)
                        e <- do.call(cbind, e)
                        Sig <- crossprod(scale(e, scale=FALSE))/nrow(e)
                        Z <- lapply(1:length(dat), function(i) dat[[i]]$x[,(2+dat[[i]]$k):ncol(dat[[i]]$x)])
                        Z <- do.call(cbind, Z)
                        w <- crossprod(Z)/nrow(e)
                        for (i in 1:length(dat))
                            for (j in 1:length(dat))
                                {
                                    s1 <- 1+(i-1)*dat[[i]]$nh
                                    e1 <- i*dat[[i]]$nh
                                    s2 <- 1+(j-1)*dat[[j]]$nh
                                    e2 <- j*dat[[j]]$nh
                                    w[s1:e1, s2:e2] <- w[s1:e1, s2:e2]*Sig[i,j]
                                }
                        attr(w, "inv") <- TRUE
                    }
            }
        return(w)
    }

.diagMatrix <- function(xlist, which=NULL)
    {
        # Create block diagonal matrix from matrices with the same number of rows.
        m <- length(xlist)
        n <- NROW(xlist[[1]])
        l <- sapply(1:m, function(i) dim(as.matrix(xlist[[i]])))
        if (!is.null(which))
            {
                if (any(l[2,1]!=l[2,]))
                    stop("diagMatrix with which given is for X with the same number of columns")
                which <- sort(which)
                if (length(which) == l[2,1])
                    {
                        dimX <- rowSums(l)
                        which <- NULL
                    } else {
                        dimX <- c(sum(l[1,]), length(which)*m + l[2,1]-length(which))
                    }
            } else {
                dimX <- rowSums(l)
            }
        X <- matrix(0, dimX[1], dimX[2])
        if (is.null(which))
            {
                for (i in 1:m)
                    {
                        s1 <- 1 + (i-1)*n
                        e1 <- n*i
                        s2 <- 1 + sum(l[2,][-(i:m)])
                        e2 <- sum(l[2,][1:i])
                        X[s1:e1, s2:e2] <- xlist[[i]]
                    }
            } else {
                q <- match(1:l[2,1],which)
                q2 <- which(is.na(q))
                wai <- 1
                for (j in q2)
                    {
                        if (wai < j)
                            {
                                xlist2 <- lapply(1:length(xlist), function(i) xlist[[i]][,wai:(j-1), drop=FALSE])
                                k <- j-wai
                                Xtmp <- .diagMatrix(xlist2)
                                X[,wai:(wai+length(xlist)*k-1)] <- Xtmp
                                wai <- wai + length(xlist)*k
                            }
                        X[,wai] <- do.call(c, lapply(1:length(xlist), function(i) xlist[[i]][,j]))
                        wai <- wai+1
                    }
                if (max(q2) < l[2,1])
                    {
                        xlist2 <- lapply(1:length(xlist), function(i) xlist[[i]][,-(1:max(q2))])
                        Xtmp <- .diagMatrix(xlist2)
                        X[,wai:ncol(X)] <- Xtmp
                    }
            }
        X
    }


.getThetaList <- function(tet, dat)
    {
        neq <- length(dat)
        if (attr(dat, "sysInfo")$commonCoef)
            {
                k <- attr(dat, "k")[[1]]
                if (length(tet) != k)
                    stop("Wrong length of tet")
                tet2 <- rep(list(c(tet)), neq)
            } else if (!is.null(attr(dat, "sysInfo")$crossEquConst)) { 
                k <- attr(dat, "k")[[1]]
                cst <- attr(dat, "sysInfo")$crossEquConst
                nk <- (k-length(cst))*neq + length(cst)
                if (nk != length(tet))
                    stop("Wrong length of tet")
                tet2 <- matrix(NA, k, neq)
                wai <- 1
                for (j in cst)
                    {
                        if (wai < j)
                            {
                                ind <- wai:(j-1)
                                tet2[ind,] <- tet[1:(neq*length(ind))]
                                tet <- tet[-(1:(neq*(j-wai)))]
                                wai <- wai + length(ind) 
                            }
                        tet2[wai,] <- tet[1]
                        tet <- tet[-1]
                        wai <- wai+1    
                    }
                if (max(cst) < k)
                        tet2[(max(cst)+1):k,] <- tet
                attr(dat, "sysInfo")$crossEquConst <- NULL
                tet2 <- .getThetaList(c(tet2), dat)
            } else {
                k2 <- do.call(c, attr(dat, "k"))
                if (sum(k2) != length(tet))
                    stop("Wrong length of tet")
                tet2 <- list()
                for (j in 1:length(k2))
                    {
                        tet2[[j]] <- tet[1:k2[j]]
                        tet <- tet[-(1:k2[j])]
                    }
            }
        tet2
    }

.chkPerfectFit <- function(obj)
    {
        r <- as.matrix(obj$residuals)
        f <- as.matrix(obj$fitted.values)
        rdf <- obj$df.residual
        rss <- colSums(r^2)
        mf <- colMeans(f)
        mv <- apply(f, 2, var)
        resvar <- rss/rdf
        resvar < (mf^2 + mv) * 1e-30 
    }