File: mixed.py

package info (click to toggle)
python-scipy 0.6.0-12
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 32,016 kB
  • ctags: 46,675
  • sloc: cpp: 124,854; ansic: 110,614; python: 108,664; fortran: 76,260; objc: 424; makefile: 384; sh: 10
file content (348 lines) | stat: -rw-r--r-- 9,768 bytes parent folder | download
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
"""
Mixed effects models
"""

import numpy as N
import numpy.linalg as L
from scipy.sandbox.models.formula import formula, I

class Unit:
    """
    Individual experimental unit for 
    EM implementation of (repeated measures)
    mixed effects model.

    \'Maximum Likelihood Computations with Repeated Measures:
    Application of the EM Algorithm\'

    Nan Laird; Nicholas Lange; Daniel Stram 

    Journal of the American Statistical Association,
    Vol. 82, No. 397. (Mar., 1987), pp. 97-105. 
    """

    def __getitem__(self, item):
        return self.dict[item]

    def __setitem__(self, item, value):
        self.dict[item] = value

    def __init__(self, dict):
        self.dict = dict

    def __call__(self, formula, **extra):
        """
        Return the corresponding design matrix from formula,
        perform a check whether formula just has an intercept in it, in
        which case the number of rows must be computed.
        """
        if hasattr(self, 'n') and not extra.has_key('nrow'):
            extra['nrow'] = self.n
        return formula(namespace=self.dict, **extra)

    def design(self, formula, **extra):
        v = N.transpose(self(formula, **extra))
        self.n = v.shape[0]
        return v

    def _compute_S(self, D, sigma):
        """
        Display (3.3) from Laird, Lange, Stram (see help(Unit))
        """ 
        self.S = (N.identity(self.n) * sigma**2 +
                  N.dot(self.Z, N.dot(D, self.Z.T)))

    def _compute_W(self):
        """
        Display (3.2) from Laird, Lange, Stram (see help(Unit))
        """ 
        self.W = L.inv(self.S)

    def compute_P(self, Sinv):
        """
        Display (3.10) from Laird, Lange, Stram (see help(Unit))
        """ 
        t = N.dot(self.W, self.X)
        self.P = self.W - N.dot(N.dot(t, Sinv), t.T)

    def _compute_r(self, alpha):
        """
        Display (3.5) from Laird, Lange, Stram (see help(Unit))
        """ 
        self.r = self.Y - N.dot(self.X, alpha)

    def _compute_b(self, D):
        """
        Display (3.4) from Laird, Lange, Stram (see help(Unit))
        """ 
        self.b = N.dot(D, N.dot(N.dot(self.Z.T, self.W), self.r))

    def fit(self, a, D, sigma):
        """
        Compute unit specific parameters in
        Laird, Lange, Stram (see help(Unit)).

        Displays (3.2)-(3.5).
        """

        self._compute_S(D, sigma)
        self._compute_W()
        self._compute_r(a)
        self._compute_b(D)

    def compute_xtwy(self):
        """
        Utility function to compute X^tWY for Unit instance.
        """
        return N.dot(N.dot(self.W, self.Y), self.X)

    def compute_xtwx(self):
        """
        Utility function to compute X^tWX for Unit instance.
        """
        return N.dot(N.dot(self.X.T, self.W), self.X)

    def cov_random(self, D, Sinv=None):
        """
        Approximate covariance of estimates of random effects. Just after
        Display (3.10) in Laird, Lange, Stram (see help(Unit)).
        """
        if Sinv is not None:
            self.compute_P(Sinv)
        t = N.dot(self.Z, D)
        return D - N.dot(N.dot(t.T, self.P), t)

    def logL(self, a, ML=False):
        """
        Individual contributions to the log-likelihood, tries to return REML
        contribution by default though this requires estimated
        fixed effect a to be passed as an argument.
        """
        
        if ML:
            return (N.log(L.det(self.W)) - (self.r * N.dot(self.W, self.r)).sum()) / 2.
        else:
            if a is None:
                raise ValueError, 'need fixed effect a for REML contribution to log-likelihood'
            r = self.Y - N.dot(self.X, a)
            return (N.log(L.det(self.W)) - (r * N.dot(self.W, r)).sum()) / 2.

    def deviance(self, ML=False):
        return - 2 * self.logL(ML=ML)

class Mixed:

    """
    Model for 
    EM implementation of (repeated measures)
    mixed effects model.

    \'Maximum Likelihood Computations with Repeated Measures:
    Application of the EM Algorithm\'

    Nan Laird; Nicholas Lange; Daniel Stram 

    Journal of the American Statistical Association,
    Vol. 82, No. 397. (Mar., 1987), pp. 97-105. 
    """

    def __init__(self, units, response, fixed=I, random=I):
        self.units = units
        self.m = len(self.units)
        
        self.fixed = formula(fixed)
        self.random = formula(random)
        self.response = formula(response)

        self.N = 0
        for unit in self.units:
            unit.Y = N.squeeze(unit.design(self.response))
            unit.X = unit.design(self.fixed)
            unit.Z = unit.design(self.random)
            self.N += unit.X.shape[0]

        # Determine size of fixed effects

        d = self.units[0].design(self.fixed)
        self.p = d.shape[1]  # d.shape = p 
        self.a = N.zeros(self.p, N.float64)

        # Determine size of D, and sensible initial estimates
        # of sigma and D        
        d = self.units[0].design(self.random)
        self.q = d.shape[1]  # d.shape = q 

        self.D = N.zeros((self.q,)*2, N.float64)
        self.sigma = 1.

        self.dev = N.inf

    def _compute_a(self):
        """
        Display (3.1) of
        Laird, Lange, Stram (see help(Mixed)).

        """

        for unit in self.units:
            unit.fit(self.a, self.D, self.sigma)

        S = sum([unit.compute_xtwx() for unit in self.units])
        Y = sum([unit.compute_xtwy() for unit in self.units])
        
        self.Sinv = L.pinv(S)
        self.a = N.dot(self.Sinv, Y)
            
    def _compute_sigma(self, ML=False):
        """
        Estimate sigma. If ML is True, return the ML estimate of sigma,
        else return the REML estimate.

        If ML, this is (3.6) in Laird, Lange, Stram (see help(Mixed)),
        otherwise it corresponds to (3.8).

        """
        sigmasq = 0.
        for unit in self.units:
            if ML:
                W = unit.W
            else:
                unit.compute_P(self.Sinv)
                W = unit.P
            t = unit.r - N.dot(unit.Z, unit.b)
            sigmasq += N.power(t, 2).sum()
            sigmasq += self.sigma**2 * N.trace(N.identity(unit.n) -
                                               self.sigma**2 * W)
        self.sigma = N.sqrt(sigmasq / self.N)

    def _compute_D(self, ML=False):
        """
        Estimate random effects covariance D.
        If ML is True, return the ML estimate of sigma,
        else return the REML estimate.

        If ML, this is (3.7) in Laird, Lange, Stram (see help(Mixed)),
        otherwise it corresponds to (3.9).

        """
        D = 0.
        for unit in self.units:
            if ML:
                W = unit.W
            else:
                unit.compute_P(self.Sinv)
                W = unit.P
            D += N.multiply.outer(unit.b, unit.b)
            t = N.dot(unit.Z, self.D)
            D += self.D - N.dot(N.dot(t.T, W), t)

        self.D = D / self.m

    def cov_fixed(self):
        """
        Approximate covariance of estimates of fixed effects. Just after
        Display (3.10) in Laird, Lange, Stram (see help(Mixed)).
        """
        return self.Sinv

    def deviance(self, ML=False):
        return -2 * self.logL(ML=ML)

    def logL(self, ML=False):
        """
        Return log-likelihood, REML by default.
        """
        logL = 0.

        for unit in self.units:
            logL += unit.logL(a=self.a, ML=ML)
        if not ML:
            logL += N.log(L.det(self.Sinv)) / 2
        return logL

    def initialize(self):
        S = sum([N.dot(unit.X.T, unit.X) for unit in self.units])
        Y = sum([N.dot(unit.X.T, unit.Y) for unit in self.units])
        self.a = L.lstsq(S, Y)[0]

        D = 0
        t = 0
        sigmasq = 0
        for unit in self.units:
            unit.r = unit.Y - N.dot(unit.X, self.a)
            if self.q > 1:
                unit.b = L.lstsq(unit.Z, unit.r)[0]
            else:
                Z = unit.Z.reshape((unit.Z.shape[0], 1))
                unit.b = L.lstsq(Z, unit.r)[0]

            sigmasq += (N.power(unit.Y, 2).sum() -
                        (self.a * N.dot(unit.X.T, unit.Y)).sum() -
                        (unit.b * N.dot(unit.Z.T, unit.r)).sum())
            D += N.multiply.outer(unit.b, unit.b)
            t += L.pinv(N.dot(unit.Z.T, unit.Z))

        sigmasq /= (self.N - (self.m - 1) * self.q - self.p)
        self.sigma = N.sqrt(sigmasq)
        self.D = (D - sigmasq * t) / self.m

    def cont(self, ML=False, tol=1.0e-05):

        self.dev, old = self.deviance(ML=ML), self.dev
        if N.fabs((self.dev - old)) * self.dev < tol:
            return False
        return True

    def fit(self, niter=100, ML=False):

        for i in range(niter):
            self._compute_a()
            self._compute_sigma(ML=ML)
            self._compute_D(ML=ML)
            if not self.cont(ML=ML):
                break
            

if __name__ == '__main__':
    import numpy.random as R

    nsubj = 400
    units  = []
    
    n = 3

    from scipy.sandbox.models.formula import term
    fixed = term('f')
    random = term('r')
    response = term('y')

    for i in range(nsubj):
        d = R.standard_normal()
        X = R.standard_normal((10,n))
        Z = X[0:2]
        Y = R.standard_normal((n,)) + d * 4
        units.append(Unit({'f':X, 'r':Z, 'y':Y}))

    #m = Mixed(units, response)#, fixed, random)
    m = Mixed(units, response, fixed, random)
    m.initialize()
    m.fit()



## a = Unit()
## a['x'] = N.array([2,3])
## a['y'] = N.array([3,4])

## x = Term('x')
## y = Term('y')

## fixed = x + y + x * y
## random = Formula(x)

## a.X = a.design(fixed)
## a.Z = a.design(random)

## print help(a.compute_S)