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.
@@ -0,0 +1,518 @@
1
+ """
2
+ covariance_field.py
3
+ -------------------
4
+
5
+ Covariance field abstraction for spatially-varying Σ(x).
6
+
7
+ A covariance field represents a function from stimulus locations to covariance
8
+ matrices, encapsulating the spatially-varying perceptual uncertainty in WPPM.
9
+
10
+ Design
11
+ ------
12
+ This module provides:
13
+ - CovarianceField: Protocol defining the interface
14
+ - WPPMCovarianceField: Concrete implementation for WPPM models
15
+ - construction from priors, posteriors, or arbitrary parameters
16
+
17
+ Mathematical Background
18
+ -----------------------
19
+ In the Wishart Process Psychophysical Model:
20
+ Σ(x) = U(x) @ U(x)^T + λI
21
+
22
+ where:
23
+ U(x) = Σ_ij W_ij * φ_ij(x) (basis expansion)
24
+ φ_ij(x) are Chebyshev basis functions
25
+ W_ij are learned coefficients
26
+ λ is a numerical stabilizer (diag_term)
27
+
28
+
29
+ Usage Examples
30
+ --------------
31
+ # Sample from prior
32
+ >>> model = WPPM(input_dim=2, prior=Prior(basis_degree=5), ...)
33
+ >>> field = WPPMCovarianceField.from_prior(model, key)
34
+ >>> Sigma = field.cov(x)
35
+
36
+ # From fitted posterior
37
+ >>> posterior = model.fit(data, optimizer=MAPOptimizer())
38
+ >>> field = posterior.get_covariance_field()
39
+ >>> Sigmas = field.cov_batch(X_grid)
40
+
41
+ # Access square root
42
+ >>> U = field.sqrt_cov(x)
43
+ """
44
+
45
+ from __future__ import annotations
46
+
47
+ import warnings
48
+ from typing import TYPE_CHECKING, Protocol, runtime_checkable
49
+
50
+ import jax
51
+ import jax.numpy as jnp
52
+
53
+ if TYPE_CHECKING:
54
+ import jax.random as jr
55
+
56
+
57
+ @runtime_checkable
58
+ class CovarianceField(Protocol):
59
+ """
60
+ Protocol for spatially-varying covariance fields Σ(x).
61
+
62
+ A covariance field maps stimulus locations x ∈ R^d to
63
+ covariance matrices Σ(x) ∈ R^{dxd}.
64
+
65
+ Methods
66
+ -------
67
+ __call__(x)
68
+ Evaluate field at one or more locations. Supports both single points
69
+ and arbitrary batch dimensions.
70
+ cov(x)
71
+ Evaluate Σ(x) at stimulus location x (deprecated, use __call__).
72
+ sqrt_cov(x)
73
+ Evaluate U(x) such that Σ(x) = U(x) @ U(x)^T + λI.
74
+ cov_batch(X)
75
+ Vectorized evaluation at multiple locations (deprecated, use __call__).
76
+
77
+ Notes
78
+ -----
79
+ This protocol enables polymorphic use of covariance fields from different
80
+ sources (prior samples, fitted posteriors, custom parameterizations).
81
+
82
+ The field is callable for mathematical elegance and JAX compatibility:
83
+ Sigma = field(x) # Single point or batch
84
+ """
85
+
86
+ def __call__(self, x: jnp.ndarray) -> jnp.ndarray:
87
+ """Evaluate covariance field at one or more stimulus locations."""
88
+ ...
89
+
90
+ def cov(self, x: jnp.ndarray) -> jnp.ndarray:
91
+ """Evaluate covariance matrix Σ(x) at stimulus location x (deprecated)."""
92
+ ...
93
+
94
+ def sqrt_cov(self, x: jnp.ndarray) -> jnp.ndarray:
95
+ """Evaluate "square root" matrix U(x) such that Σ(x) = U(x) @ U(x)^T + λI."""
96
+ ...
97
+
98
+ def cov_batch(self, X: jnp.ndarray) -> jnp.ndarray:
99
+ """Evaluate covariance at multiple locations (deprecated)."""
100
+ ...
101
+
102
+
103
+ class WPPMCovarianceField:
104
+ """
105
+ Covariance field for WPPM with Wishart process
106
+ Encapsulates model + parameters to provide clean evaluation interface
107
+ for Σ(x) and U(x).
108
+
109
+ Parameters
110
+ ----------
111
+ model : WPPM
112
+ Model providing evaluation logic (local_covariance, _compute_sqrt)
113
+ params : dict
114
+ Model parameters:
115
+ - MVP: {"log_diag": (input_dim,)}
116
+ - Wishart: {"W": (degree+1, degree+1, input_dim, embedding_dim)}
117
+ where embedding_dim = input_dim + extra_embedding_dims
118
+
119
+ Note: The 3rd dimension is input_dim (output/stimulus space), not
120
+ embedding_dim. This matches the einsum in _compute_sqrt where U(x) has
121
+ shape (input_dim, embedding_dim).
122
+
123
+ Attributes
124
+ ----------
125
+ model : WPPM
126
+ Associated model instance
127
+ params : dict
128
+ Parameter dictionary
129
+
130
+ Examples
131
+ --------
132
+ >>> # From prior
133
+ >>> model = WPPM(input_dim=2, prior=Prior(basis_degree=5), ...)
134
+ >>> field = WPPMCovarianceField.from_prior(model, key)
135
+ >>> Sigma = field.cov(jnp.array([0.5, 0.3]))
136
+ >>>
137
+ >>> # From posterior
138
+ >>> posterior = model.fit(data, optimizer=MAPOptimizer())
139
+ >>> field = posterior.get_covariance_field()
140
+ >>> Sigmas = field.cov_batch(X_grid)
141
+ >>>
142
+ >>> # Access square root (Wishart mode only)
143
+ >>> U = field.sqrt_cov(jnp.array([0.5, 0.3]))
144
+
145
+ Notes
146
+ -----
147
+ Implements the CovarianceField protocol for polymorphic use.
148
+ """
149
+
150
+ def __init__(self, model, params: dict):
151
+ """
152
+ Construct covariance field from model and parameters.
153
+
154
+ Parameters
155
+ ----------
156
+ model : WPPM
157
+ Model providing evaluation logic
158
+ params : dict
159
+ Parameter dictionary
160
+ """
161
+ self.model = model
162
+ self.params = params
163
+ # Pre-compile JIT batch evaluation path for performance
164
+ self._eval_batch_jitted = jax.jit(self._eval_batch_impl)
165
+
166
+ def __call__(self, x: jnp.ndarray) -> jnp.ndarray:
167
+ """
168
+ Evaluate covariance field at one or more stimulus locations.
169
+
170
+ Automatically dispatches to single-point or batch evaluation based on input shape.
171
+ Last axis must have size input_dim. Any number of batch dimensions supported.
172
+
173
+ Parameters
174
+ ----------
175
+ x : jnp.ndarray
176
+ - Single point: shape (input_dim,)
177
+ - Batch: shape (..., input_dim) where ... are arbitrary batch dimensions
178
+
179
+ Returns
180
+ -------
181
+ jnp.ndarray
182
+ Square covariance matrix/matrices. Shape adapts to stimulus dimensionality:
183
+ - Single point: shape (d, d) where d = model.input_dim
184
+ - Batch: shape (..., d, d) where d = model.input_dim
185
+
186
+ For input_dim=2: returns (2, 2) or (..., 2, 2)
187
+ For input_dim=3: returns (3, 3) or (..., 3, 3)
188
+
189
+ Raises
190
+ ------
191
+ ValueError
192
+ If last axis size != input_dim
193
+
194
+ Examples
195
+ --------
196
+ >>> # 2D stimulus space (e.g., isoluminant plane)
197
+ >>> model_2d = WPPM(input_dim=2, ...)
198
+ >>> field_2d = WPPMCovarianceField.from_prior(model_2d, key)
199
+ >>>
200
+ >>> # Single 2D point
201
+ >>> x = jnp.array([0.5, 0.3]) # Shape (2,)
202
+ >>> Sigma = field_2d(x) # Shape (2, 2)
203
+ >>>
204
+ >>> # Batch of 2D points
205
+ >>> X = jnp.array([[0.1, 0.2], [0.5, 0.5]]) # Shape (2, 2)
206
+ >>> Sigmas = field_2d(X) # Shape (2, 2, 2)
207
+ >>>
208
+ >>> # 2D spatial grid in 2D stimulus space
209
+ >>> X_grid = jnp.ones((10, 10, 2)) # Shape (10, 10, 2)
210
+ >>> Sigmas_grid = field_2d(X_grid) # Shape (10, 10, 2, 2)
211
+ >>>
212
+ >>> # 3D stimulus space (e.g., RGB)
213
+ >>> model_3d = WPPM(input_dim=3, ...)
214
+ >>> field_3d = WPPMCovarianceField.from_prior(model_3d, key)
215
+ >>>
216
+ >>> # Single 3D point
217
+ >>> x_3d = jnp.array([0.5, 0.3, 0.2]) # Shape (3,)
218
+ >>> Sigma_3d = field_3d(x_3d) # Shape (3, 3)
219
+ >>>
220
+ >>> # Batch of 3D points
221
+ >>> X_3d = jnp.ones((5, 10, 3)) # Shape (5, 10, 3)
222
+ >>> Sigmas_3d = field_3d(X_3d) # Shape (5, 10, 3, 3)
223
+
224
+ Notes
225
+ -----
226
+ For input_dim=1, single points must have shape (1,) not (). Use x[None]
227
+ if needed to convert scalar to shape (1,).
228
+ """
229
+ # Validate input dimension
230
+ if x.shape[-1] != self.model.input_dim:
231
+ raise ValueError(
232
+ f"Last axis must be input_dim={self.model.input_dim}, got {x.shape[-1]}"
233
+ )
234
+
235
+ # Dispatch logic:
236
+ # - x.ndim == 1: Single point -> call _eval_single()
237
+ # - x.ndim >= 2: Batch -> flatten, vmap, reshape
238
+
239
+ # Dispatch based on shape
240
+ if x.ndim == 1:
241
+ # Single point: shape (d,) -> (d, d) where d = model.input_dim
242
+ # E.g., input_dim=2: (2,) -> (2,2), input_dim=3: (3,) -> (3,3)
243
+ return self._eval_single(x)
244
+ else:
245
+ # Batch: shape (..., d) -> (..., d, d) where d = model.input_dim
246
+ # Returns square covariance matrices for each point in the batch
247
+ return self._eval_batch_jitted(x)
248
+
249
+ def _eval_single(self, x: jnp.ndarray) -> jnp.ndarray:
250
+ """
251
+ Evaluate covariance at a single stimulus location.
252
+
253
+ This is the base evaluation method that all other methods build upon.
254
+ Called directly for single points, vmapped for batches.
255
+
256
+ Parameters
257
+ ----------
258
+ x : jnp.ndarray, shape (input_dim,)
259
+ Single stimulus location
260
+
261
+ Returns
262
+ -------
263
+ jnp.ndarray, shape (input_dim, input_dim)
264
+ Covariance matrix Σ(x)
265
+ """
266
+ return self.model.local_covariance(self.params, x)
267
+
268
+ def _eval_batch_impl(self, X: jnp.ndarray) -> jnp.ndarray:
269
+ """
270
+ Batch evaluation implementation (vmapped single evaluation).
271
+
272
+ Strategy: Flatten -> vmap -> reshape
273
+ This handles arbitrary batch dimensions with a single vmap.
274
+
275
+ Parameters
276
+ ----------
277
+ X : jnp.ndarray, shape (..., input_dim)
278
+ Batch of stimulus locations with arbitrary batch dimensions
279
+
280
+ Returns
281
+ -------
282
+ jnp.ndarray, shape (..., input_dim, input_dim)
283
+ Batch of covariance matrices
284
+ """
285
+ input_dim = self.model.input_dim
286
+ batch_shape = X.shape[:-1] # Store original batch structure
287
+
288
+ # Flatten all batch dimensions: (..., input_dim) -> (n_total, input_dim)
289
+ X_flat = X.reshape(-1, input_dim)
290
+
291
+ # Vectorized evaluation: (n_total, input_dim) -> (n_total, input_dim, input_dim)
292
+ Sigmas_flat = jax.vmap(self._eval_single)(X_flat)
293
+
294
+ # Restore batch structure: (n_total, input_dim, input_dim) -> (..., input_dim, input_dim)
295
+ return Sigmas_flat.reshape(batch_shape + (input_dim, input_dim))
296
+
297
+ def cov(self, x: jnp.ndarray) -> jnp.ndarray:
298
+ """
299
+ Evaluate covariance matrix Σ(x) at stimulus location x.
300
+
301
+ .. deprecated::
302
+ Use `field(x)` instead for unified single/batch API.
303
+
304
+ Parameters
305
+ ----------
306
+ x : jnp.ndarray, shape (input_dim,)
307
+ Stimulus location in [0, 1]^d
308
+
309
+ Returns
310
+ -------
311
+ jnp.ndarray, shape (input_dim, input_dim)
312
+ Covariance matrix Σ(x) in stimulus space
313
+
314
+ Notes
315
+ -----
316
+ With the rectangular U design, this always returns stimulus-space
317
+ covariance (input_dim, input_dim), regardless of extra_dims.
318
+ """
319
+ warnings.warn(
320
+ "cov() is deprecated. Use field(x) instead for unified single/batch API.",
321
+ DeprecationWarning,
322
+ stacklevel=2,
323
+ )
324
+ if x.ndim != 1:
325
+ raise ValueError(
326
+ f"cov() only accepts single points with shape (input_dim,), got {x.shape}. "
327
+ f"Use field(X) for batches."
328
+ )
329
+ return self._eval_single(x)
330
+
331
+ def cov_batch(self, X: jnp.ndarray) -> jnp.ndarray:
332
+ """
333
+ Evaluate covariance at multiple locations (vectorized).
334
+
335
+ .. deprecated::
336
+ Use `field(X)` instead for unified single/batch API.
337
+
338
+ Parameters
339
+ ----------
340
+ X : jnp.ndarray, shape (n_points, input_dim)
341
+ Multiple stimulus locations
342
+
343
+ Returns
344
+ -------
345
+ jnp.ndarray, shape (n_points, dim, dim)
346
+ Covariance matrices at each location
347
+ """
348
+ warnings.warn(
349
+ "cov_batch() is deprecated. Use field(X) instead for unified single/batch API.",
350
+ DeprecationWarning,
351
+ stacklevel=2,
352
+ )
353
+ if X.ndim < 2:
354
+ raise ValueError(
355
+ f"cov_batch() expects batch with shape (n_points, input_dim), got {X.shape}. "
356
+ f"Use field(x) for single points."
357
+ )
358
+ return self._eval_batch_jitted(X)
359
+
360
+ @classmethod
361
+ def from_prior(cls, model, key: jr.KeyArray) -> WPPMCovarianceField:
362
+ """
363
+ Sample a covariance field from the prior.
364
+
365
+ Parameters
366
+ ----------
367
+ model : WPPM
368
+ Model defining prior distribution
369
+ key : jax.random.KeyArray
370
+ PRNG key for sampling
371
+
372
+ Returns
373
+ -------
374
+ WPPMCovarianceField
375
+ Field sampled from p(Σ(x))
376
+
377
+ Examples
378
+ --------
379
+ >>> model = WPPM(input_dim=2, prior=Prior(basis_degree=5), ...)
380
+ >>> field = WPPMCovarianceField.from_prior(model, jr.PRNGKey(42))
381
+ >>> Sigma = field.cov(jnp.array([0.5, 0.5]))
382
+ """
383
+ params = model.init_params(key)
384
+ return cls(model, params)
385
+
386
+ @classmethod
387
+ def from_posterior(cls, posterior) -> WPPMCovarianceField:
388
+ """
389
+ Create covariance field from fitted posterior.
390
+
391
+ Parameters
392
+ ----------
393
+ posterior : ParameterPosterior
394
+ Fitted posterior (e.g., from model.fit())
395
+
396
+ Returns
397
+ -------
398
+ WPPMCovarianceField
399
+ Field representing posterior estimate of Σ(x)
400
+
401
+ Notes
402
+ -----
403
+ For MAP posteriors, uses θ_MAP.
404
+ For variational posteriors, could use posterior mean or sample.
405
+
406
+ Examples
407
+ --------
408
+ >>> posterior = model.fit(data, optimizer=MAPOptimizer())
409
+ >>> field = WPPMCovarianceField.from_posterior(posterior)
410
+ >>> Sigma = field.cov(x)
411
+ """
412
+ return cls(posterior._model, posterior.params)
413
+
414
+ @classmethod
415
+ def from_params(cls, model, params: dict) -> WPPMCovarianceField:
416
+ """
417
+ Create field from arbitrary parameters.
418
+
419
+ Useful for:
420
+ - Custom initialization
421
+ - Posterior samples
422
+ - Intermediate optimization checkpoints
423
+ - Testing
424
+
425
+ Parameters
426
+ ----------
427
+ model : WPPM
428
+ Model providing evaluation logic
429
+ params : dict
430
+ Parameter dictionary
431
+
432
+ Returns
433
+ -------
434
+ WPPMCovarianceField
435
+
436
+ Examples
437
+ --------
438
+ >>> params = {"log_diag": jnp.array([0.1, 0.2])}
439
+ >>> field = WPPMCovarianceField.from_params(model, params)
440
+ """
441
+ return cls(model, params)
442
+
443
+ def sqrt_cov(self, x: jnp.ndarray) -> jnp.ndarray:
444
+ """
445
+ Evaluate U(x) such that Σ(x) = U(x) @ U(x)^T + diag_term*I.
446
+
447
+ Parameters
448
+ ----------
449
+ x : jnp.ndarray, shape (input_dim,)
450
+ Stimulus location
451
+
452
+ Returns
453
+ -------
454
+ jnp.ndarray, shape (input_dim, embedding_dim)
455
+ Rectangular square root matrix U(x).
456
+ embedding_dim = input_dim + extra_dims
457
+
458
+
459
+ Notes
460
+ -----
461
+ Only available in Wishart mode. MVP mode uses diagonal parameterization
462
+ without explicit U matrices.
463
+
464
+ In the rectangular design (Hong et al.), U is (input_dim, embedding_dim).
465
+
466
+ Examples
467
+ --------
468
+ >>> # Wishart mode
469
+ >>> model = WPPM(input_dim=2, basis_degree=5, extra_dims=1, ...)
470
+ >>> field = WPPMCovarianceField.from_prior(model, key)
471
+ >>> U = field.sqrt_cov(jnp.array([0.5, 0.3]))
472
+ >>> print(U.shape) # (2, 3) for input_dim=2, extra_dims=1
473
+ >>>
474
+ >>> # Verify: Σ = U @ U^T + λI
475
+ >>> Sigma_from_U = U @ U.T + model.diag_term * jnp.eye(2)
476
+ >>> Sigma_direct = field.cov(x)
477
+ >>> assert jnp.allclose(Sigma_from_U, Sigma_direct)
478
+ """
479
+ if "W" not in self.params:
480
+ raise ValueError(
481
+ "sqrt_cov only available in Wishart mode. "
482
+ "Set basis_degree when creating WPPM to use Wishart process."
483
+ )
484
+ return self.model._compute_sqrt(self.params, x)
485
+
486
+ def sqrt_cov_batch(self, X: jnp.ndarray) -> jnp.ndarray:
487
+ """
488
+ Vectorized evaluation of U(x) at multiple locations.
489
+
490
+ Parameters
491
+ ----------
492
+ X : jnp.ndarray, shape (n_points, input_dim)
493
+ Multiple stimulus locations
494
+
495
+ Returns
496
+ -------
497
+ jnp.ndarray, shape (n_points, input_dim, embedding_dim)
498
+ Rectangular square root matrices at each location.
499
+ embedding_dim = input_dim + extra_dims
500
+
501
+ Raises
502
+ ------
503
+ ValueError
504
+ If in MVP mode.
505
+
506
+ Notes
507
+ -----
508
+ In the rectangular design (Hong et al.), U is (input_dim, embedding_dim).
509
+
510
+ Examples
511
+ --------
512
+ >>> X_grid = jnp.array([[0.1, 0.2], [0.5, 0.5], [0.9, 0.8]])
513
+ >>> U_batch = field.sqrt_cov_batch(X_grid)
514
+ >>> print(U_batch.shape) # (3, 2, 3) for input_dim=2, extra_dims=1
515
+ """
516
+ if "W" not in self.params:
517
+ raise ValueError("sqrt_cov_batch only available in Wishart mode")
518
+ return jax.vmap(self.sqrt_cov)(X)