|
| 1 | +''' |
| 2 | +Created on Mar 7, 2011 |
| 3 | +
|
| 4 | +@author: johnsalvatier |
| 5 | +''' |
| 6 | +from numpy import floor, concatenate, exp, zeros, diag, real |
| 7 | +from numpy.linalg import inv, cholesky, eig |
| 8 | + |
| 9 | + |
| 10 | +from utils import * |
| 11 | +from ..core import * |
| 12 | + |
| 13 | +def split_hmc_step(model, vars, C, approx_loc, approx_C, step_size_scaling = .25, trajectory_length = 2. ): |
| 14 | + |
| 15 | + mapp = DASpaceMap( vars) |
| 16 | + approx_loc = mapp.project(approx_loc) |
| 17 | + |
| 18 | + n = C.shape[0] |
| 19 | + |
| 20 | + logp_d_dict = model_logp_dlogp(model, vars) |
| 21 | + |
| 22 | + step_size = step_size_scaling * n**(1/4.) |
| 23 | + |
| 24 | + invC = inv(C) |
| 25 | + cholInvC = cholesky(invC) |
| 26 | + |
| 27 | + A = zeros((2*n,2*n)) |
| 28 | + A[:n,n:] = C |
| 29 | + A[n:,:n] = -approx_C |
| 30 | + |
| 31 | + D, gamma = eig(A) |
| 32 | + |
| 33 | + e = step_size |
| 34 | + R = real(gamma.dot(diag(exp(D* e))).dot(gamma.T)) |
| 35 | + def step(logp_d, state, q0): |
| 36 | + |
| 37 | + if state is None: |
| 38 | + state = SamplerHist() |
| 39 | + |
| 40 | + nstep = int(floor(trajectory_length / step_size)) |
| 41 | + |
| 42 | + q = q0 |
| 43 | + logp0, dlogp = logp_d(q) |
| 44 | + dlogp = dlogp + dot(approx_C, q - approx_loc) |
| 45 | + logp = logp0 |
| 46 | + |
| 47 | + # momentum scale proportional to inverse of parameter scale (basically sqrt(covariance)) |
| 48 | + p = p0 = cholesky_normal( q.shape, cholInvC) |
| 49 | + |
| 50 | + #use the leapfrog method |
| 51 | + |
| 52 | + for i in range(nstep): |
| 53 | + #alternate full variable and momentum updates |
| 54 | + p = p - (e/2) * -dlogp # half momentum update |
| 55 | + |
| 56 | + x = concatenate((q - approx_loc, p)) |
| 57 | + x = dot(R, x) |
| 58 | + q = x[:n] + approx_loc |
| 59 | + |
| 60 | + logp, dlogp = logp_d(q) |
| 61 | + dlogp = dlogp + dot(approx_C, q - approx_loc) |
| 62 | + |
| 63 | + p = p - (e/2) * -dlogp # do a half step momentum update to finish off |
| 64 | + |
| 65 | + |
| 66 | + p = -p |
| 67 | + |
| 68 | + mr = logp - logp0 + K(C, p0) - K(C, p) |
| 69 | + state.metrops.append(mr) |
| 70 | + |
| 71 | + return state, metrop_select(mr, q, q0) |
| 72 | + |
| 73 | + return array_step(step, logp_d_dict, vars) |
| 74 | + |
| 75 | + |
| 76 | +def K (cov, x): |
| 77 | + return .5 * dot(x,dot(cov, x)) |
| 78 | + |
| 79 | + |
0 commit comments