diff --git a/posterior_database/data/data-raw/plasma_linear/generate_linear.py b/posterior_database/data/data-raw/plasma_linear/generate_linear.py new file mode 100644 index 00000000..78a7bc0e --- /dev/null +++ b/posterior_database/data/data-raw/plasma_linear/generate_linear.py @@ -0,0 +1,83 @@ +""" +Simulate data for the linear Gaussian toy version of the plasma model +(Langmore et al., arXiv:2103.07515, eqs. 1-2 and Fig. 4). + +The paper obtains this toy from the spectroscopy model by keeping only the +amplitude, dropping the softplus, and setting sigma_p = 0, c_A = 1. + + x ~ N(0, C_pr), C_pr[i, j] = exp(-(s_i - s_j)^2 / (2 tau^2)) + delta * 1{i = j} + y ~ N(A x, sigma^2 I) + +The posterior is exactly Gaussian, so this script also writes the analytic +posterior. That gives a tool-independent reference for both Stan and PyMC. + +Writes + plasma_linear.json -> data (matches the Stan `data` block) + plasma_linear_truth.json -> simulated truth (not model input) + plasma_linear_reference.json -> analytic posterior mean/sd of x and Z +""" +import json +import numpy as np + +SEED = 1 + +N = 40 # unknowns on a 1-D grid [paper, Fig. 1/4] +M = 20 # measurements [paper, Fig. 1/4] +TAU = 0.2 # prior correlation length [paper, Fig. 4] +DELTA = 0.001 # shrinkage on the diagonal [paper] +SIGMA = 1.0 # noise sd [paper, Fig. 4] +BLUR = 0.2 # width of each measurement's averaging kernel [choice: paper's A not given] + +rng = np.random.default_rng(SEED) + +s = np.linspace(-1, 1, N) # grid of unknowns +cm = np.linspace(-1, 1, M) # measurement centres +# Each measurement is a Gaussian-weighted local average of x (rows sum to 1). +# Nearby rows overlap strongly, so A is numerically low rank, as in Fig. 1. +A = np.exp(-(s[None, :] - cm[:, None]) ** 2 / (2 * BLUR**2)) +A /= A.sum(axis=1, keepdims=True) + +C_pr = np.exp(-(s[:, None] - s[None, :]) ** 2 / (2 * TAU**2)) + DELTA * np.eye(N) +L = np.linalg.cholesky(C_pr) + +# truth drawn from the prior, then data +Z_true = rng.standard_normal(N) +x_true = L @ Z_true +y = A @ x_true + SIGMA * rng.standard_normal(M) + +# analytic posterior in the non-centred coordinates Z (x = L Z) +B = A @ L +cov_Z = np.linalg.inv(np.eye(N) + B.T @ B / SIGMA**2) +mean_Z = cov_Z @ B.T @ y / SIGMA**2 +mean_x = L @ mean_Z +cov_x = L @ cov_Z @ L.T + + +def kappa(C): + """Condition number of eq. (8) for a covariance C.""" + lam = np.sqrt(np.sort(np.linalg.eigvalsh(C))[::-1]) + return float(np.sum((lam[0] / lam) ** 4) ** 0.25) + + +data = dict(N=N, M=M, s=s.tolist(), A=A.tolist(), y=y.tolist(), + sigma=SIGMA, tau=TAU, delta=DELTA) +truth = dict(seed=SEED, Z=Z_true.tolist(), x=x_true.tolist()) +reference = dict( + note="Exact Gaussian posterior. Z is the non-centred parameter, x = L_pr Z.", + x_mean=mean_x.tolist(), x_sd=np.sqrt(np.diag(cov_x)).tolist(), + Z_mean=mean_Z.tolist(), Z_sd=np.sqrt(np.diag(cov_Z)).tolist(), + kappa_centered=kappa(cov_x), kappa_noncentered=kappa(cov_Z), +) + +with open("plasma_linear.json", "w") as f: + json.dump(data, f) +with open("plasma_linear_truth.json", "w") as f: + json.dump(truth, f) +with open("plasma_linear_reference.json", "w") as f: + json.dump(reference, f) + +print(f"N={N} M={M} sigma={SIGMA} tau={TAU} delta={DELTA} blur={BLUR}") +print(f"singular values of A: max {np.linalg.svd(A, compute_uv=False).max():.2f}, " + f"min {np.linalg.svd(A, compute_uv=False).min():.1e}") +print(f"kappa (eq. 8): centred {reference['kappa_centered']:.1f}, " + f"non-centred {reference['kappa_noncentered']:.1f}") diff --git a/posterior_database/data/data-raw/plasma_shell_full/generate_data.py b/posterior_database/data/data-raw/plasma_shell_full/generate_data.py new file mode 100644 index 00000000..5eaa8506 --- /dev/null +++ b/posterior_database/data/data-raw/plasma_shell_full/generate_data.py @@ -0,0 +1,145 @@ +""" +Simulate data for the plasma "shell" model (Langmore et al., arXiv:2103.07515, sec. 2.3). + +Writes + plasma_shell_sim.json -> exactly the Stan `data` block (share this with the PyMC colleague) + plasma_shell_truth.json -> the simulated truth (NOT model data; for recovery checks / logp comparison) + plasma_sim_check.png -> sanity plot (only if matplotlib is installed) + +Everything marked [paper] comes from the paper; the rest are documented choices. +""" +import json +import numpy as np + +import sys + +SEED = 1 + +# Two presets share one code path: +# full : the larger dataset (default; reproduces plasma_shell_sim.json exactly) +# lite : smaller and noisier, so the posterior is cheaper and wider +PRESET = sys.argv[1] if len(sys.argv) > 1 else "full" +if PRESET not in ("full", "lite"): + sys.exit("usage: python3 generate_data.py [full|lite]") +FULL = PRESET == "full" + +# ---- geometry --------------------------------------------------------------- +G = 20 if FULL else 10 # G x G pixel grid on [-1, 1]^2 [choice] +M_PER_DIR = 20 if FULL else 10 # chords per direction (Fig. 2 uses 20) [paper count / choice] +M = 2 * M_PER_DIR # vertical + horizontal chords (breaks the c_y -> -c_y symmetry) [choice] +P = G * G +K = 60 if FULL else 30 # frequencies (paper: ~200) [choice] +R = 12 if FULL else 8 # radial nodes [choice] +R_MAX = 3.0 if FULL else 2.0 # radial grid end; farthest pixel from a centre near 0 is ~1.8 [choice] + +# ---- constants -------------------------------------------------------------- +NU_LO, NU_HI = 229.5, 229.9 # measurement bounds, Fig. 3 [paper, read off figure] +NU_0 = 229.7 # centre of window / Carbon III line [paper, inferred] +TAU = 0.2 # prior correlation length [paper value, one of two] +DELTA = 0.001 # shrinkage [paper] +SIGMA_C = 0.1 # sd of centre prior [choice] +SIGMA = 5.0 if FULL else 15.0 # additive noise (paper range 1.25-15) [paper range] +SIGMA_P = 0.05 # proportional noise [choice] +C_A = 7e-4 if FULL else 2e-4 # amplitude scale; full: peaks ~1e3 as in Fig. 3, lite: ~3e2 [chosen] +C_T = 2e-8 # temperature scale [chosen: w ~ 1-4 freq spacings] +C_V = 1e-4 # velocity scale [chosen: shift ~ 1 line width / unit f] + +OUT = "plasma_shell_sim" if FULL else "plasma_shell_lite_sim" +OUT_TRUTH = "plasma_shell_truth" if FULL else "plasma_shell_lite_truth" +OUT_PNG = "plasma_sim_check.png" if FULL else "plasma_shell_lite_check.png" + +# ---- build ------------------------------------------------------------------- +rng = np.random.default_rng(SEED) + +xs = -1 + (np.arange(G) + 0.5) * 2 / G +Xg, Yg = np.meshgrid(xs, xs) # Xg[i, j] = xs[j], Yg[i, j] = xs[i] +xy = np.column_stack([Xg.ravel(), Yg.ravel()]) # pixel p = i*G + j (row-major) +col = np.arange(P) % G # x index of each pixel +row = np.arange(P) // G # y index of each pixel + +I_mat = np.zeros((M, P)) +for m in range(M_PER_DIR): + I_mat[m, col == m] = 2 / G # vertical chords (integrate along y) + I_mat[M_PER_DIR + m, row == m] = 2 / G # horizontal chords (integrate along x) + +nu = np.linspace(NU_LO, NU_HI, K) +r_grid = np.linspace(0.0, R_MAX, R) + +# prior covariance of radial profile (delta*I, not a constant added to all entries) +C = np.exp(-(r_grid[:, None] - r_grid[None, :]) ** 2 / (2 * TAU**2)) + DELTA * np.eye(R) +L = np.linalg.cholesky(C) + +softplus = lambda u: np.log1p(np.exp(u)) + + +def mu_fn(fA, fT, fV, ctr): + """Noise-free chord spectra, M x K. Mirrors mu_fn in plasma_shell.stan.""" + r = np.sqrt(((xy - ctr) ** 2).sum(1) + 1e-12) + A = C_A * softplus(np.interp(r, r_grid, fA)) + T = C_T * softplus(np.interp(r, r_grid, fT)) + V = C_V * np.interp(r, r_grid, fV) + w = np.sqrt(T) / NU_0 + nu_tilde_inv = (1 - V) / NU_0 + emis = (A / (np.sqrt(2 * np.pi) * w))[:, None] * np.exp( + -((1 / nu)[None, :] - nu_tilde_inv[:, None]) ** 2 / (2 * w[:, None] ** 2) + ) + return I_mat @ emis + + +# ---- simulate truth from the prior ------------------------------------------- +Z_A, Z_T, Z_V = (rng.standard_normal(R) for _ in range(3)) +c_raw = rng.standard_normal(2) +ctr = SIGMA_C * c_raw +mu = mu_fn(L @ Z_A, L @ Z_T, L @ Z_V, ctr) +sd = np.sqrt(SIGMA**2 + (SIGMA_P * mu) ** 2) +Y = mu + rng.standard_normal(mu.shape) * sd + +data = dict( + P=P, M=M, K=K, R=R, + nu=nu.tolist(), nu_0=NU_0, + I_mat=I_mat.tolist(), Y=Y.tolist(), + xy=xy.tolist(), r_grid=r_grid.tolist(), + tau=TAU, delta=DELTA, sigma_c=SIGMA_C, + c_A=C_A, c_T=C_T, c_V=C_V, + sigma=SIGMA, sigma_p=SIGMA_P, +) +truth = dict(seed=SEED, Z_A=Z_A.tolist(), Z_T=Z_T.tolist(), Z_V=Z_V.tolist(), + c_raw=c_raw.tolist(), ctr=ctr.tolist()) + +with open(OUT + ".json", "w") as f: + json.dump(data, f) +with open(OUT_TRUTH + ".json", "w") as f: + json.dump(truth, f) + +# ---- sanity report ----------------------------------------------------------- +dinv = abs(np.diff(1 / nu).mean()) +print(f"preset={PRESET} M={M} K={K} P={P} R={R}") +print(f"true centre = {np.round(ctr, 3)}") +print(f"noise-free signal: min {mu.min():.3g}, max {mu.max():.3g}") +print(f"peak position (freq index) per chord: min {mu.argmax(1).min()}, max {mu.argmax(1).max()} of {K-1}") +i_pk = np.unravel_index(mu.argmax(), mu.shape) +print(f"signal-to-noise at the highest peak: {mu[i_pk] / sd[i_pk]:.1f}") +T_pix = C_T * softplus(np.interp(np.sqrt(((xy - ctr) ** 2).sum(1)), r_grid, L @ Z_T)) +w_pix = np.sqrt(T_pix) / NU_0 +print(f"line width w in frequency-grid spacings: {w_pix.min() / abs(np.diff(1 / nu).mean()):.2f}" + f" - {w_pix.max() / abs(np.diff(1 / nu).mean()):.2f} (want >~1)") + +try: + import matplotlib + matplotlib.use("Agg") + import matplotlib.pyplot as plt + fig, ax = plt.subplots(1, 2, figsize=(10, 3.5)) + half = M_PER_DIR + for m in range(0, half, max(1, half // 5)): + ax[0].plot(nu, Y[m], lw=0.8) + ax[0].set_title("vertical chords (data)") + for m in range(half, M, max(1, half // 5)): + ax[1].plot(nu, Y[m], lw=0.8) + ax[1].set_title("horizontal chords (data)") + for a in ax: + a.set_xlabel("wavelength") + plt.tight_layout() + plt.savefig(OUT_PNG, dpi=120) + print(f"wrote {OUT_PNG}") +except ImportError: + pass diff --git a/posterior_database/data/data-raw/plasma_shell_lite/generate_data.py b/posterior_database/data/data-raw/plasma_shell_lite/generate_data.py new file mode 100644 index 00000000..5eaa8506 --- /dev/null +++ b/posterior_database/data/data-raw/plasma_shell_lite/generate_data.py @@ -0,0 +1,145 @@ +""" +Simulate data for the plasma "shell" model (Langmore et al., arXiv:2103.07515, sec. 2.3). + +Writes + plasma_shell_sim.json -> exactly the Stan `data` block (share this with the PyMC colleague) + plasma_shell_truth.json -> the simulated truth (NOT model data; for recovery checks / logp comparison) + plasma_sim_check.png -> sanity plot (only if matplotlib is installed) + +Everything marked [paper] comes from the paper; the rest are documented choices. +""" +import json +import numpy as np + +import sys + +SEED = 1 + +# Two presets share one code path: +# full : the larger dataset (default; reproduces plasma_shell_sim.json exactly) +# lite : smaller and noisier, so the posterior is cheaper and wider +PRESET = sys.argv[1] if len(sys.argv) > 1 else "full" +if PRESET not in ("full", "lite"): + sys.exit("usage: python3 generate_data.py [full|lite]") +FULL = PRESET == "full" + +# ---- geometry --------------------------------------------------------------- +G = 20 if FULL else 10 # G x G pixel grid on [-1, 1]^2 [choice] +M_PER_DIR = 20 if FULL else 10 # chords per direction (Fig. 2 uses 20) [paper count / choice] +M = 2 * M_PER_DIR # vertical + horizontal chords (breaks the c_y -> -c_y symmetry) [choice] +P = G * G +K = 60 if FULL else 30 # frequencies (paper: ~200) [choice] +R = 12 if FULL else 8 # radial nodes [choice] +R_MAX = 3.0 if FULL else 2.0 # radial grid end; farthest pixel from a centre near 0 is ~1.8 [choice] + +# ---- constants -------------------------------------------------------------- +NU_LO, NU_HI = 229.5, 229.9 # measurement bounds, Fig. 3 [paper, read off figure] +NU_0 = 229.7 # centre of window / Carbon III line [paper, inferred] +TAU = 0.2 # prior correlation length [paper value, one of two] +DELTA = 0.001 # shrinkage [paper] +SIGMA_C = 0.1 # sd of centre prior [choice] +SIGMA = 5.0 if FULL else 15.0 # additive noise (paper range 1.25-15) [paper range] +SIGMA_P = 0.05 # proportional noise [choice] +C_A = 7e-4 if FULL else 2e-4 # amplitude scale; full: peaks ~1e3 as in Fig. 3, lite: ~3e2 [chosen] +C_T = 2e-8 # temperature scale [chosen: w ~ 1-4 freq spacings] +C_V = 1e-4 # velocity scale [chosen: shift ~ 1 line width / unit f] + +OUT = "plasma_shell_sim" if FULL else "plasma_shell_lite_sim" +OUT_TRUTH = "plasma_shell_truth" if FULL else "plasma_shell_lite_truth" +OUT_PNG = "plasma_sim_check.png" if FULL else "plasma_shell_lite_check.png" + +# ---- build ------------------------------------------------------------------- +rng = np.random.default_rng(SEED) + +xs = -1 + (np.arange(G) + 0.5) * 2 / G +Xg, Yg = np.meshgrid(xs, xs) # Xg[i, j] = xs[j], Yg[i, j] = xs[i] +xy = np.column_stack([Xg.ravel(), Yg.ravel()]) # pixel p = i*G + j (row-major) +col = np.arange(P) % G # x index of each pixel +row = np.arange(P) // G # y index of each pixel + +I_mat = np.zeros((M, P)) +for m in range(M_PER_DIR): + I_mat[m, col == m] = 2 / G # vertical chords (integrate along y) + I_mat[M_PER_DIR + m, row == m] = 2 / G # horizontal chords (integrate along x) + +nu = np.linspace(NU_LO, NU_HI, K) +r_grid = np.linspace(0.0, R_MAX, R) + +# prior covariance of radial profile (delta*I, not a constant added to all entries) +C = np.exp(-(r_grid[:, None] - r_grid[None, :]) ** 2 / (2 * TAU**2)) + DELTA * np.eye(R) +L = np.linalg.cholesky(C) + +softplus = lambda u: np.log1p(np.exp(u)) + + +def mu_fn(fA, fT, fV, ctr): + """Noise-free chord spectra, M x K. Mirrors mu_fn in plasma_shell.stan.""" + r = np.sqrt(((xy - ctr) ** 2).sum(1) + 1e-12) + A = C_A * softplus(np.interp(r, r_grid, fA)) + T = C_T * softplus(np.interp(r, r_grid, fT)) + V = C_V * np.interp(r, r_grid, fV) + w = np.sqrt(T) / NU_0 + nu_tilde_inv = (1 - V) / NU_0 + emis = (A / (np.sqrt(2 * np.pi) * w))[:, None] * np.exp( + -((1 / nu)[None, :] - nu_tilde_inv[:, None]) ** 2 / (2 * w[:, None] ** 2) + ) + return I_mat @ emis + + +# ---- simulate truth from the prior ------------------------------------------- +Z_A, Z_T, Z_V = (rng.standard_normal(R) for _ in range(3)) +c_raw = rng.standard_normal(2) +ctr = SIGMA_C * c_raw +mu = mu_fn(L @ Z_A, L @ Z_T, L @ Z_V, ctr) +sd = np.sqrt(SIGMA**2 + (SIGMA_P * mu) ** 2) +Y = mu + rng.standard_normal(mu.shape) * sd + +data = dict( + P=P, M=M, K=K, R=R, + nu=nu.tolist(), nu_0=NU_0, + I_mat=I_mat.tolist(), Y=Y.tolist(), + xy=xy.tolist(), r_grid=r_grid.tolist(), + tau=TAU, delta=DELTA, sigma_c=SIGMA_C, + c_A=C_A, c_T=C_T, c_V=C_V, + sigma=SIGMA, sigma_p=SIGMA_P, +) +truth = dict(seed=SEED, Z_A=Z_A.tolist(), Z_T=Z_T.tolist(), Z_V=Z_V.tolist(), + c_raw=c_raw.tolist(), ctr=ctr.tolist()) + +with open(OUT + ".json", "w") as f: + json.dump(data, f) +with open(OUT_TRUTH + ".json", "w") as f: + json.dump(truth, f) + +# ---- sanity report ----------------------------------------------------------- +dinv = abs(np.diff(1 / nu).mean()) +print(f"preset={PRESET} M={M} K={K} P={P} R={R}") +print(f"true centre = {np.round(ctr, 3)}") +print(f"noise-free signal: min {mu.min():.3g}, max {mu.max():.3g}") +print(f"peak position (freq index) per chord: min {mu.argmax(1).min()}, max {mu.argmax(1).max()} of {K-1}") +i_pk = np.unravel_index(mu.argmax(), mu.shape) +print(f"signal-to-noise at the highest peak: {mu[i_pk] / sd[i_pk]:.1f}") +T_pix = C_T * softplus(np.interp(np.sqrt(((xy - ctr) ** 2).sum(1)), r_grid, L @ Z_T)) +w_pix = np.sqrt(T_pix) / NU_0 +print(f"line width w in frequency-grid spacings: {w_pix.min() / abs(np.diff(1 / nu).mean()):.2f}" + f" - {w_pix.max() / abs(np.diff(1 / nu).mean()):.2f} (want >~1)") + +try: + import matplotlib + matplotlib.use("Agg") + import matplotlib.pyplot as plt + fig, ax = plt.subplots(1, 2, figsize=(10, 3.5)) + half = M_PER_DIR + for m in range(0, half, max(1, half // 5)): + ax[0].plot(nu, Y[m], lw=0.8) + ax[0].set_title("vertical chords (data)") + for m in range(half, M, max(1, half // 5)): + ax[1].plot(nu, Y[m], lw=0.8) + ax[1].set_title("horizontal chords (data)") + for a in ax: + a.set_xlabel("wavelength") + plt.tight_layout() + plt.savefig(OUT_PNG, dpi=120) + print(f"wrote {OUT_PNG}") +except ImportError: + pass diff --git a/posterior_database/models/pymc/plasma_linear_centered.py b/posterior_database/models/pymc/plasma_linear_centered.py new file mode 100644 index 00000000..76346f03 --- /dev/null +++ b/posterior_database/models/pymc/plasma_linear_centered.py @@ -0,0 +1,34 @@ +# plasma_linear_centered.py +""" +Linear Gaussian toy – centred parameterisation. +Matches plasma_linear_centered.stan (Langmore et al., arXiv:2103.07515). +""" +import numpy as np +import pymc as pm +import pytensor.tensor as pt + + +def build_L_pr(s, tau, delta): + """Cholesky of C_pr[i,j] = exp(-(s_i-s_j)^2/(2 tau^2)) + delta * 1{i=j}.""" + s = np.asarray(s, dtype=float) + C = np.exp(-((s[:, None] - s[None, :]) ** 2) / (2 * tau**2)) + C = C + delta * np.eye(len(s)) + return np.linalg.cholesky(C) + + +def make_model(data: dict) -> pm.Model: + N = int(data["N"]) + s = np.asarray(data["s"], dtype=float) + A = np.asarray(data["A"], dtype=float) + y = np.asarray(data["y"], dtype=float) + sigma = float(data["sigma"]) + tau = float(data["tau"]) + delta = float(data["delta"]) + + L_pr = build_L_pr(s, tau, delta) # constant; same as Stan transformed data + + with pm.Model() as model: + # x ~ N(0, C_pr) via Cholesky + x = pm.MvNormal("x", mu=np.zeros(N), chol=L_pr, shape=N) + pm.Normal("y_obs", mu=pt.dot(A, x), sigma=sigma, observed=y) + return model diff --git a/posterior_database/models/pymc/plasma_linear_noncentered.py b/posterior_database/models/pymc/plasma_linear_noncentered.py new file mode 100644 index 00000000..9a7894e7 --- /dev/null +++ b/posterior_database/models/pymc/plasma_linear_noncentered.py @@ -0,0 +1,33 @@ +# plasma_linear_noncentered.py +""" +Linear Gaussian toy – non-centred parameterisation. +Matches plasma_linear_noncentered.stan (Langmore et al., arXiv:2103.07515). +""" +import numpy as np +import pymc as pm +import pytensor.tensor as pt + + +def build_L_pr(s, tau, delta): + s = np.asarray(s, dtype=float) + C = np.exp(-((s[:, None] - s[None, :]) ** 2) / (2 * tau**2)) + C = C + delta * np.eye(len(s)) + return np.linalg.cholesky(C) + + +def make_model(data: dict) -> pm.Model: + N = int(data["N"]) + s = np.asarray(data["s"], dtype=float) + A = np.asarray(data["A"], dtype=float) + y = np.asarray(data["y"], dtype=float) + sigma = float(data["sigma"]) + tau = float(data["tau"]) + delta = float(data["delta"]) + + L_pr = build_L_pr(s, tau, delta) + + with pm.Model() as model: + Z = pm.Normal("Z", 0.0, 1.0, shape=N) + x = pm.Deterministic("x", pt.dot(L_pr, Z)) # same name as Stan transformed param + pm.Normal("y_obs", mu=pt.dot(A, x), sigma=sigma, observed=y) + return model diff --git a/posterior_database/models/stan/plasma_linear_centered.stan b/posterior_database/models/stan/plasma_linear_centered.stan new file mode 100644 index 00000000..ac87fe35 --- /dev/null +++ b/posterior_database/models/stan/plasma_linear_centered.stan @@ -0,0 +1,41 @@ +// Linear Gaussian toy version of the plasma model, centred ("direct") parameterization. +// Langmore et al. (2022), arXiv:2103.07515, eqs. (1)-(2) and Fig. 4. +// +// x ~ N(0, C_pr), y ~ N(A x, sigma^2 I) +// C_pr[i, j] = exp(-(s_i - s_j)^2 / (2 tau^2)) + delta * 1{i = j} +// +// Same posterior as plasma_linear_noncentered.stan, but sampled directly in x. +// With the default data it is much worse conditioned (larger kappa), which is +// the paper's point in Fig. 4. Its log density differs from the non-centred +// model's by the constant log|det L_pr|. + +data { + int N; + int M; + vector[N] s; + matrix[M, N] A; + vector[M] y; + real sigma; + real tau; + real delta; +} + +transformed data { + matrix[N, N] L_pr; + { + matrix[N, N] C; + for (i in 1:N) + for (j in 1:N) + C[i, j] = exp(-square(s[i] - s[j]) / (2 * square(tau))); + L_pr = cholesky_decompose(add_diag(C, delta)); + } +} + +parameters { + vector[N] x; +} + +model { + target += multi_normal_cholesky_lpdf(x | rep_vector(0, N), L_pr); + target += normal_lpdf(y | A * x, sigma); +} diff --git a/posterior_database/models/stan/plasma_linear_noncentered.stan b/posterior_database/models/stan/plasma_linear_noncentered.stan new file mode 100644 index 00000000..11ca560a --- /dev/null +++ b/posterior_database/models/stan/plasma_linear_noncentered.stan @@ -0,0 +1,43 @@ +// Linear Gaussian toy version of the plasma model, non-centred parameterization. +// Langmore et al. (2022), arXiv:2103.07515, eqs. (1), (15) and Fig. 4. +// +// Z ~ N(0, I), x = L_pr Z, y ~ N(A x, sigma^2 I) +// C_pr[i, j] = exp(-(s_i - s_j)^2 / (2 tau^2)) + delta * 1{i = j} +// +// This is the "prior reparameterization" of sec. 4.2. The posterior is exactly +// Gaussian; plasma_linear_reference.json holds its analytic mean and sd. + +data { + int N; // unknowns + int M; // measurements + vector[N] s; // grid locations of the unknowns + matrix[M, N] A; // forward matrix + vector[M] y; // measurements + real sigma; // noise sd + real tau; // prior correlation length + real delta; // shrinkage on the diagonal +} + +transformed data { + matrix[N, N] L_pr; + { + matrix[N, N] C; + for (i in 1:N) + for (j in 1:N) + C[i, j] = exp(-square(s[i] - s[j]) / (2 * square(tau))); + L_pr = cholesky_decompose(add_diag(C, delta)); + } +} + +parameters { + vector[N] Z; +} + +transformed parameters { + vector[N] x = L_pr * Z; +} + +model { + target += std_normal_lpdf(Z); + target += normal_lpdf(y | A * x, sigma); +} diff --git a/posterior_database/models/stan/plasma_shell.stan b/posterior_database/models/stan/plasma_shell.stan new file mode 100644 index 00000000..558ead66 --- /dev/null +++ b/posterior_database/models/stan/plasma_shell.stan @@ -0,0 +1,118 @@ +// Plasma "shell" model: spectroscopic tomography with a radially symmetric, +// randomly shifted-centre profile for amplitude, temperature and velocity. +// Langmore, Dikovsky, Geraedts, Norgaard, von Behren (2022), arXiv:2103.07515, sec. 2.3. +// +// Choices NOT fixed by the paper (must match the PyMC version): +// * profile prior covariance: exp(-|r-r'|^2 / (2 tau^2)) + delta * I (delta on the diagonal only) +// * one centre shared by A, T and V, centre ~ N(0, sigma_c^2 I) +// * piecewise-linear interpolation of radial profiles, constant beyond the grid ends +// * sigma and sigma_p are fixed data, not inferred +// * w = sqrt(T) / nu_0, as printed in the paper +// The full normalised density is used (target += ...), so log_prob is directly +// comparable with PyMC's model.logp(). + +functions { + // Piecewise-linear interpolation on an ascending grid; constant outside it. + real interp_lin(real r, vector grid, vector vals) { + int n = rows(grid); + if (r <= grid[1]) return vals[1]; + if (r >= grid[n]) return vals[n]; + int lo = 1; + int hi = n; + while (hi - lo > 1) { + int mid = (lo + hi) %/% 2; + if (grid[mid] <= r) lo = mid; else hi = mid; + } + real t = (r - grid[lo]) / (grid[hi] - grid[lo]); + return (1 - t) * vals[lo] + t * vals[hi]; + } + + // Noise-free chord spectra (M x K) for given radial profiles and centre. + matrix mu_fn(vector fA, vector fT, vector fV, vector ctr, + matrix xy, vector r_grid, vector nu_inv, real nu_0, + matrix I_mat, real c_A, real c_T, real c_V) { + int P = rows(xy); + int K = rows(nu_inv); + vector[P] A; + vector[P] Temp; + vector[P] V; + for (p in 1:P) { + // 1e-12 keeps the gradient finite if a pixel sits exactly on the centre + real r = sqrt(square(xy[p, 1] - ctr[1]) + square(xy[p, 2] - ctr[2]) + 1e-12); + A[p] = c_A * log1p_exp(interp_lin(r, r_grid, fA)); // softplus + Temp[p] = c_T * log1p_exp(interp_lin(r, r_grid, fT)); // softplus + V[p] = c_V * interp_lin(r, r_grid, fV); + } + vector[P] w = sqrt(Temp) / nu_0; + vector[P] pref = A ./ (sqrt(2 * pi()) * w); + vector[P] inv_2w2 = inv(2 * square(w)); + vector[P] nu_tilde_inv = (1 - V) / nu_0; // = 1 / nu_tilde, no singularity at V = 1 + matrix[P, K] emis; + for (k in 1:K) + emis[, k] = pref .* exp(-square(nu_inv[k] - nu_tilde_inv) .* inv_2w2); + return I_mat * emis; + } +} + +data { + int P; // pixels + int M; // chords + int K; // frequencies + int R; // radial nodes + + vector[K] nu; + real nu_0; + matrix[M, P] I_mat; // chord integration matrix + matrix[M, K] Y; + matrix[P, 2] xy; // pixel coordinates + vector[R] r_grid; // strictly ascending radial nodes + + real tau; // prior correlation length + real delta; // shrinkage on the diagonal + real sigma_c; // sd of the centre prior + + real c_A; + real c_T; + real c_V; + real sigma; // additive noise sd + real sigma_p; // proportional noise (model error) +} + +transformed data { + vector[K] nu_inv = inv(nu); + matrix[R, R] L_pr; + for (i in 2:R) + if (r_grid[i] <= r_grid[i - 1]) + reject("r_grid must be strictly ascending"); + { + matrix[R, R] C; + for (i in 1:R) + for (j in 1:R) + C[i, j] = exp(-square(r_grid[i] - r_grid[j]) / (2 * square(tau))); + L_pr = cholesky_decompose(add_diag(C, delta)); + } +} + +parameters { + vector[R] Z_A; // non-centred radial profiles + vector[R] Z_T; + vector[R] Z_V; + vector[2] c_raw; // standardised centre +} + +transformed parameters { + vector[2] ctr = sigma_c * c_raw; + vector[R] fA = L_pr * Z_A; // X_tilde: correlated radial profiles + vector[R] fT = L_pr * Z_T; + vector[R] fV = L_pr * Z_V; +} + +model { + matrix[M, K] mu = mu_fn(fA, fT, fV, ctr, xy, r_grid, nu_inv, nu_0, + I_mat, c_A, c_T, c_V); + matrix[M, K] sd_Y = sqrt(square(sigma) + square(sigma_p) * square(mu)); + + target += std_normal_lpdf(Z_A) + std_normal_lpdf(Z_T) + std_normal_lpdf(Z_V) + + std_normal_lpdf(c_raw); + target += normal_lpdf(to_vector(Y) | to_vector(mu), to_vector(sd_Y)); +}