/ concept-collection / walnuts-interactive
Sign in
concept-collection / walnuts-interactive
walnuts-interactive / helpers / grad_log_density.m
36 lines · 974 BCodeBlameHistory
727e2e4Interactive WALNUTS sampling of a 2D banana targetJeremy Magland 1function g = grad_log_density(theta)
cd4150fAdd target distribution selector (banana / Gaussian / correlated / donut)Jeremy Magland 2%GRAD_LOG_DENSITY Gradient of the selected target's log density (see
3% log_density.m). Dispatches on the global WTARGET.
4global WTARGET
5t = WTARGET;
6if isempty(t)
7 t = 1;
8end
9x = theta(1);
10y = theta(2);
11switch t
12 case 2 % standard Gaussian
13 g = [-x; -y];
14 case 3 % correlated Gaussian, precision = inv([1 0.8; 0.8 1])
15 c = 1 / (1 - 0.8^2);
16 g = [-c * (x - 0.8 * y); -c * (y - 0.8 * x)];
17 case 4 % donut / ring
18 r = sqrt(x.^2 + y.^2);
19 if r < 1e-9
20 g = [0; 0];
21 else
22 k = -(r - 2.5) / 0.15 / r;
23 g = [k * x; k * y];
24 end
25 otherwise % banana
26 a = 2;
27 b = 0.2;
28 y1 = x / a;
29 y2 = y * a + a * b * (x.^2 + a.^2);
30 d1 = y1;
31 d2 = y2 - 4;
32 gy1 = -((4 / 3) * d1 - (2 / 3) * d2);
33 gy2 = -(-(2 / 3) * d1 + (4 / 3) * d2);
34 g = [gy1 / a + gy2 * a * b * 2 * x; gy2 * a];
35end
moveopenescclose