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
psyphy/__init__.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""
|
|
2
|
+
psyphy
|
|
3
|
+
======
|
|
4
|
+
|
|
5
|
+
Psychophysical modeling and adaptive trial placement.
|
|
6
|
+
|
|
7
|
+
This package implements the Wishart Process Psychophysical Model (WPPM)
|
|
8
|
+
with modular components for priors, task likelihoods, and noise models,
|
|
9
|
+
which can be fitted to incoming subject data and used to adaptively
|
|
10
|
+
select new trials to present to the subject next.
|
|
11
|
+
This is useful for efficiently estimating psychophysical parameters
|
|
12
|
+
(e.g. threshold contours) with minimal trials.
|
|
13
|
+
|
|
14
|
+
----------------------------------------------------------------------
|
|
15
|
+
Workflow
|
|
16
|
+
----------------------------------------------------------------------
|
|
17
|
+
|
|
18
|
+
Core design
|
|
19
|
+
-----------
|
|
20
|
+
1. WPPM (model/wppm.py):
|
|
21
|
+
- Structural definition of the psychophysical model.
|
|
22
|
+
- Maintains parameterization of local covariance fields.
|
|
23
|
+
- Computes discriminability between stimuli.
|
|
24
|
+
- Delegates trial likelihoods and predictions to the task.
|
|
25
|
+
|
|
26
|
+
2. Prior (model/prior.py):
|
|
27
|
+
- Defines the distribution over model parameters.
|
|
28
|
+
- WPPM: structured prior over basis weights and
|
|
29
|
+
decay_rate-controlled covariance fields.
|
|
30
|
+
|
|
31
|
+
3. TaskLikelihood (model/likelihood.py):
|
|
32
|
+
- Encodes the psychophysical decision rule.
|
|
33
|
+
- WPPM: loglik and predict implemented via Monte Carlo
|
|
34
|
+
observer simulations, using the noise model explicitly.
|
|
35
|
+
|
|
36
|
+
4. NoiseModel (model/noise.py):
|
|
37
|
+
- Defines the distribution of internal representation noise.
|
|
38
|
+
- WPPM: GaussianNoise or StudentTNoise option.
|
|
39
|
+
|
|
40
|
+
Unified import style
|
|
41
|
+
--------------------
|
|
42
|
+
Top-level (core models + session):
|
|
43
|
+
from psyphy import WPPM, Prior, OddityTask, GaussianNoise, MAPOptimizer
|
|
44
|
+
from psyphy import ExperimentSession, ResponseData, TrialBatch
|
|
45
|
+
|
|
46
|
+
Subpackages:
|
|
47
|
+
from psyphy.model import WPPM, Prior, OddityTask, GaussianNoise, StudentTNoise
|
|
48
|
+
from psyphy.inference import MAPOptimizer, LangevinSampler, LaplaceApproximation
|
|
49
|
+
from psyphy.acquisition import expected_improvement, upper_confidence_bound, mutual_information
|
|
50
|
+
from psyphy.acquisition import optimize_acqf, optimize_acqf_discrete, optimize_acqf_random
|
|
51
|
+
from psyphy.trial_placement import GridPlacement, SobolPlacement
|
|
52
|
+
from psyphy.utils import grid_candidates, sobol_candidates, custom_candidates, chebyshev_basis
|
|
53
|
+
|
|
54
|
+
Data flow
|
|
55
|
+
---------
|
|
56
|
+
- A ResponseData object (psyphy.data) contains trial stimuli and responses.
|
|
57
|
+
- WPPM.init_params(prior) samples parameter initialization.
|
|
58
|
+
- Inference engines optimize the log posterior:
|
|
59
|
+
log_posterior = task.loglik(params, data, model=WPPM, noise=NoiseModel)
|
|
60
|
+
+ prior.log_prob(params)
|
|
61
|
+
- Posterior predictions (p(correct), threshold ellipses) are always obtained
|
|
62
|
+
through WPPM delegating to TaskLikelihood.
|
|
63
|
+
|
|
64
|
+
Extensibility
|
|
65
|
+
-------------
|
|
66
|
+
- To add a new task: subclass TaskLikelihood, implement predict/loglik.
|
|
67
|
+
- To add a new noise model: subclass NoiseModel, implement logpdf/sample.
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
----------------------------------------------------------------------
|
|
72
|
+
"""
|
|
73
|
+
|
|
74
|
+
# Data
|
|
75
|
+
# Re-export subpackages for unified import style (e.g., psyphy.model, psyphy.inference)
|
|
76
|
+
# from . import acquisition as acquisition
|
|
77
|
+
from . import data as data
|
|
78
|
+
from . import inference as inference
|
|
79
|
+
from . import model as model
|
|
80
|
+
from . import posterior as posterior
|
|
81
|
+
|
|
82
|
+
# from . import session as session
|
|
83
|
+
from . import trial_placement as trial_placement
|
|
84
|
+
from . import utils as utils
|
|
85
|
+
from .data.dataset import ResponseData, TrialBatch
|
|
86
|
+
from .inference.langevin import LangevinSampler
|
|
87
|
+
from .inference.laplace import LaplaceApproximation
|
|
88
|
+
|
|
89
|
+
# Inference
|
|
90
|
+
from .inference.map_optimizer import MAPOptimizer
|
|
91
|
+
from .model.likelihood import OddityTask, OddityTaskConfig
|
|
92
|
+
from .model.noise import GaussianNoise, StudentTNoise
|
|
93
|
+
from .model.prior import Prior
|
|
94
|
+
from .model.wppm import WPPM
|
|
95
|
+
|
|
96
|
+
# Posterior
|
|
97
|
+
from .posterior.parameter_posterior import ParameterPosterior
|
|
98
|
+
from .posterior.posterior import MAPPosterior
|
|
99
|
+
from .posterior.predictive_posterior import PredictivePosterior, WPPMPredictivePosterior
|
|
100
|
+
|
|
101
|
+
# Experiment orchestration
|
|
102
|
+
# from .session.experiment_session import ExperimentSession
|
|
103
|
+
|
|
104
|
+
__all__ = [
|
|
105
|
+
# Core model
|
|
106
|
+
"WPPM", # needs task for likelihood and noise model
|
|
107
|
+
"Prior",
|
|
108
|
+
"OddityTask",
|
|
109
|
+
"OddityTaskConfig",
|
|
110
|
+
"GaussianNoise", # default noise model
|
|
111
|
+
"StudentTNoise",
|
|
112
|
+
# Inference
|
|
113
|
+
"MAPOptimizer",
|
|
114
|
+
"LangevinSampler",
|
|
115
|
+
"LaplaceApproximation",
|
|
116
|
+
# Data handling
|
|
117
|
+
"ResponseData",
|
|
118
|
+
"TrialBatch",
|
|
119
|
+
# Subpackages
|
|
120
|
+
"model",
|
|
121
|
+
"inference",
|
|
122
|
+
"posterior",
|
|
123
|
+
"trial_placement",
|
|
124
|
+
"utils",
|
|
125
|
+
"data",
|
|
126
|
+
]
|
psyphy/data/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""
|
|
2
|
+
psyphy.data
|
|
3
|
+
==========
|
|
4
|
+
|
|
5
|
+
submodule for handling psychophysical experiment data.
|
|
6
|
+
|
|
7
|
+
Includes:
|
|
8
|
+
- dataset: ResponseData, TrialBatch, loaders
|
|
9
|
+
- transforms: color/model space conversions
|
|
10
|
+
- io: save/load datasets
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from .dataset import ResponseData, TrialBatch, TrialData
|
|
14
|
+
|
|
15
|
+
__all__ = ["ResponseData", "TrialBatch", "TrialData"]
|
psyphy/data/dataset.py
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
"""
|
|
2
|
+
dataset.py
|
|
3
|
+
-----------
|
|
4
|
+
|
|
5
|
+
Core data containers for psyphy.
|
|
6
|
+
|
|
7
|
+
defines:
|
|
8
|
+
- ResponseData: container for psychophysical trial data
|
|
9
|
+
- TrialBatch: container for a proposed batch of trials
|
|
10
|
+
|
|
11
|
+
Notes
|
|
12
|
+
-----
|
|
13
|
+
- Data is stored in standard NumPy (mutable!) arrays or Python lists.
|
|
14
|
+
- Use numpy for I/O and analysis.
|
|
15
|
+
- Convert to jax.numpy (jnp) (immutable!) arrays only when passing into WPPM
|
|
16
|
+
or inference engines that require JAX/Optax.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
import jax.numpy as jnp
|
|
25
|
+
import numpy as np
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True, slots=True)
|
|
29
|
+
class TrialData:
|
|
30
|
+
"""Batched trial data for compute.
|
|
31
|
+
|
|
32
|
+
This is the canonical, compute-efficient representation of observed trials.
|
|
33
|
+
|
|
34
|
+
Shapes
|
|
35
|
+
------
|
|
36
|
+
refs : (N, d)
|
|
37
|
+
comparisons : (N, d)
|
|
38
|
+
responses : (N,)
|
|
39
|
+
|
|
40
|
+
Notes
|
|
41
|
+
-----
|
|
42
|
+
- You can also think of this as a more generic ML-style dataset
|
|
43
|
+
``X`` with shape (N, 2, d) plus ``y`` with shape (N,). The explicit
|
|
44
|
+
field names (refs/comparisons) are currently native to :class:`OddityTask`.
|
|
45
|
+
- This is intended to be JAX-friendly (PyTree of arrays) so likelihood and
|
|
46
|
+
inference code can be JIT-compiled without touching Python containers.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
refs: jnp.ndarray # TODO: references
|
|
50
|
+
comparisons: jnp.ndarray
|
|
51
|
+
responses: jnp.ndarray
|
|
52
|
+
|
|
53
|
+
def __post_init__(self) -> None:
|
|
54
|
+
# Basic shape validation (keep lightweight; raise early for common mistakes).
|
|
55
|
+
if self.refs.ndim != 2:
|
|
56
|
+
raise ValueError(f"refs must be 2D (N,d), got shape {self.refs.shape}")
|
|
57
|
+
if self.comparisons.ndim != 2:
|
|
58
|
+
raise ValueError(
|
|
59
|
+
f"comparisons must be 2D (N,d), got shape {self.comparisons.shape}"
|
|
60
|
+
)
|
|
61
|
+
if self.responses.ndim != 1:
|
|
62
|
+
raise ValueError(
|
|
63
|
+
f"responses must be 1D (N,), got shape {self.responses.shape}"
|
|
64
|
+
)
|
|
65
|
+
if self.refs.shape[0] != self.comparisons.shape[0]:
|
|
66
|
+
raise ValueError(
|
|
67
|
+
"refs and comparisons must have same first dimension; "
|
|
68
|
+
f"got {self.refs.shape[0]} vs {self.comparisons.shape[0]}"
|
|
69
|
+
)
|
|
70
|
+
if self.refs.shape[0] != self.responses.shape[0]:
|
|
71
|
+
raise ValueError(
|
|
72
|
+
"refs and responses must have same first dimension; "
|
|
73
|
+
f"got {self.refs.shape[0]} vs {self.responses.shape[0]}"
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
def __len__(self) -> int:
|
|
77
|
+
"""Number of trials (N)."""
|
|
78
|
+
return int(self.responses.shape[0])
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def num_trials(self) -> int:
|
|
82
|
+
"""Number of trials (N)."""
|
|
83
|
+
return len(self)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class ResponseData:
|
|
87
|
+
"""Python-friendly incremental trial log.
|
|
88
|
+
|
|
89
|
+
This container is convenient for adaptive trial placement and I/O (e.g., CSV),
|
|
90
|
+
but it is not a compute-efficient representation for JAX.
|
|
91
|
+
|
|
92
|
+
Use :class:`TrialData` for model fitting and likelihood evaluation.
|
|
93
|
+
"""
|
|
94
|
+
|
|
95
|
+
def __init__(self) -> None:
|
|
96
|
+
self.refs: list[Any] = []
|
|
97
|
+
self.comparisons: list[Any] = []
|
|
98
|
+
self.responses: list[int] = []
|
|
99
|
+
|
|
100
|
+
def add_trial(self, ref: Any, comparison: Any, resp: int) -> None:
|
|
101
|
+
"""
|
|
102
|
+
append a single trial.
|
|
103
|
+
|
|
104
|
+
Parameters
|
|
105
|
+
----------
|
|
106
|
+
ref : Any
|
|
107
|
+
Reference stimulus (numpy array, list, etc.)
|
|
108
|
+
comparison : Any
|
|
109
|
+
Probe stimulus
|
|
110
|
+
resp : int
|
|
111
|
+
Subject response (binary or categorical)
|
|
112
|
+
"""
|
|
113
|
+
self.refs.append(ref)
|
|
114
|
+
self.comparisons.append(comparison)
|
|
115
|
+
self.responses.append(resp)
|
|
116
|
+
|
|
117
|
+
def add_batch(self, responses: list[int], trial_batch: TrialBatch) -> None:
|
|
118
|
+
"""
|
|
119
|
+
Append responses for a batch of trials.
|
|
120
|
+
|
|
121
|
+
Parameters
|
|
122
|
+
----------
|
|
123
|
+
responses : List[int]
|
|
124
|
+
Responses corresponding to each (ref, comparison) in the trial batch.
|
|
125
|
+
trial_batch : TrialBatch
|
|
126
|
+
The batch of proposed trials.
|
|
127
|
+
"""
|
|
128
|
+
for (ref, comparison), resp in zip(trial_batch.stimuli, responses):
|
|
129
|
+
self.add_trial(ref, comparison, resp)
|
|
130
|
+
|
|
131
|
+
def to_numpy(self) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
|
132
|
+
"""Return refs, comparisons, responses as NumPy arrays."""
|
|
133
|
+
return (
|
|
134
|
+
np.asarray(self.refs),
|
|
135
|
+
np.asarray(self.comparisons),
|
|
136
|
+
np.asarray(self.responses),
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
def to_trial_data(self) -> TrialData:
|
|
140
|
+
"""Convert this log into the canonical JAX batch (:class:`TrialData`)."""
|
|
141
|
+
refs, comparisons, responses = self.to_numpy()
|
|
142
|
+
return TrialData(
|
|
143
|
+
refs=jnp.asarray(refs),
|
|
144
|
+
comparisons=jnp.asarray(comparisons),
|
|
145
|
+
responses=jnp.asarray(responses),
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
@property
|
|
149
|
+
def trials(self) -> list[tuple[Any, Any, int]]:
|
|
150
|
+
"""
|
|
151
|
+
Return list of (ref, comparison, response) tuples.
|
|
152
|
+
|
|
153
|
+
Returns
|
|
154
|
+
-------
|
|
155
|
+
list[tuple]
|
|
156
|
+
Each element is (ref, comparison, resp)
|
|
157
|
+
"""
|
|
158
|
+
return list(zip(self.refs, self.comparisons, self.responses))
|
|
159
|
+
|
|
160
|
+
def __len__(self) -> int:
|
|
161
|
+
"""Return number of trials."""
|
|
162
|
+
return len(self.refs)
|
|
163
|
+
|
|
164
|
+
@classmethod
|
|
165
|
+
def from_arrays(
|
|
166
|
+
cls,
|
|
167
|
+
X: jnp.ndarray | np.ndarray,
|
|
168
|
+
y: jnp.ndarray | np.ndarray,
|
|
169
|
+
*,
|
|
170
|
+
comparisons: jnp.ndarray | np.ndarray | None = None,
|
|
171
|
+
) -> ResponseData:
|
|
172
|
+
"""
|
|
173
|
+
Construct ResponseData from arrays.
|
|
174
|
+
|
|
175
|
+
Parameters
|
|
176
|
+
----------
|
|
177
|
+
X : array, shape (n_trials, 2, input_dim) or (n_trials, input_dim)
|
|
178
|
+
Stimuli. If 3D, second axis is [reference, comparison].
|
|
179
|
+
If 2D, comparisons must be provided separately.
|
|
180
|
+
y : array, shape (n_trials,)
|
|
181
|
+
Responses
|
|
182
|
+
comparisons : array, shape (n_trials, input_dim), optional
|
|
183
|
+
Probe stimuli. Only needed if X is 2D.
|
|
184
|
+
|
|
185
|
+
Returns
|
|
186
|
+
-------
|
|
187
|
+
ResponseData
|
|
188
|
+
Data container
|
|
189
|
+
|
|
190
|
+
Examples
|
|
191
|
+
--------
|
|
192
|
+
>>> # From paired stimuli
|
|
193
|
+
>>> X = jnp.array([[[0, 0], [1, 0]], [[1, 1], [2, 1]]])
|
|
194
|
+
>>> y = jnp.array([1, 0])
|
|
195
|
+
>>> data = ResponseData.from_arrays(X, y)
|
|
196
|
+
|
|
197
|
+
>>> # From separate refs and comparisons
|
|
198
|
+
>>> refs = jnp.array([[0, 0], [1, 1]])
|
|
199
|
+
>>> comparisons = jnp.array([[1, 0], [2, 1]])
|
|
200
|
+
>>> data = ResponseData.from_arrays(refs, y, comparisons=comparisons)
|
|
201
|
+
"""
|
|
202
|
+
data = cls()
|
|
203
|
+
|
|
204
|
+
X = np.asarray(X)
|
|
205
|
+
y = np.asarray(y)
|
|
206
|
+
|
|
207
|
+
if X.ndim == 3:
|
|
208
|
+
# X is (n_trials, 2, input_dim)
|
|
209
|
+
refs = X[:, 0, :]
|
|
210
|
+
comparisons_arr = X[:, 1, :]
|
|
211
|
+
elif X.ndim == 2 and comparisons is not None:
|
|
212
|
+
refs = X
|
|
213
|
+
comparisons_arr = np.asarray(comparisons)
|
|
214
|
+
else:
|
|
215
|
+
raise ValueError(
|
|
216
|
+
"X must be shape (n_trials, 2, input_dim) or "
|
|
217
|
+
"(n_trials, input_dim) with comparisons argument"
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
for ref, comparison, response in zip(refs, comparisons_arr, y):
|
|
221
|
+
data.add_trial(ref, comparison, int(response))
|
|
222
|
+
|
|
223
|
+
return data
|
|
224
|
+
|
|
225
|
+
@classmethod
|
|
226
|
+
def from_trial_data(cls, data: TrialData) -> ResponseData:
|
|
227
|
+
"""Build a ResponseData log from a :class:`TrialData` batch."""
|
|
228
|
+
refs = np.asarray(data.refs)
|
|
229
|
+
comps = np.asarray(data.comparisons)
|
|
230
|
+
ys = np.asarray(data.responses)
|
|
231
|
+
out = cls()
|
|
232
|
+
for r, c, y in zip(refs, comps, ys):
|
|
233
|
+
out.add_trial(r, c, int(y))
|
|
234
|
+
return out
|
|
235
|
+
|
|
236
|
+
def merge(self, other: ResponseData) -> None:
|
|
237
|
+
"""
|
|
238
|
+
Merge another dataset into this one (in-place).
|
|
239
|
+
|
|
240
|
+
Parameters
|
|
241
|
+
----------
|
|
242
|
+
other : ResponseData
|
|
243
|
+
Dataset to merge
|
|
244
|
+
"""
|
|
245
|
+
self.refs.extend(other.refs)
|
|
246
|
+
self.comparisons.extend(other.comparisons)
|
|
247
|
+
self.responses.extend(other.responses)
|
|
248
|
+
|
|
249
|
+
def tail(self, n: int) -> ResponseData:
|
|
250
|
+
"""
|
|
251
|
+
Return last n trials as a new ResponseData.
|
|
252
|
+
|
|
253
|
+
Parameters
|
|
254
|
+
----------
|
|
255
|
+
n : int
|
|
256
|
+
Number of trials to keep
|
|
257
|
+
|
|
258
|
+
Returns
|
|
259
|
+
-------
|
|
260
|
+
ResponseData
|
|
261
|
+
New dataset with last n trials
|
|
262
|
+
"""
|
|
263
|
+
new_data = ResponseData()
|
|
264
|
+
new_data.refs = self.refs[-n:]
|
|
265
|
+
new_data.comparisons = self.comparisons[-n:]
|
|
266
|
+
new_data.responses = self.responses[-n:]
|
|
267
|
+
return new_data
|
|
268
|
+
|
|
269
|
+
def copy(self) -> ResponseData:
|
|
270
|
+
"""
|
|
271
|
+
Create a deep copy of this dataset.
|
|
272
|
+
|
|
273
|
+
Returns
|
|
274
|
+
-------
|
|
275
|
+
ResponseData
|
|
276
|
+
New dataset with copied data
|
|
277
|
+
"""
|
|
278
|
+
new_data = ResponseData()
|
|
279
|
+
new_data.refs = list(self.refs)
|
|
280
|
+
new_data.comparisons = list(self.comparisons)
|
|
281
|
+
new_data.responses = list(self.responses)
|
|
282
|
+
return new_data
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
class TrialBatch:
|
|
286
|
+
"""
|
|
287
|
+
Container for a proposed batch of trials
|
|
288
|
+
|
|
289
|
+
Attributes
|
|
290
|
+
----------
|
|
291
|
+
stimuli : List[Tuple[Any, Any]]
|
|
292
|
+
Each trial is a (reference, comparison) tuple.
|
|
293
|
+
"""
|
|
294
|
+
|
|
295
|
+
def __init__(self, stimuli: list[tuple[Any, Any]]) -> None:
|
|
296
|
+
self.stimuli = list(stimuli)
|
|
297
|
+
|
|
298
|
+
@classmethod
|
|
299
|
+
def from_stimuli(cls, pairs: list[tuple[Any, Any]]) -> TrialBatch:
|
|
300
|
+
"""
|
|
301
|
+
Construct a TrialBatch from a list of stimuli (ref, comparison) pairs.
|
|
302
|
+
"""
|
|
303
|
+
return cls(pairs)
|
psyphy/data/io.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""
|
|
2
|
+
io.py
|
|
3
|
+
-----
|
|
4
|
+
|
|
5
|
+
I/O utilities for saving and loading psyphy data.
|
|
6
|
+
|
|
7
|
+
Supports:
|
|
8
|
+
- CSV for human-readable trial logs
|
|
9
|
+
- Pickle (.pkl) for Posterior and ResponseData checkpoints?
|
|
10
|
+
|
|
11
|
+
Notes
|
|
12
|
+
-----
|
|
13
|
+
- Data is stored in NumPy arrays (via ResponseData.to_numpy()).
|
|
14
|
+
- Convert to jax.numpy when passing into models.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import ast
|
|
20
|
+
import csv
|
|
21
|
+
import pickle
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Union
|
|
24
|
+
|
|
25
|
+
import numpy as np
|
|
26
|
+
|
|
27
|
+
from .dataset import ResponseData, TrialData
|
|
28
|
+
|
|
29
|
+
PathLike = Union[str, Path]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def save_responses_csv(data: TrialData | ResponseData, path: PathLike) -> None:
|
|
33
|
+
"""
|
|
34
|
+
Save ResponseData to a CSV file.
|
|
35
|
+
|
|
36
|
+
Parameters
|
|
37
|
+
----------
|
|
38
|
+
data : ResponseData
|
|
39
|
+
path : str or Path
|
|
40
|
+
"""
|
|
41
|
+
if isinstance(data, TrialData):
|
|
42
|
+
refs, comparisons, resps = (
|
|
43
|
+
np.asarray(data.refs),
|
|
44
|
+
np.asarray(data.comparisons),
|
|
45
|
+
np.asarray(data.responses),
|
|
46
|
+
)
|
|
47
|
+
else:
|
|
48
|
+
refs, comparisons, resps = data.to_numpy()
|
|
49
|
+
with open(path, "w", newline="") as f:
|
|
50
|
+
writer = csv.writer(f)
|
|
51
|
+
writer.writerow(["ref", "probe", "response"])
|
|
52
|
+
for r, p, y in zip(refs, comparisons, resps):
|
|
53
|
+
writer.writerow([r.tolist(), p.tolist(), int(y)])
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def load_responses_csv(path: PathLike) -> TrialData:
|
|
57
|
+
"""
|
|
58
|
+
Load ResponseData from a CSV file.
|
|
59
|
+
|
|
60
|
+
Parameters
|
|
61
|
+
----------
|
|
62
|
+
path : str or Path
|
|
63
|
+
|
|
64
|
+
Returns
|
|
65
|
+
-------
|
|
66
|
+
ResponseData
|
|
67
|
+
"""
|
|
68
|
+
data = ResponseData()
|
|
69
|
+
with open(path) as f:
|
|
70
|
+
reader = csv.DictReader(f)
|
|
71
|
+
for row in reader:
|
|
72
|
+
ref = ast.literal_eval(row["ref"])
|
|
73
|
+
probe = ast.literal_eval(row["probe"])
|
|
74
|
+
resp = int(row["response"])
|
|
75
|
+
data.add_trial(ref, probe, resp)
|
|
76
|
+
return data.to_trial_data()
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def save_posterior(posterior: object, path: PathLike) -> None:
|
|
80
|
+
"""
|
|
81
|
+
Save a Posterior object to disk using pickle.
|
|
82
|
+
"""
|
|
83
|
+
with open(path, "wb") as f:
|
|
84
|
+
pickle.dump(posterior, f)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def load_posterior(path: PathLike) -> object:
|
|
88
|
+
"""
|
|
89
|
+
Load a Posterior object from pickle.
|
|
90
|
+
"""
|
|
91
|
+
with open(path, "rb") as f:
|
|
92
|
+
return pickle.load(f)
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""
|
|
2
|
+
inference
|
|
3
|
+
=========
|
|
4
|
+
|
|
5
|
+
Inference engines for WPPM.
|
|
6
|
+
|
|
7
|
+
This subpackage provides different strategies for fitting model parameters
|
|
8
|
+
to data and returning posterior objects.
|
|
9
|
+
|
|
10
|
+
MVP implementations
|
|
11
|
+
-------------------
|
|
12
|
+
- MAPOptimizer : maximum a posteriori fit with Optax optimizers.
|
|
13
|
+
- LaplaceApproximation : approximate posterior covariance around MAP.
|
|
14
|
+
- LangevinSampler : skeleton for sampling-based inference.
|
|
15
|
+
|
|
16
|
+
Future extensions
|
|
17
|
+
-----------------
|
|
18
|
+
- adjusted MC samplers, e.g., MALA (for Bayesian posterior inference).
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from .base import InferenceEngine
|
|
22
|
+
from .langevin import LangevinSampler
|
|
23
|
+
from .laplace import LaplaceApproximation
|
|
24
|
+
from .map_optimizer import MAPOptimizer
|
|
25
|
+
|
|
26
|
+
# Registry for string-based inference selection
|
|
27
|
+
INFERENCE_ENGINES = {
|
|
28
|
+
"map": MAPOptimizer,
|
|
29
|
+
"laplace": LaplaceApproximation,
|
|
30
|
+
"langevin": LangevinSampler,
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
__all__ = [
|
|
34
|
+
"InferenceEngine",
|
|
35
|
+
"MAPOptimizer",
|
|
36
|
+
"LangevinSampler",
|
|
37
|
+
"LaplaceApproximation",
|
|
38
|
+
"INFERENCE_ENGINES",
|
|
39
|
+
]
|
psyphy/inference/base.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""
|
|
2
|
+
base.py
|
|
3
|
+
-------
|
|
4
|
+
|
|
5
|
+
Abstract base class for inference engines.
|
|
6
|
+
|
|
7
|
+
All inference engines must implement a `fit(model, data)` method
|
|
8
|
+
that returns a Posterior object.
|
|
9
|
+
|
|
10
|
+
All inference engines (MAPOptimizer, LangevinSampler, LaplaceApproximation)
|
|
11
|
+
subclass from this base.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from abc import ABC, abstractmethod
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class InferenceEngine(ABC):
|
|
21
|
+
"""
|
|
22
|
+
Abstract interface for inference engines.
|
|
23
|
+
|
|
24
|
+
Methods
|
|
25
|
+
-------
|
|
26
|
+
fit(model, data) -> Posterior
|
|
27
|
+
Fit model parameters to data and return a Posterior object.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
@abstractmethod
|
|
31
|
+
def fit(self, model: Any, data: Any) -> Any:
|
|
32
|
+
"""
|
|
33
|
+
Fit model parameters to data.
|
|
34
|
+
|
|
35
|
+
Parameters
|
|
36
|
+
----------
|
|
37
|
+
model : WPPM
|
|
38
|
+
Psychophysical model to fit.
|
|
39
|
+
data : ResponseData
|
|
40
|
+
Observed trials.
|
|
41
|
+
|
|
42
|
+
Returns
|
|
43
|
+
-------
|
|
44
|
+
Posterior
|
|
45
|
+
Posterior object wrapping fitted params and model reference.
|
|
46
|
+
"""
|
|
47
|
+
...
|