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/__init__.py +126 -0
- psyphy/data/__init__.py +15 -0
- psyphy/data/dataset.py +303 -0
- psyphy/data/io.py +92 -0
- psyphy/inference/__init__.py +39 -0
- psyphy/inference/base.py +47 -0
- psyphy/inference/langevin.py +89 -0
- psyphy/inference/laplace.py +56 -0
- psyphy/inference/map_optimizer.py +245 -0
- psyphy/model/__init__.py +46 -0
- psyphy/model/base.py +77 -0
- psyphy/model/covariance_field.py +518 -0
- psyphy/model/likelihood.py +701 -0
- psyphy/model/noise.py +44 -0
- psyphy/model/prior.py +215 -0
- psyphy/model/wppm.py +531 -0
- psyphy/posterior/__init__.py +34 -0
- psyphy/posterior/parameter_posterior.py +87 -0
- psyphy/posterior/posterior.py +75 -0
- psyphy/posterior/predictive_posterior.py +287 -0
- psyphy/trial_placement/__init__.py +38 -0
- psyphy/trial_placement/grid.py +56 -0
- psyphy/trial_placement/sobol.py +65 -0
- psyphy/utils/__init__.py +19 -0
- psyphy/utils/math.py +104 -0
- psyphy-0.0.2.dist-info/METADATA +139 -0
- psyphy-0.0.2.dist-info/RECORD +29 -0
- psyphy-0.0.2.dist-info/WHEEL +4 -0
- psyphy-0.0.2.dist-info/licenses/LICENSE.md +21 -0
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""
|
|
2
|
+
posterior.py
|
|
3
|
+
------------
|
|
4
|
+
|
|
5
|
+
Concrete ParameterPosterior implementations.
|
|
6
|
+
|
|
7
|
+
This module provides:
|
|
8
|
+
- MAPPosterior: delta distribution at θ_MAP (point estimate)
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import jax
|
|
14
|
+
import jax.numpy as jnp
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class MAPPosterior:
|
|
18
|
+
"""
|
|
19
|
+
MAP (Maximum A Posteriori) posterior - delta distribution at θ_MAP.
|
|
20
|
+
|
|
21
|
+
Represents a point estimate with no uncertainty.
|
|
22
|
+
|
|
23
|
+
Parameters
|
|
24
|
+
----------
|
|
25
|
+
params : dict
|
|
26
|
+
MAP parameter dictionary (θ_MAP)
|
|
27
|
+
model : WPPM
|
|
28
|
+
Model instance used for predictions
|
|
29
|
+
|
|
30
|
+
Notes
|
|
31
|
+
-----
|
|
32
|
+
This implements the ParameterPosterior protocol.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
def __init__(self, params, model):
|
|
36
|
+
self._params = params
|
|
37
|
+
self._model = model
|
|
38
|
+
|
|
39
|
+
# ------------------------------------------------------------------
|
|
40
|
+
# ParameterPosterior protocol implementation
|
|
41
|
+
# ------------------------------------------------------------------
|
|
42
|
+
@property
|
|
43
|
+
def params(self):
|
|
44
|
+
"""Return the MAP parameters (θ_MAP)."""
|
|
45
|
+
return self._params
|
|
46
|
+
|
|
47
|
+
@property
|
|
48
|
+
def model(self):
|
|
49
|
+
"""Return the associated model."""
|
|
50
|
+
return self._model
|
|
51
|
+
|
|
52
|
+
def sample(self, n: int = 1, *, key=None):
|
|
53
|
+
"""
|
|
54
|
+
Sample from delta distribution (returns repeated θ_MAP).
|
|
55
|
+
|
|
56
|
+
Parameters
|
|
57
|
+
----------
|
|
58
|
+
n : int, default=1
|
|
59
|
+
Number of samples
|
|
60
|
+
key : jax.random.KeyArray, optional
|
|
61
|
+
PRNG key (unused for delta distribution)
|
|
62
|
+
|
|
63
|
+
Returns
|
|
64
|
+
-------
|
|
65
|
+
dict
|
|
66
|
+
Parameter PyTree with leading dimension n.
|
|
67
|
+
Each array has shape (n, ...) with identical values.
|
|
68
|
+
|
|
69
|
+
Notes
|
|
70
|
+
-----
|
|
71
|
+
Delta distribution has no randomness - returns repeated MAP estimate.
|
|
72
|
+
"""
|
|
73
|
+
return jax.tree.map(
|
|
74
|
+
lambda x: jnp.tile(x[None, ...], (n,) + (1,) * x.ndim), self._params
|
|
75
|
+
)
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
"""
|
|
2
|
+
predictive_posterior.py
|
|
3
|
+
----------------------
|
|
4
|
+
|
|
5
|
+
Predictive posterior distributions p(f(X*) | data) at test stimuli.
|
|
6
|
+
|
|
7
|
+
This module defines posteriors over **predictions** (not parameters),
|
|
8
|
+
used by acquisition functions for Bayesian optimization.
|
|
9
|
+
|
|
10
|
+
Design
|
|
11
|
+
------
|
|
12
|
+
PredictivePosterior wraps a ParameterPosterior and computes predictions via:
|
|
13
|
+
E[f(X*) | data] \approx (1/N) Σ_i f(X*; θ_i) where θ_i ~ p(θ | data)
|
|
14
|
+
|
|
15
|
+
This separates concerns:
|
|
16
|
+
- ParameterPosterior: represents uncertainty over θ
|
|
17
|
+
- PredictivePosterior: represents uncertainty over f(X*) (decision-making)
|
|
18
|
+
- effectively decoupling how we FIT the model from how we USE the fitted model
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
from typing import TYPE_CHECKING, Protocol, runtime_checkable
|
|
24
|
+
|
|
25
|
+
import jax
|
|
26
|
+
import jax.numpy as jnp
|
|
27
|
+
import jax.random as jr
|
|
28
|
+
|
|
29
|
+
if TYPE_CHECKING:
|
|
30
|
+
from psyphy.posterior.parameter_posterior import ParameterPosterior
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@runtime_checkable
|
|
34
|
+
class PredictivePosterior(Protocol):
|
|
35
|
+
"""
|
|
36
|
+
Protocol for predictive distributions p(f(X*) | data) at test stimuli.
|
|
37
|
+
|
|
38
|
+
Returned by Model.posterior(X) for use in acquisition functions.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def mean(self) -> jnp.ndarray:
|
|
43
|
+
"""
|
|
44
|
+
Posterior predictive mean E[f(X*) | data].
|
|
45
|
+
|
|
46
|
+
Returns
|
|
47
|
+
-------
|
|
48
|
+
jnp.ndarray
|
|
49
|
+
Shape (n_test,) for scalar outputs
|
|
50
|
+
Shape (n_test, output_dim) for vector outputs (future)
|
|
51
|
+
|
|
52
|
+
Notes
|
|
53
|
+
-----
|
|
54
|
+
Computed via Monte Carlo integration over parameter posterior.
|
|
55
|
+
"""
|
|
56
|
+
...
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def variance(self) -> jnp.ndarray:
|
|
60
|
+
"""
|
|
61
|
+
Posterior predictive marginal variances Var[f(X*) | data].
|
|
62
|
+
|
|
63
|
+
Returns
|
|
64
|
+
-------
|
|
65
|
+
jnp.ndarray
|
|
66
|
+
Shape (n_test,) for scalar outputs
|
|
67
|
+
Shape (n_test, output_dim) for vector outputs (future)
|
|
68
|
+
|
|
69
|
+
Notes
|
|
70
|
+
-----
|
|
71
|
+
Captures both aleatoric (model) and epistemic (parameter) uncertainty.
|
|
72
|
+
"""
|
|
73
|
+
...
|
|
74
|
+
|
|
75
|
+
def rsample(self, sample_shape: tuple = (), *, key: jr.KeyArray) -> jnp.ndarray:
|
|
76
|
+
"""
|
|
77
|
+
Reparameterized samples from p(f(X*) | data).
|
|
78
|
+
|
|
79
|
+
Parameters
|
|
80
|
+
----------
|
|
81
|
+
sample_shape : tuple, default=()
|
|
82
|
+
Shape of sample batch
|
|
83
|
+
key : jax.random.KeyArray
|
|
84
|
+
PRNG key
|
|
85
|
+
|
|
86
|
+
Returns
|
|
87
|
+
-------
|
|
88
|
+
jnp.ndarray
|
|
89
|
+
Shape (*sample_shape, n_test) for scalar outputs
|
|
90
|
+
Shape (*sample_shape, n_test, output_dim) for vector outputs
|
|
91
|
+
|
|
92
|
+
Notes
|
|
93
|
+
-----
|
|
94
|
+
Enables gradient-based acquisition optimization via reparameterization trick.
|
|
95
|
+
"""
|
|
96
|
+
...
|
|
97
|
+
|
|
98
|
+
def cov_field(self, X: jnp.ndarray) -> jnp.ndarray:
|
|
99
|
+
"""
|
|
100
|
+
Posterior over perceptual covariance field Σ(X).
|
|
101
|
+
|
|
102
|
+
Parameters
|
|
103
|
+
----------
|
|
104
|
+
X : jnp.ndarray
|
|
105
|
+
Test stimuli, shape (n_test, input_dim)
|
|
106
|
+
|
|
107
|
+
Returns
|
|
108
|
+
-------
|
|
109
|
+
jnp.ndarray
|
|
110
|
+
Posterior mean covariance E[Σ(X) | data],
|
|
111
|
+
shape (n_test, input_dim, input_dim)
|
|
112
|
+
|
|
113
|
+
Notes
|
|
114
|
+
-----
|
|
115
|
+
WPPM-specific method for visualizing perceptual noise structure.
|
|
116
|
+
This is NOT the predictive covariance - it's the model's
|
|
117
|
+
internal representation of perceptual uncertainty.
|
|
118
|
+
"""
|
|
119
|
+
...
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class WPPMPredictivePosterior:
|
|
123
|
+
"""
|
|
124
|
+
Predictive posterior for WPPM models.
|
|
125
|
+
|
|
126
|
+
Computes p(f(X*) | data) via Monte Carlo integration over
|
|
127
|
+
parameter posterior p(θ | data).
|
|
128
|
+
|
|
129
|
+
Parameters
|
|
130
|
+
----------
|
|
131
|
+
param_posterior : ParameterPosterior
|
|
132
|
+
Posterior over model parameters
|
|
133
|
+
X : jnp.ndarray, shape (n_test, input_dim)
|
|
134
|
+
Test reference stimuli
|
|
135
|
+
comparisons : jnp.ndarray, shape (n_test, input_dim), optional
|
|
136
|
+
Test probe stimuli. If None, predictions are over thresholds.
|
|
137
|
+
n_samples : int, default=100
|
|
138
|
+
Number of posterior samples for MC integration
|
|
139
|
+
|
|
140
|
+
Attributes
|
|
141
|
+
----------
|
|
142
|
+
param_posterior : ParameterPosterior
|
|
143
|
+
Wrapped parameter posterior
|
|
144
|
+
X : jnp.ndarray
|
|
145
|
+
Test stimuli
|
|
146
|
+
comparisons : jnp.ndarray | None
|
|
147
|
+
Test comparisons
|
|
148
|
+
n_samples : int
|
|
149
|
+
MC sample count
|
|
150
|
+
|
|
151
|
+
Notes
|
|
152
|
+
-----
|
|
153
|
+
Uses lazy evaluation: moments computed on first access.
|
|
154
|
+
"""
|
|
155
|
+
|
|
156
|
+
def __init__(
|
|
157
|
+
self,
|
|
158
|
+
param_posterior: ParameterPosterior,
|
|
159
|
+
X: jnp.ndarray,
|
|
160
|
+
comparisons: jnp.ndarray | None = None,
|
|
161
|
+
n_samples: int = 100,
|
|
162
|
+
):
|
|
163
|
+
self.param_posterior = param_posterior
|
|
164
|
+
self.X = X
|
|
165
|
+
self.comparisons = comparisons
|
|
166
|
+
self.n_samples = n_samples
|
|
167
|
+
|
|
168
|
+
# Lazy evaluation cache
|
|
169
|
+
self._mean = None
|
|
170
|
+
self._variance = None
|
|
171
|
+
self._computed = False
|
|
172
|
+
|
|
173
|
+
def _ensure_computed(self):
|
|
174
|
+
"""Compute moments via MC integration (lazy)."""
|
|
175
|
+
if self._computed:
|
|
176
|
+
return
|
|
177
|
+
|
|
178
|
+
# Sample parameters from posterior
|
|
179
|
+
key = jr.PRNGKey(0) # TODO: Make configurable via init
|
|
180
|
+
param_samples = self.param_posterior.sample(self.n_samples, key=key)
|
|
181
|
+
|
|
182
|
+
model = self.param_posterior.model
|
|
183
|
+
|
|
184
|
+
if self.comparisons is None:
|
|
185
|
+
# TODO: Implement threshold prediction
|
|
186
|
+
raise NotImplementedError(
|
|
187
|
+
"Threshold prediction not yet implemented. "
|
|
188
|
+
"Pass comparisons argument for pairwise discrimination."
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
# Vectorized prediction over parameter samples
|
|
192
|
+
def predict_batch(params):
|
|
193
|
+
"""Predict p(correct) for all (ref, probe) pairs given params."""
|
|
194
|
+
return jax.vmap(lambda r, p: model.predict_prob(params, (r, p)))(
|
|
195
|
+
self.X, self.comparisons
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
# predictions: shape (n_samples, n_test)
|
|
199
|
+
predictions = jax.vmap(predict_batch)(param_samples)
|
|
200
|
+
|
|
201
|
+
# Compute moments
|
|
202
|
+
self._mean = jnp.mean(predictions, axis=0)
|
|
203
|
+
self._variance = jnp.var(predictions, axis=0)
|
|
204
|
+
self._computed = True
|
|
205
|
+
|
|
206
|
+
@property
|
|
207
|
+
def mean(self) -> jnp.ndarray:
|
|
208
|
+
"""E[f(X*) | data], shape (n_test,)."""
|
|
209
|
+
self._ensure_computed()
|
|
210
|
+
return self._mean
|
|
211
|
+
|
|
212
|
+
@property
|
|
213
|
+
def variance(self) -> jnp.ndarray:
|
|
214
|
+
"""Var[f(X*) | data], shape (n_test,)."""
|
|
215
|
+
self._ensure_computed()
|
|
216
|
+
return self._variance
|
|
217
|
+
|
|
218
|
+
def rsample(self, sample_shape: tuple = (), *, key: jr.KeyArray) -> jnp.ndarray:
|
|
219
|
+
"""
|
|
220
|
+
Sample predictions from p(f(X*) | data).
|
|
221
|
+
|
|
222
|
+
Parameters
|
|
223
|
+
----------
|
|
224
|
+
sample_shape : tuple
|
|
225
|
+
Batch shape
|
|
226
|
+
key : jax.random.KeyArray
|
|
227
|
+
PRNG key
|
|
228
|
+
|
|
229
|
+
Returns
|
|
230
|
+
-------
|
|
231
|
+
jnp.ndarray
|
|
232
|
+
Shape (*sample_shape, n_test)
|
|
233
|
+
"""
|
|
234
|
+
n = int(jnp.prod(jnp.array(sample_shape))) if sample_shape else 1
|
|
235
|
+
param_samples = self.param_posterior.sample(n, key=key)
|
|
236
|
+
|
|
237
|
+
model = self.param_posterior.model
|
|
238
|
+
|
|
239
|
+
if self.comparisons is None:
|
|
240
|
+
raise NotImplementedError("Threshold sampling not yet implemented")
|
|
241
|
+
|
|
242
|
+
def predict_one(params):
|
|
243
|
+
"""Predict for all test points with given params."""
|
|
244
|
+
return jax.vmap(lambda r, p: model.predict_prob(params, (r, p)))(
|
|
245
|
+
self.X, self.comparisons
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
samples = jax.vmap(predict_one)(param_samples)
|
|
249
|
+
|
|
250
|
+
if sample_shape:
|
|
251
|
+
return samples.reshape(*sample_shape, -1)
|
|
252
|
+
return samples
|
|
253
|
+
|
|
254
|
+
def cov_field(self, X: jnp.ndarray) -> jnp.ndarray:
|
|
255
|
+
"""
|
|
256
|
+
Posterior mean covariance field E[Σ(X) | data].
|
|
257
|
+
|
|
258
|
+
Parameters
|
|
259
|
+
----------
|
|
260
|
+
X : jnp.ndarray
|
|
261
|
+
Test stimuli, shape (n_test, input_dim)
|
|
262
|
+
|
|
263
|
+
Returns
|
|
264
|
+
-------
|
|
265
|
+
jnp.ndarray
|
|
266
|
+
Covariance matrices, shape (n_test, input_dim, input_dim)
|
|
267
|
+
|
|
268
|
+
Notes
|
|
269
|
+
-----
|
|
270
|
+
Averages local_covariance(x) over parameter posterior samples.
|
|
271
|
+
"""
|
|
272
|
+
key = jr.PRNGKey(0)
|
|
273
|
+
param_samples = self.param_posterior.sample(self.n_samples, key=key)
|
|
274
|
+
|
|
275
|
+
model = self.param_posterior.model
|
|
276
|
+
|
|
277
|
+
def cov_at_x(params, x):
|
|
278
|
+
"""Evaluate Σ(x) with given parameters."""
|
|
279
|
+
return model.local_covariance(params, x)
|
|
280
|
+
|
|
281
|
+
# Vectorized evaluation: (n_samples, n_test, input_dim, input_dim)
|
|
282
|
+
cov_samples = jax.vmap(
|
|
283
|
+
lambda params: jax.vmap(lambda x: cov_at_x(params, x))(X)
|
|
284
|
+
)(param_samples)
|
|
285
|
+
|
|
286
|
+
# Return posterior mean
|
|
287
|
+
return jnp.mean(cov_samples, axis=0)
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""
|
|
2
|
+
trial_placement
|
|
3
|
+
===============
|
|
4
|
+
|
|
5
|
+
Non-acquisition-based trial placement strategies.
|
|
6
|
+
|
|
7
|
+
This module provides classical (non-Bayesian-optimization) placement strategies:
|
|
8
|
+
|
|
9
|
+
- GridPlacement: Fixed grid designs for systematic exploration
|
|
10
|
+
- SobolPlacement: Quasi-random low-discrepancy sequences (space-filling)
|
|
11
|
+
|
|
12
|
+
For acquisition-based adaptive designs (Bayesian optimization), use:
|
|
13
|
+
- psyphy.acquisition: Expected Improvement, UCB, Mutual Information
|
|
14
|
+
- See: psyphy.acquisition.optimize_acqf_discrete() for trial selection
|
|
15
|
+
|
|
16
|
+
Examples
|
|
17
|
+
--------
|
|
18
|
+
>>> # Fixed grid design
|
|
19
|
+
>>> from psyphy.trial_placement import GridPlacement
|
|
20
|
+
>>> placement = GridPlacement(n_points_per_dim=10, bounds=[[-1, 1], [-1, 1]])
|
|
21
|
+
>>> trials = placement.propose(batch_size=5)
|
|
22
|
+
|
|
23
|
+
>>> # Quasi-random exploration
|
|
24
|
+
>>> from psyphy.trial_placement import SobolPlacement
|
|
25
|
+
>>> placement = SobolPlacement(bounds=[[-1, 1], [-1, 1]])
|
|
26
|
+
>>> trials = placement.propose(batch_size=10)
|
|
27
|
+
|
|
28
|
+
>>> # For adaptive designs with acquisition functions, see:
|
|
29
|
+
>>> from psyphy.acquisition import expected_improvement, optimize_acqf_discrete
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
from psyphy.trial_placement.grid import GridPlacement
|
|
33
|
+
from psyphy.trial_placement.sobol import SobolPlacement
|
|
34
|
+
|
|
35
|
+
__all__ = [
|
|
36
|
+
"GridPlacement",
|
|
37
|
+
"SobolPlacement",
|
|
38
|
+
]
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""
|
|
2
|
+
grid.py
|
|
3
|
+
-------
|
|
4
|
+
|
|
5
|
+
Grid-based placement strategy.
|
|
6
|
+
|
|
7
|
+
MVP:
|
|
8
|
+
- Iterates through a fixed list of grid points.
|
|
9
|
+
- Ignores the posterior (non-adaptive).
|
|
10
|
+
|
|
11
|
+
Full WPPM mode:
|
|
12
|
+
- Could refine the grid adaptively around regions of high posterior uncertainty.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from psyphy.data.dataset import TrialBatch
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class GridPlacement:
|
|
19
|
+
"""
|
|
20
|
+
Fixed grid placement.
|
|
21
|
+
|
|
22
|
+
Parameters
|
|
23
|
+
----------
|
|
24
|
+
grid_points : list of (ref, probe)
|
|
25
|
+
Predefined set of trial stimuli.
|
|
26
|
+
|
|
27
|
+
Notes
|
|
28
|
+
-----
|
|
29
|
+
- grid = your set of allowable trials.
|
|
30
|
+
- this class simply walks through that set.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
def __init__(self, grid_points):
|
|
34
|
+
self.grid_points = list(grid_points)
|
|
35
|
+
self._index = 0
|
|
36
|
+
|
|
37
|
+
def propose(self, posterior, batch_size: int) -> TrialBatch:
|
|
38
|
+
"""
|
|
39
|
+
Return the next batch of trials from the grid.
|
|
40
|
+
|
|
41
|
+
Parameters
|
|
42
|
+
----------
|
|
43
|
+
posterior : Posterior
|
|
44
|
+
Ignored in MVP (grid is non-adaptive).
|
|
45
|
+
batch_size : int
|
|
46
|
+
Number of trials to return.
|
|
47
|
+
|
|
48
|
+
Returns
|
|
49
|
+
-------
|
|
50
|
+
TrialBatch
|
|
51
|
+
Fixed batch of (ref, probe).
|
|
52
|
+
"""
|
|
53
|
+
start, end = self._index, self._index + batch_size
|
|
54
|
+
batch = self.grid_points[start:end]
|
|
55
|
+
self._index = end
|
|
56
|
+
return TrialBatch.from_stimuli(batch)
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""
|
|
2
|
+
sobol.py
|
|
3
|
+
--------
|
|
4
|
+
|
|
5
|
+
Sobol quasi-random placement.
|
|
6
|
+
|
|
7
|
+
MVP:
|
|
8
|
+
- Uses a Sobol engine to generate low-discrepancy points.
|
|
9
|
+
- Ignores the posterior (pure exploration).
|
|
10
|
+
|
|
11
|
+
Levaraging WPPM's posterior:
|
|
12
|
+
- Could combine Sobol exploration (early) with posterior-aware exploitation (later).
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from scipy.stats.qmc import Sobol
|
|
16
|
+
|
|
17
|
+
from psyphy.data.dataset import TrialBatch
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class SobolPlacement:
|
|
21
|
+
"""
|
|
22
|
+
Sobol quasi-random placement.
|
|
23
|
+
|
|
24
|
+
Parameters
|
|
25
|
+
----------
|
|
26
|
+
dim : int
|
|
27
|
+
Dimensionality of stimulus space.
|
|
28
|
+
bounds : list of (low, high)
|
|
29
|
+
Bounds per dimension.
|
|
30
|
+
seed : int, optional
|
|
31
|
+
RNG seed.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
def __init__(self, dim: int, bounds, seed: int = 0):
|
|
35
|
+
self.engine = Sobol(d=dim, scramble=True, seed=seed)
|
|
36
|
+
self.bounds = bounds
|
|
37
|
+
|
|
38
|
+
def propose(self, posterior, batch_size: int) -> TrialBatch:
|
|
39
|
+
"""
|
|
40
|
+
Propose Sobol points (ignores posterior).
|
|
41
|
+
|
|
42
|
+
Parameters
|
|
43
|
+
----------
|
|
44
|
+
posterior : Posterior
|
|
45
|
+
Ignored in MVP.
|
|
46
|
+
batch_size : int
|
|
47
|
+
Number of trials to return.
|
|
48
|
+
|
|
49
|
+
Returns
|
|
50
|
+
-------
|
|
51
|
+
TrialBatch
|
|
52
|
+
Candidate trials from Sobol sequence.
|
|
53
|
+
|
|
54
|
+
"""
|
|
55
|
+
raw = self.engine.random(batch_size)
|
|
56
|
+
scaled = [
|
|
57
|
+
low + (high - low) * raw[:, i] for i, (low, high) in enumerate(self.bounds)
|
|
58
|
+
]
|
|
59
|
+
# Convert column-wise scaled arrays into list of probe vectors
|
|
60
|
+
comparisons = [tuple(vals) for vals in zip(*scaled)]
|
|
61
|
+
# MVP: use a zero reference vector of matching dimension
|
|
62
|
+
dim = len(self.bounds)
|
|
63
|
+
zero_ref = 0.0 if dim == 1 else tuple(0.0 for _ in range(dim))
|
|
64
|
+
trials = [(zero_ref, p) for p in comparisons]
|
|
65
|
+
return TrialBatch.from_stimuli(trials)
|
psyphy/utils/__init__.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""
|
|
2
|
+
utils
|
|
3
|
+
=====
|
|
4
|
+
|
|
5
|
+
Shared utility functions and helpers for psyphy.
|
|
6
|
+
|
|
7
|
+
This subpackage provides:
|
|
8
|
+
- math : mathematical utilities
|
|
9
|
+
(currently: basis functions, which may get their own module).
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from .math import chebyshev_basis
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
# math
|
|
18
|
+
"chebyshev_basis",
|
|
19
|
+
]
|
psyphy/utils/math.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""
|
|
2
|
+
math.py
|
|
3
|
+
-------
|
|
4
|
+
|
|
5
|
+
Math utilities for psyphy.
|
|
6
|
+
|
|
7
|
+
Includes:
|
|
8
|
+
- chebyshev_basis : compute Chebyshev polynomial basis.
|
|
9
|
+
- mahalanobis_distance : discriminability metric used in WPPM MVP.
|
|
10
|
+
- rbf_kernel : kernel function, useful in Full WPPM mode covariance priors.
|
|
11
|
+
|
|
12
|
+
All functions use JAX (jax.numpy) for compatibility with autodiff.
|
|
13
|
+
|
|
14
|
+
Notes
|
|
15
|
+
-----
|
|
16
|
+
- math.chebyshev_basis is relevant when implementing Full WPPM mode,
|
|
17
|
+
where covariance fields are expressed in a basis expansion.
|
|
18
|
+
- math.mahalanobis_distance is directly used in WPPM MVP discriminability.
|
|
19
|
+
- math.rbf_kernel is a placeholder for Gaussian-process-style covariance priors.
|
|
20
|
+
|
|
21
|
+
Examples
|
|
22
|
+
--------
|
|
23
|
+
>>> import jax.numpy as jnp
|
|
24
|
+
>>> from psyphy.utils import math
|
|
25
|
+
>>> x = jnp.linspace(-1, 1, 5)
|
|
26
|
+
>>> math.chebyshev_basis(x, degree=3).shape
|
|
27
|
+
(5, 4)
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
import jax.numpy as jnp
|
|
33
|
+
from jax import lax
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def chebyshev_basis(x: jnp.ndarray, degree: int) -> jnp.ndarray:
|
|
37
|
+
"""
|
|
38
|
+
Construct the Chebyshev polynomial basis matrix T_0..T_degree evaluated at x.
|
|
39
|
+
|
|
40
|
+
Parameters
|
|
41
|
+
----------
|
|
42
|
+
x : jnp.ndarray
|
|
43
|
+
Input points of shape (N,). For best numerical properties, values should lie in [-1, 1].
|
|
44
|
+
degree : int
|
|
45
|
+
Maximum polynomial degree (>= 0). The output includes columns for T_0 through T_degree.
|
|
46
|
+
|
|
47
|
+
Returns
|
|
48
|
+
-------
|
|
49
|
+
jnp.ndarray
|
|
50
|
+
Array of shape (N, degree + 1) where column j contains T_j(x).
|
|
51
|
+
|
|
52
|
+
Raises
|
|
53
|
+
------
|
|
54
|
+
ValueError
|
|
55
|
+
If `degree` is negative or `x` is not 1-D.
|
|
56
|
+
|
|
57
|
+
Notes
|
|
58
|
+
-----
|
|
59
|
+
Uses the three-term recurrence:
|
|
60
|
+
T_0(x) = 1
|
|
61
|
+
T_1(x) = x
|
|
62
|
+
T_{n+1}(x) = 2 x T_n(x) - T_{n-1}(x)
|
|
63
|
+
The Chebyshev polynomials are orthogonal on [-1, 1] with weight (1 / sqrt(1 - x^2)).
|
|
64
|
+
|
|
65
|
+
Examples
|
|
66
|
+
--------
|
|
67
|
+
>>> import jax.numpy as jnp
|
|
68
|
+
>>> x = jnp.linspace(-1, 1, 5)
|
|
69
|
+
>>> B = chebyshev_basis(x, degree=3) # columns: T0, T1, T2, T3
|
|
70
|
+
"""
|
|
71
|
+
if degree < 0:
|
|
72
|
+
raise ValueError("degree must be >= 0")
|
|
73
|
+
if x.ndim != 1:
|
|
74
|
+
raise ValueError("x must be 1-D (shape (N,))")
|
|
75
|
+
|
|
76
|
+
# Ensure a floating dtype (Chebyshev recurrences are polynomial in x)
|
|
77
|
+
x = x.astype(jnp.result_type(x, 0.0))
|
|
78
|
+
|
|
79
|
+
N = x.shape[0]
|
|
80
|
+
|
|
81
|
+
# Handle small degrees explicitly.
|
|
82
|
+
if degree == 0:
|
|
83
|
+
return jnp.ones((N, 1), dtype=x.dtype)
|
|
84
|
+
if degree == 1:
|
|
85
|
+
return jnp.stack([jnp.ones_like(x), x], axis=1)
|
|
86
|
+
|
|
87
|
+
# Initialize T0 and T1 columns.
|
|
88
|
+
T0 = jnp.ones_like(x)
|
|
89
|
+
T1 = x
|
|
90
|
+
|
|
91
|
+
# Scan to generate T2..T_degree in a JIT-friendly way (avoids Python-side loops).
|
|
92
|
+
def step(carry, _):
|
|
93
|
+
# compute next Chebyshev polynomial
|
|
94
|
+
Tm1, Tm = carry
|
|
95
|
+
Tnext = 2.0 * x * Tm - Tm1
|
|
96
|
+
return (Tm, Tnext), Tnext # new carry, plus an output to collect
|
|
97
|
+
|
|
98
|
+
# Jax friendly loop
|
|
99
|
+
(final_Tm1_ignored, final_Tm_ignored), Ts = lax.scan(
|
|
100
|
+
step, (T0, T1), xs=None, length=degree - 1
|
|
101
|
+
)
|
|
102
|
+
# Ts has shape (degree-1, N) and holds [T2, T3, ..., T_degree]
|
|
103
|
+
B = jnp.concatenate([T0[:, None], T1[:, None], jnp.swapaxes(Ts, 0, 1)], axis=1)
|
|
104
|
+
return B
|