psyphy 0.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
psyphy/model/wppm.py ADDED
@@ -0,0 +1,531 @@
1
+ """
2
+ wppm.py
3
+ -------
4
+
5
+ Wishart Process Psychophysical Model (WPPM)
6
+
7
+ Goals
8
+ -----
9
+ Wishart Process Psychophysical Model (WPPM):
10
+ - Expose hyperparameters needed to for example use Model config used in Hong et al.:
11
+ * extra_dims: embedding size for basis expansions
12
+ * variance_scale: global covariance scale
13
+ * decay_rate: smoothness/length-scale for covariance field
14
+ * diag_term: numerical stabilizer added to covariance diagonals
15
+
16
+ All numerics use JAX (jax.numpy as jnp) to support autodiff and optax optimizers
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from typing import Any
22
+
23
+ import jax
24
+ import jax.numpy as jnp
25
+
26
+ from psyphy.utils.math import chebyshev_basis
27
+
28
+ from .base import Model
29
+ from .likelihood import TaskLikelihood
30
+ from .prior import Prior
31
+
32
+ # Type aliases for readability
33
+ Params = dict[str, jnp.ndarray]
34
+ # A "stimulus" is a pair (reference, comparison) in model space (shape: (input_dim,))
35
+ Stimulus = tuple[jnp.ndarray, jnp.ndarray]
36
+
37
+
38
+ class WPPM(Model):
39
+ """
40
+ Wishart Process Psychophysical Model (WPPM).
41
+
42
+ Parameters
43
+ ----------
44
+ input_dim : int
45
+ Dimensionality of the *input stimulus space* (e.g., 2 for isoluminant plane,
46
+ 3 for RGB). Both reference and comparison live in R^{input_dim}.
47
+ prior : Prior
48
+ Prior distribution over model parameters. Controls basis_degree in WPPM (basis expansion).
49
+ The WPPM delegates
50
+ to prior.basis_degree to ensure consistency between parameter sampling and
51
+ basis evaluation.
52
+ likelihood : TaskLikelihood
53
+ Psychophysical task mapping that defines how discriminability translates
54
+ to p(correct) and how log-likelihood of responses is computed.
55
+ (e.g., OddityTask)
56
+ noise : Any, optional
57
+ Noise model describing internal representation noise (e.g., GaussianNoise).
58
+
59
+ hyperparameters
60
+ -----------------------------------
61
+ extra_dims : int, default=0
62
+ Additional embedding dimensions for basis expansions (beyond input_dim).
63
+ embedding_dim = input_dim + extra_dims.
64
+ variance_scale : float, default=1.0
65
+ Global scaling factor for covariance magnitude
66
+ decay_rate : float, default=1.0
67
+ Smoothness/length-scale for spatial covariance variation
68
+ diag_term : float, default=1e-6
69
+ Small positive value added to the covariance diagonal for numerical stability.
70
+
71
+ **model_kwargs : Any
72
+ Reserved for *future* keyword arguments accepted by the base `Model.__init__`.
73
+ Do not pass WPPM math knobs or task/likelihood knobs here.
74
+ """
75
+
76
+ def __init__(
77
+ self,
78
+ prior: Prior,
79
+ likelihood: TaskLikelihood,
80
+ noise: Any | None = None,
81
+ *, # everything after here is keyword-only
82
+ input_dim: int = 2,
83
+ extra_dims: int = 1,
84
+ variance_scale: float = 4e-3,
85
+ decay_rate: float = 0.4,
86
+ diag_term: float = 1e-6,
87
+ **model_kwargs: Any,
88
+ ) -> None:
89
+ # Base-model configuration.
90
+ #
91
+ # `model_kwargs` is reserved for *future* base `Model.__init__` kwargs.
92
+ # It should NOT be used for WPPM-specific math (e.g. alternative covariance
93
+ # parameterizations) or for task-specific likelihood knobs.
94
+ if model_kwargs:
95
+ known_misuses = {"num_samples", "bandwidth", "online_config"}
96
+ bad = sorted(known_misuses.intersection(model_kwargs.keys()))
97
+ if bad:
98
+ raise TypeError(
99
+ "Do not pass task-specific kwargs via WPPM(..., **model_kwargs). "
100
+ f"Move {bad} into the task config (e.g. OddityTaskConfig)."
101
+ )
102
+
103
+ super().__init__(**model_kwargs)
104
+
105
+ # --- core components ---
106
+ self.input_dim = int(input_dim) # stimulus-space dimensionality
107
+ self.prior = prior # prior over parameter PyTree
108
+
109
+ if self.prior.input_dim != self.input_dim:
110
+ raise ValueError(
111
+ f"Dimension mismatch: Model initialized with input_dim={self.input_dim}, "
112
+ f"but Prior expects input_dim={self.prior.input_dim}."
113
+ )
114
+
115
+ self.likelihood = likelihood # task mapping and likelihood
116
+ self.noise = noise # noise model
117
+
118
+ self.extra_dims = int(extra_dims)
119
+ self.variance_scale = float(variance_scale)
120
+ self.decay_rate = float(decay_rate)
121
+ self.diag_term = float(diag_term)
122
+
123
+ @property
124
+ def basis_degree(self) -> int | None:
125
+ """
126
+ Chebyshev polynomial degree for Wishart process basis expansion.
127
+
128
+ This property delegates to self.prior.basis_degree to ensure consistency
129
+ between parameter sampling and basis evaluation.
130
+
131
+ Returns
132
+ -------
133
+ int | None
134
+ Degree of Chebyshev polynomial basis (0 = constant, 1 = linear, etc.)
135
+
136
+ Notes
137
+ -----
138
+ WPPM gets its basis_degree parameter from Prior.basis_degree.
139
+ """
140
+ return self.prior.basis_degree
141
+
142
+ @property
143
+ def embedding_dim(self) -> int:
144
+ """
145
+ Dimension of the embedding space.
146
+
147
+ embedding_dim = input_dim + extra_dims.
148
+ this represents the full perceptual space where:
149
+ - First input_dim dimensions correspond to observable stimulus features
150
+ - Remaining extra_dims are latent dimensions
151
+
152
+ Returns
153
+ -------
154
+ int
155
+ input_dim + extra_dims
156
+
157
+ Notes
158
+ -----
159
+ This is a computed property, not a constructor parameter.
160
+ """
161
+ if self.basis_degree is None:
162
+ raise ValueError("Basis degree must be set for embedding.")
163
+ # Wishart mode: full perceptual space
164
+ return self.input_dim + self.extra_dims
165
+
166
+ def _validate_basis_input(self, x: jnp.ndarray) -> None:
167
+ """Validate that inputs are in the expected basis domain.
168
+
169
+ Design contract (current):
170
+ - WPPM does **not** normalize stimuli.
171
+ - Users must provide stimulus coordinates already in the basis domain.
172
+
173
+ For the current Chebyshev basis implementation, the domain is ``[-1, 1]``
174
+ per dimension.
175
+
176
+ Notes
177
+ -----
178
+ This is intentionally a lightweight, eager validator (Python exceptions).
179
+ If we later need fully-jittable checks, we can replace this with
180
+ ``jax.experimental.checkify``.
181
+ """
182
+
183
+ x = jnp.asarray(x)
184
+ if x.ndim != 1 or x.shape[0] != self.input_dim:
185
+ raise ValueError(
186
+ f"Expected x with shape ({self.input_dim},), got {tuple(x.shape)}"
187
+ )
188
+
189
+ # NOTE: This method may be called from jitted code paths.
190
+ # Avoid Python bool/float conversions on JAX tracers.
191
+ #
192
+ # Strategy:
193
+ # - If x is concrete (non-traced), do normal Python ('eager') exceptions.
194
+ # - If x is traced (e.g., under jit/vmap), skip eager checks to
195
+ # remain JIT-compatible.
196
+ # JAX tracing produces Tracer objects (not concrete values). Eager validation
197
+ # (Python exceptions) is only safe on concrete arrays.
198
+ if isinstance(x, jax.core.Tracer):
199
+ return
200
+
201
+ if jnp.any(~jnp.isfinite(x)):
202
+ raise ValueError("Stimulus x contains NaN/Inf.")
203
+
204
+ # Chebyshev basis expects inputs in [-1, 1].
205
+ tol = 1e-6
206
+ if jnp.any(x < (-1.0 - tol)) or jnp.any(x > (1.0 + tol)):
207
+ x_min = float(jnp.min(x))
208
+ x_max = float(jnp.max(x))
209
+ raise ValueError(
210
+ "Stimulus x is outside the Chebyshev domain [-1, 1]. "
211
+ f"Observed min={x_min:g}, max={x_max:g}. "
212
+ "Normalize your data to align with domain of basis "
213
+ "in order to avoid unexpected behavior."
214
+ )
215
+
216
+ # ----------------------------------------------------------------------
217
+ # PARAMETERS
218
+ # ----------------------------------------------------------------------
219
+ def init_params(self, key: jax.Array) -> Params:
220
+ """Sample initial parameters from the prior.
221
+
222
+ Returns
223
+ -------
224
+ params : dict[str, jnp.ndarray]
225
+ """
226
+ return self.prior.sample_params(key)
227
+
228
+ # ----------------------------------------------------------------------
229
+ # WISHART PROCESS COVARIANCE
230
+ # ----------------------------------------------------------------------
231
+ def _evaluate_basis_at_point(self, x: jnp.ndarray) -> jnp.ndarray:
232
+ """
233
+ Evaluate all Chebyshev basis functions at point x, keeping structure for einsum.
234
+
235
+ For 2D: returns phi_ij(x) = T_i(x_1) * T_j(x_2) with shape (degree+1, degree+1)
236
+ For 3D: returns phi_ijk(x) = T_i(x_1) * T_j(x_2) * T_k(x_3) with shape (degree+1, degree+1, degree+1)
237
+
238
+ Note: chebyshev_basis(x, degree=d) returns (degree+1) basis functions [T_0, ..., T_d].
239
+
240
+ Parameters
241
+ ----------
242
+ x : jnp.ndarray, shape (input_dim,)
243
+ Stimulus coordinates in the Chebyshev domain ``[-1, 1]``.
244
+ The model does not normalize inputs; callers must normalize upstream.
245
+
246
+ Returns
247
+ -------
248
+ phi : jnp.ndarray
249
+ Basis function values with structured shape for efficient einsum.
250
+ Shape is (degree+1, degree+1) for 2D or (degree+1, degree+1, degree+1) for 3D.
251
+ """
252
+
253
+ if self.basis_degree is None:
254
+ raise ValueError(
255
+ "Cannot evaluate basis: basis_degree is None. "
256
+ "Set basis_degree to a valid integer."
257
+ )
258
+
259
+ self._validate_basis_input(x)
260
+ x_norm = x
261
+
262
+ if self.input_dim == 2:
263
+ # Evaluate basis functions: \phi_ij(x) = T_i(x_1) * T_j(x_2)
264
+ # chebyshev_basis returns (1, degree+1) for each dimension
265
+ cheb_0 = chebyshev_basis(x_norm[0:1], degree=self.basis_degree)[
266
+ 0, :
267
+ ] # (degree+1,)
268
+ cheb_1 = chebyshev_basis(x_norm[1:2], degree=self.basis_degree)[
269
+ 0, :
270
+ ] # (degree+1,)
271
+ phi = cheb_0[:, None] * cheb_1[None, :] # (degree+1, degree+1)
272
+
273
+ elif self.input_dim == 3:
274
+ # 3D case: \phi_ijk(x) = T_i(x_1) * T_j(x_2) * T_k(x_3)
275
+ # phi.shape = (degree+1, degree+1, degree+1)
276
+ cheb_0 = chebyshev_basis(x_norm[0:1], degree=self.basis_degree)[0, :]
277
+ cheb_1 = chebyshev_basis(x_norm[1:2], degree=self.basis_degree)[0, :]
278
+ cheb_2 = chebyshev_basis(x_norm[2:3], degree=self.basis_degree)[0, :]
279
+ phi = cheb_0[:, None, None] * cheb_1[None, :, None] * cheb_2[None, None, :]
280
+
281
+ else:
282
+ raise NotImplementedError(
283
+ f"Wishart process currently only supports 2D and 3D. Got input_dim={self.input_dim}"
284
+ )
285
+
286
+ return phi
287
+
288
+ def _compute_sqrt(self, params: Params, x: jnp.ndarray) -> jnp.ndarray:
289
+ r"""
290
+ Compute "square root" matrix U(x) from basis expansion.
291
+
292
+ This is the core of the Wishart process: U(x) = Σ_ij W_ij * \phi_ij(x)
293
+ where W_ij are learned coefficients and \phi_ij are Chebyshev basis functions.
294
+
295
+ The covariance is then Σ(x) = U(x) @ U(x)^T + diag_term * I, which is
296
+ guaranteed to be positive definite.
297
+
298
+ Parameters
299
+ ----------
300
+ params : dict
301
+ Model parameters. Must contain "W" for Wishart mode.
302
+ x : jnp.ndarray, shape (input_dim,)
303
+ Stimulus location
304
+
305
+ Returns
306
+ -------
307
+ U : jnp.ndarray, shape (input_dim, embedding_dim)
308
+ Rectangular square root matrix if extra_dims > 0.
309
+ embedding_dim = input_dim + extra_dims
310
+
311
+ Raises
312
+ ------
313
+ ValueError
314
+ If params doesn't contain "W" (not in Wishart mode)
315
+
316
+ Notes
317
+ -----
318
+ U is rectangular when extra_dims > 0.
319
+ When multiplied U @ U^T, this produces covariance in stimulus space:
320
+ Σ(x) \in R^(input_dim x input_dim)
321
+ """
322
+ if "W" not in params:
323
+ raise ValueError("Cannot compute U(x): params missing 'W'. ")
324
+
325
+ W = params["W"]
326
+ phi = self._evaluate_basis_at_point(x)
327
+
328
+ # Linear combination: U(x) = Σ_ij W_ij * phi_ij(x)
329
+ # Einstein summation over basis function indices
330
+ if self.input_dim == 2:
331
+ # W[i,j,d,e] * phi[i,j] -> U[d,e]
332
+ # W is (degree+1, degree+1, input_dim, embedding_dim)
333
+ # U is rectangular if extra_dims > 0: (input_dim, embedding_dim)
334
+ U = jnp.einsum("ijde,ij->de", W, phi)
335
+ elif self.input_dim == 3:
336
+ # W[i,j,k,d,e] * phi[i,j,k] -> U[d,e]
337
+ # W is (degree+1, degree+1, degree+1, input_dim, embedding_dim)
338
+ # U is rectangular if extra_dims > 0: (input_dim, embedding_dim)
339
+ U = jnp.einsum("ijkde,ijk->de", W, phi)
340
+ else:
341
+ raise NotImplementedError(
342
+ f"Wishart process only supports 2D and 3D. Got input_dim={self.input_dim}"
343
+ )
344
+
345
+ return U
346
+
347
+ # ----------------------------------------------------------------------
348
+ # LOCAL COVARIANCE (Σ(x))
349
+ # ----------------------------------------------------------------------
350
+ def local_covariance(self, params: Params, x: jnp.ndarray) -> jnp.ndarray:
351
+ """
352
+ Return local covariance Σ(x) at stimulus location x.
353
+
354
+
355
+ Wishart mode (basis_degree set):
356
+ Σ(x) = U(x) @ U(x)^T + diag_term * I
357
+ where U(x) is rectangular (input_dim, embedding_dim) if extra_dims > 0.
358
+ - Varies smoothly with x
359
+ - Guaranteed positive-definite
360
+ - Returns stimulus covariance directly (input_dim, input_dim)
361
+
362
+ Parameters
363
+ ----------
364
+ params : dict
365
+ Model parameters:
366
+ - WPPM: {"W": (degree+1, ..., input_dim, embedding_dim)}
367
+ x : jnp.ndarray, shape (input_dim,)
368
+ Stimulus location
369
+
370
+ Returns
371
+ -------
372
+ Σ : jnp.ndarray, shape (input_dim, input_dim)
373
+ Covariance matrix in stimulus space.
374
+ """
375
+ # WPPM: spatially-varying covariance
376
+ if "W" in params:
377
+ U = self._compute_sqrt(params, x) # (input_dim, embedding_dim)
378
+ # Σ(x) = U(x) @ U(x)^T + diag_term * I
379
+ # Result is (input_dim, input_dim)
380
+ Sigma = U @ U.T + self.diag_term * jnp.eye(self.input_dim)
381
+ return Sigma
382
+
383
+ raise ValueError("params must contain 'W' (weights of WPPM)")
384
+
385
+ # ----------------------------------------------------------------------
386
+ # PREDICTION (delegates to likelihood)
387
+ # ----------------------------------------------------------------------
388
+ def predict_prob(
389
+ self, params: Params, stimulus: Stimulus, **likelihood_kwargs: Any
390
+ ) -> jnp.ndarray:
391
+ """
392
+ Predict probability of a correct response for a single stimulus.
393
+
394
+ Design choice:
395
+ WPPM computes discriminability & covariance; the LIKELIHOOD defines how
396
+ that translates to performance. We therefore delegate to:
397
+ likelihood.predict(params, stimulus, model=self, noise=self.noise)
398
+
399
+ Parameters
400
+ ----------
401
+ params : dict
402
+ stimulus : tuple[jnp.ndarray, jnp.ndarray]
403
+ (reference, comparison) pair in model space.
404
+
405
+ Returns
406
+ -------
407
+ p_correct : jnp.ndarray
408
+ """
409
+ # Strict task-owned configuration:
410
+ # - MC control knobs (e.g. num_samples/bandwidth) live in the task config.
411
+ # - WPPM.predict_prob therefore does not accept task-specific kwargs.
412
+ if likelihood_kwargs:
413
+ raise TypeError(
414
+ f"WPPM.predict_prob got unexpected kwargs: {likelihood_kwargs}. "
415
+ "Configure likelihood behavior via the TaskLikelihood object itself."
416
+ )
417
+
418
+ return self.likelihood.predict(params, stimulus, self, self.noise)
419
+
420
+ # ----------------------------------------------------------------------
421
+ # LIKELIHOOD (delegates to likelihood component)
422
+ # ----------------------------------------------------------------------
423
+ # TODO: add random key
424
+ def log_likelihood(
425
+ self,
426
+ params: Params,
427
+ refs: jnp.ndarray,
428
+ comparisons: jnp.ndarray,
429
+ responses: jnp.ndarray,
430
+ ) -> jnp.ndarray:
431
+ """
432
+ Compute the log-likelihood for arrays of trials.
433
+
434
+ IMPORTANT:
435
+ We delegate to the TaskLikelihood to avoid duplicating Bernoulli (MPV)
436
+ or MC likelihood logic in multiple places.
437
+
438
+ Parameters
439
+ ----------
440
+ params : dict
441
+ Model parameters.
442
+ refs : jnp.ndarray, shape (N, input_dim)
443
+ comparisons : jnp.ndarray, shape (N, input_dim)
444
+ responses : jnp.ndarray, shape (N,)
445
+ Typically 0/1; task may support richer encodings.
446
+
447
+ Returns
448
+ -------
449
+ loglik : jnp.ndarray
450
+ Scalar log-likelihood (task-only; add prior outside if needed)
451
+
452
+ Notes
453
+ -----
454
+ This method is intentionally strict and does not accept task-specific
455
+ runtime kwargs.
456
+
457
+ - Configure task behavior (e.g. MC fidelity/smoothing for ``OddityTask``)
458
+ via the task instance passed to the model.
459
+ - If you need reproducible randomness, pass a ``key`` when calling the
460
+ task directly.
461
+ """
462
+ # Delegate to the task on a batched, JAX-native dataset.
463
+ from psyphy.data.dataset import TrialData # local import to avoid cycles
464
+
465
+ data = TrialData(
466
+ refs=jnp.asarray(refs),
467
+ comparisons=jnp.asarray(comparisons),
468
+ responses=jnp.asarray(responses),
469
+ )
470
+ return self.likelihood.loglik(params, data, self, self.noise)
471
+
472
+ def log_likelihood_from_data(
473
+ self, params: Params, data: Any, *, key: jax.Array | None = None
474
+ ) -> jnp.ndarray:
475
+ """Compute log-likelihood directly from a batched data object.
476
+
477
+ Why delegate to the likelihood?
478
+ - The likelihood knows the decision rule (oddity, 2AFC, ...).
479
+ - The likelihood can use the model (this WPPM) to fetch discriminabilities.
480
+ - The likelihood can use the noise model if it needs MC simulation.
481
+
482
+ Parameters
483
+ ----------
484
+ params : dict
485
+ Model parameters.
486
+ data : TrialData (or any object with refs/comparisons/responses arrays)
487
+ Collected trial data.
488
+ key : jax.Array | None, optional
489
+ JAX random key for MC likelihood evaluation. When provided, a fresh
490
+ noise realization is drawn every call — required for correct stochastic
491
+ gradient estimates during optimization. When None, the task falls back
492
+ to ``OddityTaskConfig.default_key_seed`` (useful for fixed evaluation
493
+ and testing, but should not be used during gradient-based optimization).
494
+
495
+ Returns
496
+ -------
497
+ loglik : jnp.ndarray
498
+ Scalar log-likelihood (task-only; add prior outside if needed).
499
+ """
500
+ return self.likelihood.loglik(params, data, self, self.noise, key=key)
501
+
502
+ # ----------------------------------------------------------------------
503
+ # POSTERIOR-STYLE CONVENIENCE (OPTIONAL)
504
+ # ----------------------------------------------------------------------
505
+ def log_posterior_from_data(
506
+ self, params: Params, data: Any, *, key: jax.Array | None = None
507
+ ) -> jnp.ndarray:
508
+ """Compute log posterior from data.
509
+
510
+ This simply adds the prior log-probability to the task log-likelihood.
511
+ Inference engines (e.g., MAP optimizer) typically optimize this quantity.
512
+
513
+ Parameters
514
+ ----------
515
+ params : dict
516
+ Model parameters.
517
+ data : TrialData
518
+ Collected trial data.
519
+ key : jax.Array | None, optional
520
+ JAX random key for the MC likelihood. Must be provided during
521
+ optimization so each gradient step uses a fresh noise realization.
522
+ When None, falls back to ``OddityTaskConfig.default_key_seed``.
523
+
524
+ Returns
525
+ -------
526
+ jnp.ndarray
527
+ Scalar log posterior = loglik(params | data) + log_prior(params).
528
+ """
529
+ return self.log_likelihood_from_data(
530
+ params, data, key=key
531
+ ) + self.prior.log_prob(params)
@@ -0,0 +1,34 @@
1
+ """
2
+ posterior
3
+ =========
4
+
5
+ Posterior representations.
6
+
7
+ This subpackage provides:
8
+ - ParameterPosterior: protocol for posteriors over model parameters p(θ | data)
9
+ - MAPPosterior: delta distribution at θ_MAP (point estimate)
10
+
11
+ Two-tier design
12
+ ---------------
13
+ - ParameterPosterior: represents p(θ | data)
14
+ - PredictivePosterior: represents p(f(X*) | data)
15
+
16
+ Future extensions
17
+ -----------------
18
+ - LaplacePosterior: Gaussian approximation N(θ_MAP, Σ)
19
+ - NumpyroPosterior/BlackjaxPosterior: MCMC samples
20
+ """
21
+
22
+ from .parameter_posterior import ParameterPosterior
23
+ from .posterior import MAPPosterior
24
+ from .predictive_posterior import PredictivePosterior, WPPMPredictivePosterior
25
+
26
+ __all__ = [
27
+ # Core protocols
28
+ "ParameterPosterior",
29
+ "PredictivePosterior",
30
+ # Parameter posterior implementations
31
+ "MAPPosterior",
32
+ # Predictive posterior implementations
33
+ "WPPMPredictivePosterior",
34
+ ]
@@ -0,0 +1,87 @@
1
+ """
2
+ parameter_posterior.py
3
+ ---------------------
4
+
5
+ Protocol and implementations for posterior distributions over model parameters.
6
+
7
+ This module defines the ParameterPosterior interface representing p(θ | data),
8
+ used for research workflows: diagnostics, parameter uncertainty, sampling.
9
+
10
+ Design
11
+ ------
12
+ Different inference engines produce different posterior representations:
13
+ - MAP: delta distribution at θ_MAP
14
+ - MCMC: collection of samples
15
+
16
+ All implement a common protocol for polymorphic use.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from typing import TYPE_CHECKING, Protocol, runtime_checkable
22
+
23
+ if TYPE_CHECKING:
24
+ import jax.random as jr
25
+
26
+
27
+ @runtime_checkable
28
+ class ParameterPosterior(Protocol):
29
+ """
30
+ Protocol for posterior distributions over model parameters p(θ | data).
31
+
32
+ Returned by InferenceEngine.fit(model, data).
33
+ Used for diagnostics, parameter sampling, uncertainty.
34
+ """
35
+
36
+ @property
37
+ def params(self) -> dict:
38
+ """
39
+ Point estimate or posterior mean parameters.
40
+
41
+ Returns
42
+ -------
43
+ dict
44
+ Parameter PyTree (e.g., {"log_diag": jnp.ndarray, ...})
45
+
46
+ Notes
47
+ -----
48
+ - MAP: θ_MAP
49
+ - MCMC: posterior mean of samples
50
+ """
51
+ ...
52
+
53
+ @property
54
+ def model(self):
55
+ """
56
+ Associated generative model.
57
+
58
+ Returns
59
+ -------
60
+ Model
61
+ The WPPM or (other model) instance used for predictions.
62
+ """
63
+ ...
64
+
65
+ def sample(self, n: int, *, key: jr.KeyArray) -> dict:
66
+ """
67
+ Sample parameter vectors from p(θ | data).
68
+
69
+ Parameters
70
+ ----------
71
+ n : int
72
+ Number of samples
73
+ key : jax.random.KeyArray
74
+ PRNG key for randomness
75
+
76
+ Returns
77
+ -------
78
+ dict
79
+ Parameter PyTree with leading dimension n.
80
+
81
+
82
+ Notes
83
+ -----
84
+ - MAP: returns repeated θ_MAP
85
+ - Numpyro/Blackjax: returns stored samples (may subsample if n differs)
86
+ """
87
+ ...