API reference¶
The ring package, generated from NumPy-style docstrings.
ring.sim¶
ring.sim ¶
ODE simulation of the ring-attractor dynamical system.
run_sim performs Euler integration of
tau * dx/dt = -x + J @ phi(x) + omega(t) * J' @ phi(x) + stabilizer
on GPU/CPU torch tensors, with optional periodic save of state and an early-stop check that fires when per-batch derivatives plateau.
run_sim ¶
run_sim(T, tau, dt, T_eval, J, x_init, nonlin=fn.unity_erf, omega_func=None, J_prime=None, target_mean=None, const=np.nan, return_derivs=False, break_if_stopped=True, disable_tqdm=False)
Euler-integrate the ring-attractor ODE on GPU/CPU torch.
The integrated equation is
tau * dx/dt = -x + J @ phi(x) + omega(t) * J' @ phi(x) + stabilizer
where phi is the nonlinearity, omega(t) is an optional time-
varying scalar drift, J_prime is the skew-coupling to omega,
and the stabilizer (if enabled) clamps the population mean of
phi(x) toward target_mean.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
T
|
float
|
Total integration time. |
required |
tau
|
float
|
Membrane time constant (same units as |
required |
dt
|
float
|
Integration step. |
required |
T_eval
|
float or None
|
Period at which to save state into |
required |
J
|
(Tensor, shape(N, N))
|
Recurrent weight matrix. |
required |
x_init
|
(Tensor, shape(N, N_batch))
|
Initial state for |
required |
nonlin
|
callable
|
Pointwise nonlinearity |
``fn.unity_erf``
|
omega_func
|
callable or None
|
Function |
None
|
J_prime
|
(Tensor or None, shape(N, N))
|
Required if |
None
|
target_mean
|
float or None
|
If given, adds a stabilizer
|
None
|
const
|
float
|
Stabilizer strength; ignored when |
``np.nan``
|
return_derivs
|
bool
|
If True, also return per-batch RMS derivatives at exit. |
False
|
break_if_stopped
|
bool
|
If True, break out of the loop when all batch trajectories' RMS derivatives drop below 1e-100 (numerical zero). |
True
|
disable_tqdm
|
bool
|
Disable the tqdm progress bar (emits periodic plain-text status prints instead). |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
x_final |
(ndarray, shape(N, N_batch))
|
Final state. |
X_save |
(ndarray or None, shape(N_eval, N, N_batch))
|
Periodic snapshots of state; |
finished |
bool
|
True if all |
derivs |
(ndarray, shape(N_batch), optional)
|
Final per-batch RMS derivatives. Only returned if
|
Source code in ring/sim.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 | |
ring.dmft¶
ring.dmft ¶
Dynamical mean-field theory (DMFT) for the ring-attractor model.
Single class DMFTModel constructs the wraparound Gaussian covariance,
derives the analytical recurrent weights J and the deviation operator U,
and simulates the DMFT equations (Euler integration of the order parameter
m and its conjugate m_hat). Used by notebooks/dmft.ipynb and
notebooks/weight_matrix_analyses.ipynb.
Public API on a DMFTModel instance:
F, J analytical functions / weights
simulate Euler integration
compute_bump_jacobian Jacobian at the bump fixed point
compute_homogeneous_jacobian Jacobian at the homogeneous solution
Other attributes (Gamma_*, U, dF_*, compute_*,
rfft_sum, J_m_prod etc.) are internal implementation detail.
DMFTModel ¶
Analytical + simulation toolkit for the ring-attractor DMFT.
On construction, derives the wraparound Gaussian covariance Gamma_x
(length scale scale, N_theta angular points), the nonlinear
covariance map F, the analytical recurrent weights J (from
Gamma_x / Gamma_phi in Fourier space), and the deviation operator
U. After construction the instance exposes F, J, and the
simulate / compute_*_jacobian methods listed in the module
docstring.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
N_theta
|
int
|
Number of angular grid points on the ring. |
1000
|
scale
|
float
|
Wrapped-Gaussian length scale (in units of Fourier-frequency index). |
1.5
|
g
|
float
|
Gain parameter scaling the nonlinearity. |
2.0
|
lamda
|
float
|
Regularization entering the mean-field kernels as
It has the same PLACE in the formula as the Keeping this at |
1e-12
|
Source code in ring/dmft.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 | |
compute_F_function ¶
compute_F_function()
(internal) Derive the nonlinear covariance map F and its derivatives.
Sets three instance attributes:
self.F(C_11, C_22, C_12): the 2-point Gaussian average of the erf-based nonlinearity for joint variances/covarianceC_*.self.dF_dC12,self.dF_dC11: partial derivatives.
Source code in ring/dmft.py
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 | |
compute_Gamma ¶
compute_Gamma()
(internal) Build Gamma_x (input covariance) and Gamma_phi (output).
Source code in ring/dmft.py
113 114 115 116 117 118 | |
compute_J_and_U ¶
compute_J_and_U()
(internal) Derive J = Gamma_x / (Gamma_phi + lamda) and U = Gamma_x / (Gamma_phi + lamda)^2 in Fourier space.
The ridge self.lamda is added to the Fourier-space Gamma_phi,
which is what regularizes the inversion at high n where
Gamma_phi_ft decays toward zero.
Source code in ring/dmft.py
120 121 122 123 124 125 126 127 128 129 130 | |
rfft_sum ¶
rfft_sum(x)
(internal) Reduce real Fourier coefficients x to the implied real-space sum.
Source code in ring/dmft.py
132 133 134 | |
J_m_prod ¶
J_m_prod(m)
(internal) Convolve m with J via FFT.
Source code in ring/dmft.py
136 137 138 139 | |
J_deriv_m_hat_prod ¶
J_deriv_m_hat_prod(m_hat)
(internal) Convolve m_hat with the derivative of J via FFT.
Source code in ring/dmft.py
141 142 143 144 145 146 147 | |
compute_Q ¶
compute_Q(m, m_hat)
(internal) Compute the DMFT Q functional from m, m_hat.
Notes
Both the mean field and its variance are driven by the same single
source s = m - d(m_hat)/dtheta, whose Fourier coefficients are
s_n = m_n - i n mhat_n. The mean field is J convolved with
s, since J_m_prod(m) - J_deriv_m_hat_prod(m_hat) equals
irfft(J_ft * s_ft), and Q is the same source measured with
U instead of J,
Q = sum_n U_n |m_n - i n mhat_n|^2,
which is what t1 + t2 + t3 below expands to. That expansion fixes
the conjugation in t3: m_hat_ft.conj() * m_ft gives the cross
term of |m_n - i n mhat_n|^2, whereas conjugating the other factor
would flip its sign and give |m_n + i n mhat_n|^2, a source
inconsistent with the one the mean field uses. Both choices are
positive, so positivity of the variance does not settle it and
consistency with H does. Verified numerically against the closed
form, 2026-07-31. The two agree only when m_hat = 0, that is at
zero drift, so nothing computed at omega = 0 was ever sensitive
to this.
Source code in ring/dmft.py
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | |
simulate ¶
simulate(T, dt, T_eval, omega_func=None, m_init=None, use_tqdm=True, tau=1.0, exclude_Q=False)
Euler-integrate the DMFT equations for m and m_hat.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
T
|
float
|
Total integration time. |
required |
dt
|
float
|
Integration step. |
required |
T_eval
|
float
|
Save state every |
required |
omega_func
|
callable or None
|
Time-varying drift |
None
|
m_init
|
(ndarray, shape(N_theta))
|
Initial order parameter. Defaults to |
None
|
use_tqdm
|
bool
|
Show progress bar. |
True
|
tau
|
float
|
Membrane time constant. |
1.
|
exclude_Q
|
bool
|
If True, replace |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
t |
(ndarray, shape(N_eval))
|
Sampled timesteps. |
m |
(ndarray, shape(N_eval, N_theta))
|
Order-parameter snapshots. |
m_hat |
(ndarray, shape(N_eval, N_theta))
|
Conjugate order-parameter snapshots. |
g_dyn |
(ndarray, shape(N_eval, N_theta))
|
Snapshots of the input |
Source code in ring/dmft.py
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 | |
compute_bump_jacobian ¶
compute_bump_jacobian(exclude_Q=False)
Compute the Jacobian and eigenvalues at the bump solution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exclude_Q
|
bool
|
If True, omit the Q-fluctuation contribution. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
jac |
(ndarray, shape(N_theta, N_theta))
|
Jacobian matrix at the bump. |
eigenvals |
(ndarray, shape(N_theta))
|
Eigenvalues sorted by descending real part. |
Source code in ring/dmft.py
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 | |
find_homogeneous_solution ¶
find_homogeneous_solution(tol=1e-14, max_iter=2000, exclude_Q=False)
Locate the homogeneous (theta-independent) fixed point m0 via bisection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tol
|
float
|
Convergence tolerance on the residual. |
1e-14
|
max_iter
|
int
|
Maximum bisection iterations. |
2000
|
exclude_Q
|
bool
|
If True, replace Q with Gamma_x[0] in the fixed-point equation. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
m0 |
float
|
Homogeneous fixed-point value. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If bisection fails to converge within |
Source code in ring/dmft.py
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 | |
compute_homogeneous_jacobian ¶
compute_homogeneous_jacobian(m0=None, exclude_Q=False, exclude_Q_for_m0=False)
Compute the Jacobian and eigenvalues at the homogeneous fixed point.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
m0
|
float
|
Homogeneous solution value. Computed via |
None
|
exclude_Q
|
bool
|
If True, omit the Q-fluctuation contribution. |
False
|
exclude_Q_for_m0
|
bool
|
If True (and |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
jac |
(ndarray, shape(N_theta, N_theta))
|
Jacobian matrix at the homogeneous solution. |
eigenvals |
(ndarray, shape(N_theta))
|
Eigenvalues sorted by descending real part. |
Source code in ring/dmft.py
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 | |
ring.tc¶
ring.tc ¶
Tuning curve sampling and wraparound covariance helpers.
Used by other ring/* modules and notebooks for sampling random tuning curves
(sample_tcs) and constructing the wrapped Gaussian covariance kernel
(wrapped_gaussian_cov) used in DMFT and grid-search optimization.
wrapped_gaussian_cov ¶
wrapped_gaussian_cov(eq_var, scale, N_theta, backend='numpy')
Wraparound (periodic) Gaussian covariance and its real Fourier transform.
The kernel is the wraparound generalization of N(0, scale^2) sampled
at N_theta evenly-spaced points on the circle, normalized so the
Fourier amplitude at DC is eq_var.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
eq_var
|
float
|
Equilibrium variance. |
required |
scale
|
float
|
Gaussian length scale (in units of Fourier-frequency index). |
required |
N_theta
|
int
|
Number of angular grid points. |
required |
backend
|
str
|
|
'numpy'
|
Returns:
| Name | Type | Description |
|---|---|---|
Gamma |
(ndarray or Tensor, shape(N_theta))
|
Real-space wraparound covariance. |
Gamma_ft |
(ndarray or Tensor, shape(N_theta // 2 + 1))
|
Fourier-space (real) covariance. |
Source code in ring/tc.py
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | |
sample_tcs ¶
sample_tcs(N, Gamma_ft, cutoff=None)
Sample N tuning curves from a wraparound Gaussian process.
Each sampled curve is a real periodic function of theta whose Fourier-
space covariance matches Gamma_ft. The procedure draws iid complex
normal Fourier coefficients, scales by the sqrt of the spectrum, and
inverse-FFTs to real space. Uses the global numpy RNG, so the caller is
responsible for seeding it when the draw needs to be reproducible.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
N
|
int
|
Number of curves to sample. |
required |
Gamma_ft
|
(ndarray, shape(N_freq))
|
Fourier-space covariance spectrum (real). |
required |
cutoff
|
int
|
If given, zero out spectrum beyond this index (high-frequency cutoff). Default uses all frequencies. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
X |
(ndarray, shape(N_theta, N))
|
Sampled tuning curves, one per column. |
Notes
Draws the complex Fourier coefficients in (N_freq, N) layout;
gp_opt.sample_z uses the transposed (N_samples, N_freq) layout, so
the two yield different realizations under the same seed and are
intentionally NOT interchangeable.
Source code in ring/tc.py
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | |
gen_tuning_curves_idealized ¶
gen_tuning_curves_idealized(N_samples, N_theta, scale, beta)
Sample idealized (erf) tuning curves for the large-N generative process.
Draws input currents from the wraparound Gaussian process
(wrapped_gaussian_cov + sample_tcs) and applies the idealized
error-function nonlinearity (fn.nonlin_idealized). Uses the global numpy
RNG via sample_tcs; the caller is responsible for seeding.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
N_samples
|
int
|
Number of tuning curves to sample. |
required |
N_theta
|
int
|
Number of angular grid points. |
required |
scale
|
float
|
Wraparound-Gaussian Fourier decay scale ( |
required |
beta
|
float
|
Response sharpness of the nonlinearity. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
X |
(ndarray, shape(N_theta, N_samples))
|
Input-current tuning curves. |
Phi |
(ndarray, shape(N_theta, N_samples))
|
Firing-rate tuning curves. |
Source code in ring/tc.py
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 | |
ring.data¶
ring.data ¶
Mouse head-direction tuning-curve producer.
Walks the Peyrache lab NWB sessions on disk, computes per-unit tuning
curves (with Poisson-likelihood-optimized Gaussian smoothing per
cross-validation fold), and writes
tc_data.npz, the tuning-curve file consumed by notebooks/data_and_generative_model.ipynb
and the data_driven chain.
External entry point: run as a script, ::
python -m ring.data
(or python ring/data.py). Consumers reference the produced cache as
data/mouse_data/tc_data.npz.
Running this is optional. The cache it writes is distributed with the rest of the caches, so it is only needed to rebuild the tuning curves from the raw recordings.
get_session_info ¶
get_session_info()
Enumerate NWB sessions in DATA_DIR.
Returns:
| Name | Type | Description |
|---|---|---|
sessions |
list of (fname, subject_id, has_optogenetics) tuples
|
Sorted by filename. |
Source code in ring/data.py
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | |
compute_angular_occupancy_and_spike_counts ¶
compute_angular_occupancy_and_spike_counts(N_theta, hd_idx, spike_time_idx, mask=None)
Bin behavioral occupancy and spike counts by head-direction angle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
N_theta
|
int
|
Number of angular bins on the ring. |
required |
hd_idx
|
(ndarray, shape(N_bins))
|
Per-time-bin angular bin index (in [0, N_theta)); negative entries flag invalid bins (e.g. NaN HD samples). |
required |
spike_time_idx
|
(ndarray, shape(N_spikes))
|
Time-bin indices at which spikes occurred. |
required |
mask
|
ndarray of bool or None, shape (N_bins,)
|
Optional per-time-bin mask (e.g. cross-validation fold). Negative
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
angular_occupancy_counts |
(ndarray, shape(N_theta))
|
|
angular_spike_counts |
(ndarray, shape(N_theta))
|
|
Source code in ring/data.py
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 | |
compute_tuning_curve ¶
compute_tuning_curve(N_theta, hd_idx, spike_time_idx, mask=None)
Tuning curve = (spike count) / (occupancy * DATA_DT) per angular bin.
Zero-rate bins are floored at mean * 1e-3 so the downstream
Poisson likelihood never sees a log(0).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
N_theta
|
int
|
Number of angular bins on the ring. |
required |
hd_idx
|
(ndarray, shape(N_bins))
|
Per-time-bin angular bin index; negative entries flag invalid bins. |
required |
spike_time_idx
|
(ndarray, shape(N_spikes))
|
Time-bin indices at which spikes occurred. |
required |
mask
|
ndarray of bool or None, shape (N_bins,)
|
Optional per-time-bin mask (e.g. cross-validation fold). |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
tc |
(ndarray, shape(N_theta))
|
Firing-rate tuning curve (Hz). |
Source code in ring/data.py
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 | |
compute_poisson_ll ¶
compute_poisson_ll(tuning_curve, hd_idx, temporal_spike_counts, mask=None)
Poisson log-likelihood of observed spike counts given a tuning curve.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tuning_curve
|
(ndarray, shape(N_theta))
|
Firing-rate tuning curve (Hz). |
required |
hd_idx
|
(ndarray, shape(N_bins))
|
Per-time-bin angular bin index; negatives are masked. |
required |
temporal_spike_counts
|
(ndarray, shape(N_bins))
|
Spike count per time bin. |
required |
mask
|
ndarray of bool or None, shape (N_bins,)
|
Optional cross-validation mask. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
ll |
float
|
Summed log-pmf across the masked bins. |
Source code in ring/data.py
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | |
generate_alternating_mask ¶
generate_alternating_mask(N_bins, K)
Alternating-chunk True/False mask for 2*K blocks of cross-validation.
Used as a cross-validation fold split: 2*K contiguous chunks of
near-equal size, alternating between True and False.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
N_bins
|
int
|
Total number of time bins. |
required |
K
|
int
|
Number of "True" chunks (and number of "False" chunks); total
|
required |
Returns:
| Name | Type | Description |
|---|---|---|
mask |
ndarray of bool, shape (N_bins,)
|
|
Source code in ring/data.py
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 | |
process_file ¶
process_file(nwbfile, N_theta=100, sigma_vals=np.logspace(-1, 2, 100), K=4)
Compute per-unit tuning curves for one session.
For each unit, computes a plain (occupancy-normalized) tuning curve
per cross-validation fold, then sweeps Gaussian smoothing widths
sigma_vals and picks the one that maximizes the held-out Poisson
log-likelihood.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nwbfile
|
pynwb NWBFile (already-opened)
|
Session to process. Expects |
required |
N_theta
|
int
|
Number of angular bins. |
100
|
sigma_vals
|
ndarray
|
Gaussian smoothing widths (in bin units) to sweep. |
``np.logspace(-1, 2, 100)``
|
K
|
int
|
Number of alternating-chunk cross-validation folds. |
4
|
Returns:
| Name | Type | Description |
|---|---|---|
plain_tcs |
(ndarray, shape(num_units, 2, N_theta))
|
Plain (un-smoothed) tuning curves per fold. |
opt_tcs |
(ndarray, shape(num_units, 2, N_theta))
|
Smoothed tuning curve at the held-out-LL-optimal sigma per fold. |
opt_sigmas |
(ndarray, shape(num_units, 2))
|
Optimal sigma per fold. |
Source code in ring/data.py
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 | |
process_all_tcs ¶
process_all_tcs()
Process all sessions in DATA_DIR and write tc_data.npz.
Output keys (concatenated across sessions on axis 0 where applicable):
hd_mask, exc_mask, fs_mask: per-unit boolean classifiers from the NWB units table.plain_tcs: shape(N_total_units, 2, N_theta), per-fold occupancy-normalized tuning curves.opt_tcs, opt_sigmas: optimal smoothed tuning curves and smoothing widths.fnames: per-session NWB filenames.unit_counts: per-session unit count.mouse_nums, mouse_names: per-unit session and subject id.has_ogen: per-unit optogenetics flag.
Source code in ring/data.py
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 | |
ring.data_driven¶
ring.data_driven ¶
Data-driven ring-attractor toolkit.
Builds the empirical weight matrix J from mouse tuning curves, runs
the resulting recurrent network with closed-loop head-direction drive,
projects trajectories into PC space, and plots them. Consumed primarily
by notebooks/data_driven_attractor.ipynb (Fig 3 producer) and the
data_driven_analyses / grid_sims chains.
load_tuning_curve_data ¶
load_tuning_curve_data()
(internal) Load tuning curves from TC_DATA_PATH, dropping all-zero rows.
Returns:
| Name | Type | Description |
|---|---|---|
tcs |
(ndarray, shape(N_units, N_theta))
|
Cross-validation-fold-averaged tuning curves (zero-row units dropped). |
plain_tcs |
(ndarray, shape(N_units, 2, N_theta))
|
Plain (un-smoothed) per-fold tuning curves. |
hd_mask, fs_mask, exc_mask : ndarray of bool, shape (N_units,)
|
Per-unit head-direction / fast-spiking / excitatory classifiers. |
|
num_units |
int
|
Number of surviving units. |
Source code in ring/data_driven.py
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | |
prepare_Phi ¶
prepare_Phi(tcs, hd_mask)
(internal) Select HD-classified units, mean-normalize, and transpose to (N_theta, N).
Source code in ring/data_driven.py
57 58 59 60 61 62 | |
load_data_Phi ¶
load_data_Phi()
Load Phi for the HD-classified subset of mouse units.
Returns:
| Name | Type | Description |
|---|---|---|
Phi |
(ndarray, shape(N_theta, N))
|
Mean-normalized tuning curves transposed to (N_theta, N). |
Source code in ring/data_driven.py
65 66 67 68 69 70 71 72 73 74 | |
nonlin ¶
nonlin(x, beta=2)
Softplus nonlinearity. Thin wrapper around fn.softplus(x, beta).
Source code in ring/data_driven.py
79 80 81 | |
inv_nonlin ¶
inv_nonlin(phi, beta=2)
(internal) Inverse softplus: log(exp(beta * phi) - 1) / beta.
Supports numpy or torch input; raises TypeError otherwise.
Source code in ring/data_driven.py
84 85 86 87 88 89 90 91 92 93 94 | |
resample_curves_fft ¶
resample_curves_fft(X, N_new)
(internal) FFT-based resampling of curves from N_original to N_new points.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
(ndarray, shape(N_original, N_curves))
|
|
required |
N_new
|
int
|
|
required |
Returns:
| Name | Type | Description |
|---|---|---|
X_resampled |
(ndarray, shape(N_new, N_curves))
|
|
Source code in ring/data_driven.py
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 | |
prepare_smoothed_normalized_resampled_tuning_curves ¶
prepare_smoothed_normalized_resampled_tuning_curves(Phi, N_theta=500, sigma=2, normalize=True, normalize_across_neurons=True)
Smooth, normalize and resample tuning curves for network construction.
Applies Gaussian smoothing, then Sinkhorn-iterate normalization, then FFT resampling. This is the preparation behind the networks in the paper, so changing it changes the published figures.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
Phi
|
(ndarray, shape(N_theta_orig, N))
|
|
required |
N_theta
|
int
|
Output resolution after FFT resampling. |
500
|
sigma
|
float
|
Gaussian smoothing width in bin units. |
2
|
normalize
|
bool
|
If True, apply Sinkhorn-iterate normalization. |
True
|
normalize_across_neurons
|
bool
|
If True, normalize across both axes; otherwise only across theta. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
X_smooth_norm_resampled |
(ndarray, shape(N_theta, N))
|
|
Phi_smooth_norm_resampled |
(ndarray, shape(N_theta, N))
|
|
Source code in ring/data_driven.py
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 | |
compute_weights ¶
compute_weights(X, Phi, lamda=1e-08)
Compute the recurrent weight matrix J and its skew derivative J_prime.
J is the ridge regression solution to X ≈ J @ Phi (via
regression.compute_J); J_prime is the analogous solution for
the angular derivative of X, used as the coupling to the omega
drift term in the dynamics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
(ndarray, shape(N_theta, N))
|
Preactivation tuning curves. |
required |
Phi
|
(ndarray, shape(N_theta, N))
|
Output (post-nonlinearity) tuning curves. |
required |
lamda
|
float
|
Ridge regularization strength, in the |
1e-8
|
Returns:
| Name | Type | Description |
|---|---|---|
J |
(ndarray, shape(N, N))
|
Recurrent weight matrix. |
J_prime |
(ndarray, shape(N, N))
|
Skew coupling matrix (for omega drift). |
Source code in ring/data_driven.py
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 | |
run_simulation ¶
run_simulation(J, x_init, T, tau, dt, T_eval, J_prime=None, omega_func=None, c_const=1.0, device=None)
Run the data-driven recurrent dynamics (CUDA if available, else CPU).
Wraps sim.run_sim with the softplus nonlinearity, the mean-
stabilizer (target_mean=1.), and torch conversion of J/J_prime
/x_init. Returns only the saved trajectory snapshots.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
J
|
(ndarray, shape(N, N))
|
Recurrent weights. |
required |
x_init
|
(ndarray, shape(N, N_batch))
|
Initial states. |
required |
T
|
float
|
Integration time, time constant, step, save period. |
required |
tau
|
float
|
Integration time, time constant, step, save period. |
required |
dt
|
float
|
Integration time, time constant, step, save period. |
required |
T_eval
|
float
|
Integration time, time constant, step, save period. |
required |
J_prime
|
(ndarray, shape(N, N))
|
Required if |
None
|
omega_func
|
callable or None
|
Time-varying drift. |
None
|
c_const
|
float
|
Mean-stabilizer strength. |
1.
|
device
|
str or int or None
|
Torch device. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
x_save |
(ndarray, shape(N_eval, N, N_batch))
|
Saved state snapshots. |
Source code in ring/data_driven.py
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 | |
compute_m ¶
compute_m(x_save, X)
Project trajectories onto tuning-curve basis via tensor contraction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x_save
|
(ndarray, shape(T_eval, N, N_batch))
|
Trajectories. |
required |
X
|
(ndarray, shape(N_theta, N))
|
Tuning-curve basis. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
m |
(ndarray, shape(T_eval, N_theta, N_batch))
|
|
Source code in ring/data_driven.py
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 | |
remove_discontinuities_mod_2pi ¶
remove_discontinuities_mod_2pi(hd)
Mod-2pi-wrap an angle series, marking wrap discontinuities as NaN.
Used for plotting head-direction traces without spurious vertical lines at each wrap-around.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hd
|
(ndarray, shape(T))
|
Continuous (possibly unwrapped) angles. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
hd_plot |
(ndarray, shape(T))
|
Mod-2pi-wrapped; entries flanking a > pi jump are NaN. |
Source code in ring/data_driven.py
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 | |
plot_head_direction ¶
plot_head_direction(ax, m, hd, m_dt, hd_dt, vmin=0)
Plot m as a heatmap with the head-direction track overlaid.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
matplotlib axis
|
|
required |
m
|
(ndarray, shape(T_eval, N_theta))
|
|
required |
hd
|
(ndarray, shape(T_hd))
|
|
required |
m_dt
|
float
|
Time step between |
required |
hd_dt
|
float
|
Time step between |
required |
vmin
|
float
|
Lower bound for the imshow colormap (vmax is auto-set to the 97.5
percentile of |
0
|
Source code in ring/data_driven.py
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 | |
do_pca_on_tcs_and_trajectories ¶
do_pca_on_tcs_and_trajectories(X, x_save, N_pcs=3, comp_axis=None, return_V=False, return_eig=False, N_retain=None)
PCA on tuning curves and projection of trajectories into PC space.
Decomposes the centered tuning-curve matrix X - X.mean(0) and
projects both the tuning curves and the trajectories x_save onto
the top N_pcs principal components. Uses the kernel trick when
N_theta < N to avoid building the (N x N) covariance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
(ndarray, shape(N_theta, N))
|
Tuning-curve matrix (samples x features). |
required |
x_save
|
(ndarray, shape(T_eval, N, N_batch))
|
Trajectories to project. |
required |
N_pcs
|
int
|
Number of principal components. |
3
|
comp_axis
|
int or None
|
Force the kernel method ( |
None
|
return_V
|
bool
|
Also return the eigenvector matrix |
False
|
return_eig
|
bool
|
Also return eigenvalues |
False
|
N_retain
|
int
|
Number of PCs to use for the projection of |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
pcs |
(ndarray, shape(N_theta, N_retain))
|
|
pcs_traj |
(ndarray, shape(T_eval, N_pcs, N_batch))
|
|
V |
(ndarray, shape(N, N_pcs), optional)
|
|
w |
(ndarray, optional)
|
Returned in (pcs, pcs_traj, V, w) order when both flags are True. |
Source code in ring/data_driven.py
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 | |
plot_3d_pca ¶
plot_3d_pca(ax, pcs, pcs_traj, torus=False, cloud_color='black', cloud_alpha=0.1, cloud_s=10, traj_lw=None, end_s=12, start_s=5)
3D plot of trajectories in PC space with cyclic color coding.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
matplotlib 3D axis
|
|
required |
pcs
|
ndarray, shape (N_theta, >= 3)
|
|
required |
pcs_traj
|
(ndarray, shape(T_eval, 3, N_batch))
|
|
required |
torus
|
bool
|
If True, render |
False
|
cloud_color
|
(str, float, float)
|
Appearance of the |
'black'
|
cloud_alpha
|
(str, float, float)
|
Appearance of the |
'black'
|
cloud_s
|
(str, float, float)
|
Appearance of the |
'black'
|
traj_lw
|
float or None
|
Trajectory line width. None keeps the rcParams default. |
None
|
end_s
|
float
|
Marker sizes for the trajectory end dot and start cross. Smaller values stop the black markers from swamping the trajectory colours. |
12
|
start_s
|
float
|
Marker sizes for the trajectory end dot and start cross. Smaller values stop the black markers from swamping the trajectory colours. |
12
|
Source code in ring/data_driven.py
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 | |
torus_display_frame ¶
torus_display_frame(pcs, phase_a, phase_b)
Build a 3-axis display frame that makes a 2-torus manifold read as a torus.
Taking the top three principal components is not a stable way to view this
manifold. On the hexagonal grid the leading PCA block is SIX-fold
near-degenerate (three lattice directions times cos/sin), with the six
eigenvalues spanning under 5% and a 92% gap to the seventh. Which three of
the six come out on top is therefore decided by noise, and a perturbation as
small as a few percent in J reshuffles them, so the projection can swing
from showing the hole to hiding it while the manifold itself is unchanged.
Since the two toroidal phases are known, the frame can be pinned to them instead:
x,yspan the plane in whichphase_atraces a closed circle, obtained by regressing its cosine and sine onto the block;zis the residual direction that best encodesphase_b, which lifts the tube out of that plane.
A projection shows a hole exactly when one toroidal angle sweeps a full circle in the plotted plane while the other displaces along the third axis, which is what this construction guarantees. It is deterministic given the lattice, so it does not drift with the PC ordering.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pcs
|
(ndarray, shape(N_points, N_pcs))
|
Manifold projected onto the leading PCs. Use the whole degenerate block (six components for the hexagonal grid), not three. |
required |
phase_a
|
(ndarray, shape(N_points))
|
Toroidal phase to place in the plotted plane, in radians. |
required |
phase_b
|
(ndarray, shape(N_points))
|
The other toroidal phase, in radians, which sets the third axis. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
frame |
(ndarray, shape(3, N_pcs))
|
Orthonormal rows. Apply to the manifold as |
Source code in ring/data_driven.py
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 | |
compute_distances_to_ring ¶
compute_distances_to_ring(X, x_save, device='cpu')
(internal) Closest-tuning-curve distance per timestep, normalized by sqrt(N).
Source code in ring/data_driven.py
525 526 527 528 529 530 531 532 533 534 535 536 537 538 | |
compute_distances_to_ring_batched ¶
compute_distances_to_ring_batched(X, x_save, device='cpu', chunk_size=10)
Chunked wrapper around compute_distances_to_ring to keep GPU memory in check.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
(ndarray, shape(N_theta, N))
|
|
required |
x_save
|
(ndarray, shape(T_eval, N, N_batch))
|
|
required |
device
|
str
|
|
'cpu'
|
chunk_size
|
int
|
Number of batch elements per GPU chunk. |
10
|
Returns:
| Name | Type | Description |
|---|---|---|
all_dists |
(ndarray, shape(T_eval, N_batch))
|
Normalized closest-tuning-curve distance per timestep per batch. |
Source code in ring/data_driven.py
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 | |
circular_com ¶
circular_com(data, return_idx=False)
Circular center of mass of curves indexed by theta.
The float-angle computation is delegated to
analysis.circular_center_of_mass (bit-identical single source); this
function adds the optional integer-bin (floor) return.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
(ndarray, shape(N_curves, N_theta))
|
|
required |
return_idx
|
bool
|
If True, return integer bin indices (floor) instead of float angles. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
com |
(ndarray, shape(N_curves))
|
Either angles in [0, 2*pi) (default) or integer bin indices. |
Source code in ring/data_driven.py
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 | |
sort_weight_matrix ¶
sort_weight_matrix(J, Phi)
Sort J rows and columns by the circular COM of Phi's tuning curves.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
J
|
(ndarray, shape(N, N))
|
|
required |
Phi
|
(ndarray, shape(N_theta, N))
|
|
required |
Returns:
| Name | Type | Description |
|---|---|---|
J_srt |
(ndarray, shape(N, N))
|
|
order |
(ndarray, shape(N))
|
Sorting permutation (apply via |
Source code in ring/data_driven.py
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 | |
load_hd_timeseries_data ¶
load_hd_timeseries_data(file_path=HD_TIMESERIES_PATH)
(internal) Load (hd, dt) from a Peyrache-style npz.
Source code in ring/data_driven.py
614 615 616 617 618 619 620 | |
interpolate_angle_nans ¶
interpolate_angle_nans(hd)
(internal) Linearly interpolate NaN gaps in a wrapped-angle series.
Interpolation is done on the complex-exponential representation
z = exp(1j * hd) to handle wrap-around correctly.
Source code in ring/data_driven.py
623 624 625 626 627 628 629 630 631 632 633 634 635 636 | |
preprocess_hd_data ¶
preprocess_hd_data(hd, data_dt, smoothing_sigma=10)
(internal) NaN-interpolate + unwrap + Gaussian-smooth + compute omega(t).
Prepends 2000 stationary samples to the unwrapped series so the dynamics has a quiet start.
Returns:
| Name | Type | Description |
|---|---|---|
hd_unwrap_smooth |
ndarray
|
|
omega |
ndarray
|
Angular velocity = d(hd)/dt of the smoothed series. |
Source code in ring/data_driven.py
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 | |
load_hd_and_omega ¶
load_hd_and_omega()
Load mouse HD timeseries and compute its smoothed angular velocity.
Returns:
| Name | Type | Description |
|---|---|---|
hd |
ndarray
|
|
omega |
ndarray
|
|
data_dt |
float
|
|
Source code in ring/data_driven.py
659 660 661 662 663 664 665 666 667 668 669 670 | |
ring.gp_opt¶
ring.gp_opt ¶
Grid-search optimizer for the (scale, bias, beta) tuning-curve generative parameters.
Walks a (scale, bias, beta) grid, generates Phi_m samples from each parameter
triple, computes the resulting Fourier-space covariance, and compares to a
target Gamma_phi_data_ft (typically derived from real mouse data in
notebooks/data_and_generative_model.ipynb).
Run as a script to (re)produce grid_search_results.npz::
python -m ring.gp_opt
Public surface used by notebooks: gen_Phi_m and compute_cov_from_params
(see e.g. data_and_generative_model.ipynb); the other functions support the
script flow.
sample_z ¶
sample_z(N_samples, N_freq, device=None)
Draw iid complex normal Fourier coefficients z for GP sampling.
The DC coefficient (column 0) is constrained to be real (and rescaled
by sqrt(2)) so the inverse Fourier transform produces a real series.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
N_samples
|
int
|
Number of independent draws. |
required |
N_freq
|
int
|
Number of Fourier frequencies (typically |
required |
device
|
int or None
|
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
z |
(ndarray or Tensor, shape(N_samples, N_freq), complex)
|
|
Notes
Draws in (N_samples, N_freq) layout. tc.sample_tcs draws the same
kind of coefficients in the transposed (N_freq, N) layout, so the two
fill the RNG stream in a different order and yield different realizations
under the same seed. They are intentionally NOT interchangeable, so do not
reroute one through the other.
Source code in ring/gp_opt.py
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | |
gen_Phi_m ¶
gen_Phi_m(scale, bias, beta, N_samples, N_theta, device=None, return_Gamma_x_ft=False, normalize=False)
Generate Phi_m samples from a wraparound Gaussian process + softplus.
X_m is a draw from the wraparound-Gaussian prior with length
scale scale; Phi_m = softplus(X_m - bias, beta=beta) applies
the nonlinearity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scale
|
float
|
Wraparound-Gaussian length scale. |
required |
bias
|
float
|
Offset subtracted before the nonlinearity. |
required |
beta
|
float
|
Sharpness of the softplus nonlinearity. |
required |
N_samples
|
int
|
Number of independent samples. |
required |
N_theta
|
int
|
Number of angular grid points. |
required |
device
|
int or None
|
CUDA device index, or |
None
|
return_Gamma_x_ft
|
bool
|
Also return the Fourier-space covariance. |
False
|
normalize
|
bool
|
Normalize each sample by its mean before returning (avoids the all-zero collapse for some parameter combinations). |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
Phi_m |
(ndarray or Tensor, shape(N_samples, N_theta))
|
|
X_m |
same type/shape, optional
|
Returned only if |
Gamma_x_ft |
same type, shape (N_theta // 2 + 1,), optional
|
Returned only if |
Source code in ring/gp_opt.py
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 | |
compute_cov_from_params ¶
compute_cov_from_params(params, N_samples, N_theta, device=None)
Generate Phi_m samples for params = (scale, bias, beta) and return their covariance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
sequence of 3 floats
|
(scale, bias, beta). |
required |
N_samples
|
int
|
|
required |
N_theta
|
int
|
|
required |
device
|
int or None
|
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Gamma_phi |
(ndarray or Tensor, shape(N_theta))
|
|
Gamma_phi_ft |
(ndarray or Tensor, shape(N_theta // 2 + 1))
|
|
Source code in ring/gp_opt.py
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 | |
eval_loss ¶
eval_loss(params, Gamma_phi_data_ft, N_samples, N_theta, device=None)
L2 distance between the model and data covariance in the first 20 Fourier components.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
sequence of 3 floats
|
(scale, bias, beta). |
required |
Gamma_phi_data_ft
|
ndarray, shape (>= 20,)
|
Target Fourier-space covariance. |
required |
N_samples
|
Forwarded to |
required | |
N_theta
|
Forwarded to |
required | |
device
|
Forwarded to |
required |
Returns:
| Name | Type | Description |
|---|---|---|
err |
float
|
|
Source code in ring/gp_opt.py
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 | |
run_grid_search ¶
run_grid_search(Gamma_phi_data_ft)
Run the (scale, bias, beta) grid search and write intermediate + final results.
Seeds the global RNG to 42 before any sampling, so results are bit-reproducible.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
Gamma_phi_data_ft
|
ndarray, shape (>= 20,)
|
Target Fourier coefficients. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
best_params |
dict
|
|
loss_vals |
(ndarray, shape(N_SCALE_POINTS, N_BIAS_POINTS, N_BETA_POINTS))
|
Full grid of loss values. |
Source code in ring/gp_opt.py
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 | |
main ¶
main()
Script entry point: load INPUT_GAMMA_FILE and run the grid search.
Source code in ring/gp_opt.py
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 | |
ring.regression¶
ring.regression ¶
Ridge regression for tuning-curve-to-weight inference.
Solves the regularized least-squares problem X ≈ J @ Phi for the weight
matrix J, with three options for handling the N_theta vs N
asymmetry: primal, dual, and leave_one_out.
compute_J ¶
compute_J(X, Phi, lamda, method='opt')
Solve ridge regression X ≈ J @ Phi with diagonal subtraction.
Removes the autapse (self-coupling) by subtracting a diagonal correction
from the unconstrained solution J_uc; the returned J has zero
diagonal in the relevant inner product.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
(ndarray, shape(N_theta, N))
|
Target activity (e.g. preactivations or trajectories). |
required |
Phi
|
(ndarray, shape(N_theta, N))
|
Predictor activity (e.g. tuning curves). |
required |
lamda
|
float
|
Ridge regularization strength, in the |
required |
method
|
(opt, primal, dual, leave_one_out)
|
Solver variant:
|
'opt'
|
Notes
The data term of the loss carries a 1 / N alongside the 1 / N_theta,
.. math::
L(J) = \frac{1}{N} \frac{1}{2\pi} \int d\theta \sum_i
\Big( \sum_j J_{ij} \phi_j(\theta) - x_i(\theta) \Big)^2
+ \lambda \sum_{ij} J_{ij}^2 ,
so that lamda has a well-defined N -> infinity limit. Without the
1 / N the data term grows with N while the penalty does not, the
effective regularization is lamda / N, and it vanishes at fixed
lamda. The dual kernel is then Phi @ Phi.T / N + N_theta * lamda * I,
with eigenvalues N * N_theta * (Ghat_phi_n + lamda), free of both N
and N_theta.
This convention was adopted on 2026-07-31 and is a change of normalization,
not a correction. To convert a value from the earlier convention, in which
the data term had no 1 / N, use lamda_new = lamda_old / N.
Returns:
| Name | Type | Description |
|---|---|---|
J |
(ndarray, shape(N, N))
|
Weight matrix with the diagonal correction applied. |
J_uc |
(ndarray or None, shape(N, N))
|
Unconstrained ridge solution before diagonal subtraction. |
Source code in ring/regression.py
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | |
ring.analysis¶
ring.analysis ¶
Tuning-curve statistics + model-vs-data comparison for the paper analysis.
Provides circular-statistics primitives (COM, centering, peak-finding),
per-mouse aggregate computations, scalar comparison metrics (peak counts,
peak values, flip symmetry, bits-per-spike), and a Kuiper-test-with-
FDR-correction pipeline. The top-level analyze_tuning_curves runs all
four comparison metrics on data vs model and returns a dict; the npz
serialization round-trip uses save_analysis_results /
load_analysis_results. Consumed by
notebooks/data_and_generative_model.ipynb and ring/plot.py.
circular_center_of_mass ¶
circular_center_of_mass(tuning_curves)
Angular center of mass of one or more tuning curves.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tuning_curves
|
(ndarray, shape(N_curves, N_theta))
|
|
required |
Returns:
| Name | Type | Description |
|---|---|---|
coms |
(ndarray, shape(N_curves))
|
Angular positions in [0, 2*pi). |
Source code in ring/analysis.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | |
center_tuning_curves ¶
center_tuning_curves(tuning_curves)
Roll each tuning curve so its circular center of mass is at index 0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tuning_curves
|
(ndarray, shape(N_curves, N_theta))
|
|
required |
Returns:
| Name | Type | Description |
|---|---|---|
centered |
(ndarray, shape(N_curves, N_theta))
|
|
Source code in ring/analysis.py
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | |
find_local_maxima ¶
find_local_maxima(signal, z_thresh)
Indices of peaks in signal exceeding z_thresh SDs above mean.
Treats the signal as circular (wrap-around at the boundary).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
signal
|
(ndarray, shape(N))
|
|
required |
z_thresh
|
float
|
|
required |
Returns:
| Name | Type | Description |
|---|---|---|
maxima |
ndarray of int
|
|
Source code in ring/analysis.py
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | |
select_mice_by_cell_count ¶
select_mice_by_cell_count(mouse_nums, n_mice)
Select the n_mice mice with the most recorded cells.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mouse_nums
|
(ndarray, shape(N_curves))
|
Per-cell mouse-id labels. |
required |
n_mice
|
int
|
Number of mice to keep. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
selected |
(ndarray, shape(n_mice))
|
Mouse-id values, ordered by descending cell count. |
Source code in ring/analysis.py
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | |
compute_mean_and_std_profiles ¶
compute_mean_and_std_profiles(tuning_curves)
COM-centered mean and std profiles across one set of tuning curves.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tuning_curves
|
(ndarray, shape(N_curves, N_theta))
|
|
required |
Returns:
| Name | Type | Description |
|---|---|---|
mean_profile |
(ndarray, shape(N_theta))
|
|
std_profile |
(ndarray, shape(N_theta))
|
|
Source code in ring/analysis.py
103 104 105 106 107 108 109 110 111 112 113 114 115 116 | |
compute_mean_and_std_profiles_for_all_mice ¶
compute_mean_and_std_profiles_for_all_mice(Phi_m_data, mouse_nums)
Per-mouse mean + std profiles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
Phi_m_data
|
(ndarray, shape(N_curves, N_theta))
|
|
required |
mouse_nums
|
(ndarray, shape(N_curves))
|
|
required |
Returns:
| Name | Type | Description |
|---|---|---|
means |
(ndarray, shape(n_mice, N_theta))
|
|
stds |
(ndarray, shape(n_mice, N_theta))
|
|
Source code in ring/analysis.py
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 | |
compute_coms_for_all_mice ¶
compute_coms_for_all_mice(Phi_m_data, mouse_nums)
Per-mouse list of tuning-curve COMs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
Phi_m_data
|
(ndarray, shape(N_curves, N_theta))
|
|
required |
mouse_nums
|
(ndarray, shape(N_curves))
|
|
required |
Returns:
| Name | Type | Description |
|---|---|---|
mouse_coms |
list of ndarray
|
Length- |
Source code in ring/analysis.py
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 | |
compute_peak_counts ¶
compute_peak_counts(tuning_curves, z_thresh, max_peaks=6)
Normalized histogram of number-of-peaks across tuning curves.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tuning_curves
|
(ndarray, shape(N_curves, N_theta))
|
|
required |
z_thresh
|
float
|
Z-score threshold for peak detection. |
required |
max_peaks
|
int
|
Histogram extends to |
6
|
Returns:
| Name | Type | Description |
|---|---|---|
hist |
(ndarray, shape(max_peaks - 1))
|
Probabilities (sums to 1). |
Source code in ring/analysis.py
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 | |
get_peak_values ¶
get_peak_values(tuning_curves, num_peaks)
Top-num_peaks peak heights per curve (NaN-padded for short rows).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tuning_curves
|
(ndarray, shape(N_curves, N_theta))
|
|
required |
num_peaks
|
int
|
|
required |
Returns:
| Name | Type | Description |
|---|---|---|
results |
(ndarray, shape(N_curves, num_peaks))
|
Sorted descending; missing values are NaN. |
Source code in ring/analysis.py
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 | |
compute_symmetry_scores ¶
compute_symmetry_scores(tuning_curves)
Flip-symmetry correlation for each tuning curve.
For each curve, reflect across its circular COM and compute the Pearson correlation between the original and the reflection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tuning_curves
|
(ndarray, shape(N_curves, N_theta))
|
|
required |
Returns:
| Name | Type | Description |
|---|---|---|
scores |
(ndarray, shape(N_curves))
|
Pearson r in [-1, 1]. |
Source code in ring/analysis.py
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 | |
compute_bits_per_spike ¶
compute_bits_per_spike(tuning_curves)
Per-curve bits-per-spike (mean of tc * log2(tc)).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tuning_curves
|
(ndarray, shape(N_curves, N_theta))
|
|
required |
Returns:
| Name | Type | Description |
|---|---|---|
bits |
(ndarray, shape(N_curves))
|
|
Source code in ring/analysis.py
237 238 239 240 241 242 243 244 245 246 247 248 | |
analyze_circular_datasets ¶
analyze_circular_datasets(datasets, alpha=0.05)
Kuiper uniformity test per dataset + Benjamini-Hochberg FDR correction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
datasets
|
list of ndarray
|
Each entry is an array of angular values to test against uniformity. |
required |
alpha
|
float
|
FDR target significance level. |
0.05
|
Returns:
| Name | Type | Description |
|---|---|---|
results |
list of dict
|
Per-dataset |
Source code in ring/analysis.py
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 | |
analyze_and_print_stats ¶
analyze_and_print_stats(mouse_coms)
Run uniformity tests on per-mouse COM distributions; print a summary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mouse_coms
|
list of ndarray
|
From |
required |
Source code in ring/analysis.py
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 | |
analyze_tuning_curves ¶
analyze_tuning_curves(data_curves, model_curves, z_thresholds=[1.0, 0.5, 0.0])
Run all four data-vs-model comparison metrics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_curves
|
(ndarray, shape(N_curves, N_theta))
|
|
required |
model_curves
|
(ndarray, shape(N_curves, N_theta))
|
|
required |
z_thresholds
|
list of float
|
Thresholds for peak detection in the peak-count histogram. |
[1.0, 0.5, 0.0]
|
Returns:
| Name | Type | Description |
|---|---|---|
results |
dict
|
Keys: |
Source code in ring/analysis.py
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 | |
save_analysis_results ¶
save_analysis_results(results, filename='tuning_curve_analysis.npz')
Serialize the dict from analyze_tuning_curves to compressed npz.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results
|
dict
|
|
required |
filename
|
str
|
|
'tuning_curve_analysis.npz'
|
Source code in ring/analysis.py
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 | |
load_analysis_results ¶
load_analysis_results(filename='tuning_curve_analysis.npz')
Inverse of save_analysis_results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
|
'tuning_curve_analysis.npz'
|
Returns:
| Name | Type | Description |
|---|---|---|
results |
dict
|
Same structure produced by |
Source code in ring/analysis.py
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 | |
ring.fn¶
ring.fn ¶
Low-level math helpers: nonlinearities and Fourier-space covariance.
Used by other ring/* modules and notebooks for activation functions
(unity_erf, softplus) and circulant covariance estimation
(calc_C).
unity_erf ¶
unity_erf(x)
Error-function nonlinearity normalized so phi'(0) = 1.
phi(x) = erf(sqrt(pi) * x / 2).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
float or ndarray or Tensor
|
Input. |
required |
Returns:
| Type | Description |
|---|---|
Same type and shape as `x`.
|
|
Source code in ring/fn.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | |
unity_erf_deriv ¶
unity_erf_deriv(x)
Derivative of unity_erf: exp(-pi * x^2 / 4).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
float or ndarray or Tensor
|
Input. |
required |
Returns:
| Type | Description |
|---|---|
Same type and shape as `x`.
|
|
Source code in ring/fn.py
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | |
nonlin_idealized ¶
nonlin_idealized(x, beta)
Idealized (saturating) activation: 1 + unity_erf(beta * x).
The error-function nonlinearity used for the large-N "idealized" generative process (saturates to 0 and 2). Shared by the spectra / weight-matrix / spurious-fixed-point notebooks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
float or ndarray or Tensor
|
Input. |
required |
beta
|
float
|
Response sharpness. |
required |
Returns:
| Type | Description |
|---|---|
Same type and shape as `x`.
|
|
Source code in ring/fn.py
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | |
softplus ¶
softplus(x, beta=1.0)
Numerically stable softplus: log(1 + exp(beta * x)) / beta.
Uses x + log(1 + exp(-beta*x))/beta for x >= 0 and
log(1 + exp(beta*x))/beta for x < 0 to avoid overflow.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
float or ndarray or Tensor
|
Input. Python floats are promoted to a 1-element numpy array. |
required |
beta
|
float
|
Sharpness parameter; approaches ReLU as |
1.0
|
Returns:
| Type | Description |
|---|---|
Same type and shape as the (possibly promoted) input.
|
|
Source code in ring/fn.py
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | |
calc_C ¶
calc_C(X, return_ft=True)
Circulant (wraparound) covariance of rows of X via FFT.
Uses the identity E[|FFT(x)|^2] = FT(C): averaging the squared
Fourier magnitudes across samples yields the power spectrum, whose
inverse transform is the circulant covariance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
(ndarray or Tensor, shape(N_samples, N_theta))
|
Sample matrix; rows are samples. |
required |
return_ft
|
bool
|
If True, return both |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
C |
same type as `X`, shape (N_theta,)
|
Real-space circulant covariance. |
C_ft |
same type as `X`, shape (N_theta // 2 + 1,)
|
Fourier-space covariance (the power spectrum). Only returned
if |
Source code in ring/fn.py
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 | |
ring.plot¶
ring.plot ¶
Plotting helpers for the paper figures.
Each public plot_* function takes one or more matplotlib axes and renders
a specific panel of the paper figures (mostly Figs 4, 6 from
notebooks/data_and_generative_model.ipynb). The helpers setup_tc_axes and
setup_profile_axes are internal axis-formatting utilities shared by
several plotters.
setup_tc_axes ¶
setup_tc_axes(axes)
(internal) Standardize tuning-curve panel formatting.
Sets x-tick positions to [0, pi, 2pi] with symbolic labels, x-limits to [0, 2pi], y-limits to [0, 10]; suppresses x-labels on non-bottom rows and y-tick labels on non-left columns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
axes
|
ndarray of matplotlib axes
|
1-D or 2-D grid of axes. |
required |
Source code in ring/plot.py
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | |
setup_profile_axes ¶
setup_profile_axes(ax, ylabel)
(internal) Standardize profile-plot panel formatting.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
matplotlib axis
|
|
required |
ylabel
|
str
|
|
required |
Source code in ring/plot.py
57 58 59 60 61 62 63 64 65 66 67 68 69 | |
plot_log_sigma_scatter ¶
plot_log_sigma_scatter(ax, opt_sigmas)
Cross-validation sigma-smoothing comparison scatter.
Plots log10(sigma_fold1) vs log10(sigma_fold2) and overlays the
Pearson correlation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
matplotlib axis
|
|
required |
opt_sigmas
|
(ndarray, shape(N_units, 2))
|
Optimal sigmas per CV fold. |
required |
Source code in ring/plot.py
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | |
plot_loss_vs_scale ¶
plot_loss_vs_scale(ax, scale_vals, min_losses, opt_scale)
Optimization loss vs the wrap-Gaussian scale parameter, with optimum marked.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
matplotlib axis or None
|
If None, a fresh |
required |
scale_vals
|
(ndarray, shape(N_scale))
|
|
required |
min_losses
|
(ndarray, shape(N_scale))
|
Minimum loss at each scale (after marginalizing over bias, beta). |
required |
opt_scale
|
float
|
Optimal scale value (where to draw the vertical line). |
required |
Source code in ring/plot.py
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 | |
plot_loss_landscape ¶
plot_loss_landscape(ax, loss_slice, bias_vals, beta_vals, opt_bias, opt_beta)
2D loss-landscape heatmap in (bias, beta) at the optimal scale, with optimum marked.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
matplotlib axis or None
|
If None, a fresh |
required |
loss_slice
|
(ndarray, shape(N_bias, N_beta))
|
Loss landscape at the optimal scale. |
required |
bias_vals
|
(ndarray, shape(N_bias))
|
|
required |
beta_vals
|
(ndarray, shape(N_beta))
|
|
required |
opt_bias
|
float
|
Optimal (bias, beta). |
required |
opt_beta
|
float
|
Optimal (bias, beta). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
ax |
matplotlib axis
|
|
cbar |
matplotlib colorbar
|
|
Source code in ring/plot.py
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 | |
plot_data_tuning_curves ¶
plot_data_tuning_curves(axes, mouse_nums_to_plot, mouse_nums, mouse_names, plain_tcs, scalings, Phi_m_data, fold_colors=None)
Per-mouse tuning curves: plain CV-fold pairs + smoothed canonical.
For each mouse in mouse_nums_to_plot, randomly samples
axes.shape[1] units and plots both CV-fold tuning curves plus the
smoothed canonical curve.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
axes
|
ndarray of matplotlib axes, shape (N_mice, N_cols)
|
|
required |
mouse_nums_to_plot
|
sequence of int
|
Mouse ids to render (one per row). |
required |
mouse_nums
|
(ndarray, shape(N_curves))
|
Per-cell mouse-id labels. |
required |
mouse_names
|
(ndarray, shape(N_curves))
|
Per-cell mouse names (strings). |
required |
plain_tcs
|
(ndarray, shape(N_curves, 2, N_theta))
|
Plain (per-CV-fold) tuning curves. |
required |
scalings
|
(ndarray, shape(N_curves))
|
Per-cell scaling factors (mean-normalize). |
required |
Phi_m_data
|
(ndarray, shape(N_curves, N_theta))
|
Smoothed canonical tuning curves. fold_colors : tuple of 2 str or None Colours for the two cross-validation folds. None keeps the original bright pair; Fig. 2 passes the muted published pair. |
required |
Source code in ring/plot.py
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 | |
plot_model_tuning_curves ¶
plot_model_tuning_curves(axes, opt_params, seed=42)
Random samples from the generative process at the optimum parameters.
One independent sample per sub-panel, so every panel shows a DISTINCT curve.
Until 2026-08-02 this drew a fixed 16 samples and then picked one per panel
with np.random.choice, i.e. WITH replacement, which on the published 4x6
grid gave 24 panels holding only 11 distinct curves with pixel-identical
duplicates. That defeats the panel's purpose, which is to show the diversity
of the process, so the sample count now follows the number of panels and each
sample is used exactly once. The samples are i.i.d., so consuming them in
order is already a random assignment and no extra permutation is needed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
axes
|
ndarray of matplotlib axes (1-D or 2-D)
|
|
required |
opt_params
|
sequence of 3 floats
|
(scale, bias, beta). |
required |
seed
|
int
|
Seed for the global RNG that |
42
|
Source code in ring/plot.py
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 | |
plot_profile ¶
plot_profile(ax, theta, profiles, mean_profile=None, profile_label='', mean_label='mean', color=style.INDIVIDUAL_DATA, model_profile=None)
(internal) Plot individual + mean profiles with optional model overlay.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
matplotlib axis
|
|
required |
theta
|
(ndarray, shape(N_theta))
|
|
required |
profiles
|
(ndarray, shape(N_curves, N_theta))
|
|
required |
mean_profile
|
(ndarray or None, shape(N_theta))
|
|
None
|
profile_label
|
str
|
Y-axis label. |
''
|
mean_label
|
str
|
(Unused; kept for backward compat with signature.) |
'mean'
|
color
|
str
|
Color for the individual-profile lines. |
INDIVIDUAL_DATA
|
model_profile
|
(ndarray or None, shape(N_theta))
|
|
None
|
Source code in ring/plot.py
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 | |
plot_mean_std_profiles ¶
plot_mean_std_profiles(ax_mu, ax_std, all_mus, all_stds, opt_params=None)
Mean + std profile panels, with optional generative-process overlay.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax_mu
|
matplotlib axes
|
|
required |
ax_std
|
matplotlib axes
|
|
required |
all_mus
|
(ndarray, shape(n_mice, N_theta))
|
Per-mouse mean and std profiles (from
|
required |
all_stds
|
(ndarray, shape(n_mice, N_theta))
|
Per-mouse mean and std profiles (from
|
required |
opt_params
|
sequence of 3 floats or None
|
If given, also draws a model curve from
|
None
|
Source code in ring/plot.py
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 | |
plot_covariance_comparison ¶
plot_covariance_comparison(ax, Gamma_phi_data, Gamma_phi_opt)
Overlay data + generative-process covariance functions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
matplotlib axis
|
|
required |
Gamma_phi_data
|
(ndarray, shape(N_theta))
|
|
required |
Gamma_phi_opt
|
(ndarray, shape(N_theta))
|
|
required |
Source code in ring/plot.py
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 | |
plot_peak_count_comparison ¶
plot_peak_count_comparison(ax, data_counts, model_counts)
Side-by-side bar chart of peak-count distributions: data vs model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
matplotlib axis
|
|
required |
data_counts
|
(ndarray, shape(N_bins))
|
|
required |
model_counts
|
(ndarray, shape(N_bins))
|
|
required |
Source code in ring/plot.py
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 | |
plot_peak_value_histograms ¶
plot_peak_value_histograms(ax, data_peaks, model_peaks)
Peak-value distribution: data vs model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
matplotlib axis
|
|
required |
data_peaks
|
ndarray
|
Flat arrays of peak heights. |
required |
model_peaks
|
ndarray
|
Flat arrays of peak heights. |
required |
Source code in ring/plot.py
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 | |
plot_symmetry_histogram ¶
plot_symmetry_histogram(ax, data_scores, model_scores, ylim=None)
Flip-symmetry score distribution: data vs model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
matplotlib axis
|
|
required |
data_scores
|
ndarray
|
Per-curve Pearson r in [-1, 1]. |
required |
model_scores
|
ndarray
|
Per-curve Pearson r in [-1, 1]. |
required |
ylim
|
tuple or None
|
Optional y-axis limits. |
None
|
Source code in ring/plot.py
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 | |
plot_information_histogram ¶
plot_information_histogram(ax, data_info, model_info)
Bits-per-spike distribution: data vs model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
matplotlib axis
|
|
required |
data_info
|
ndarray
|
|
required |
model_info
|
ndarray
|
|
required |
Source code in ring/plot.py
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 | |
plot_mouse_coms ¶
plot_mouse_coms(ax, mouse_coms, null=False, color=style.COM_GREEN, seed=42)
Per-mouse circular center-of-mass scatter (one row per mouse).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
matplotlib axis
|
|
required |
mouse_coms
|
list of ndarray
|
Length-n_mice; from |
required |
null
|
bool
|
If True, replace each mouse's COMs with a uniform-random null draw of the same size (for a visual significance baseline). |
False
|
color
|
str
|
Scatter color. |
COM_GREEN
|
seed
|
int
|
Seed for the global RNG, set only when |
42
|
Source code in ring/plot.py
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 | |
plot_covariance_grid ¶
plot_covariance_grid(axes, mouse_nums, mouse_nums_to_plot, mouse_names, Phi_m_data, subsample_sizes)
Grid of per-mouse subsampled covariance matrices, demonstrating convergence.
Rows = mice in mouse_nums_to_plot; columns = subsample sizes in
subsample_sizes. Each cell shows the empirical covariance of a
random N_sub subset of that mouse's tuning curves.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
axes
|
ndarray of matplotlib axes, shape (N_mice_to_plot, N_subsample_sizes)
|
|
required |
mouse_nums
|
ndarray
|
|
required |
mouse_nums_to_plot
|
sequence of int
|
|
required |
mouse_names
|
ndarray
|
|
required |
Phi_m_data
|
(ndarray, shape(N_curves, N_theta))
|
|
required |
subsample_sizes
|
sequence of int
|
|
required |
Returns:
| Name | Type | Description |
|---|---|---|
im |
matplotlib image handle (last drawn)
|
|
Source code in ring/plot.py
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 | |
plot_cov_examples ¶
plot_cov_examples(ax)
Wrap-Gaussian covariance functions at a few scales.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
matplotlib axis
|
|
required |
Source code in ring/plot.py
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 | |
plot_pre_examples ¶
plot_pre_examples(ax)
Sample pre-nonlinearity tuning curves at a few scales, vertically offset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
matplotlib axis
|
|
required |
Source code in ring/plot.py
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 | |
plot_nonlin_examples ¶
plot_nonlin_examples(ax)
Softplus nonlinearity examples at a few (bias, beta) pairs, plus Gaussian prior overlay.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
matplotlib axis
|
|
required |
Source code in ring/plot.py
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 | |
plot_ring_schematic ¶
plot_ring_schematic(ax, n_neurons=19, soma_r=0.155, e_targets=(1, 2), i_targets=(3, 4, 5), e_color=None, i_color=None, label_fontsize=20, theta_fontsize=15)
Classical ring-attractor connectivity schematic (Fig. 2A).
Somata are evenly spaced on a unit ring, with excitatory (short-range) and
inhibitory (longer-range) projections drawn from the top neuron. Every
connection begins and ends on the inner tangent circle of radius
1 - soma_r, the circle inscribed against all somata, so terminals meet
their target squarely: excitatory discs are centred on the soma edge and
inhibitory bars lie along the tangent there. Terminal placement is therefore
parametric, and re-anchors itself if soma_r or n_neurons changes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
matplotlib axes
|
|
required |
n_neurons
|
int
|
Number of somata on the ring. |
19
|
soma_r
|
float
|
Soma radius in ring-radius units. Somata stay visibly separated while
|
0.155
|
e_targets
|
sequence of int
|
Neuron offsets (both signs are drawn) receiving excitatory and inhibitory projections from the source neuron. |
(1, 2)
|
i_targets
|
sequence of int
|
Neuron offsets (both signs are drawn) receiving excitatory and inhibitory projections from the source neuron. |
(1, 2)
|
e_color
|
str or None
|
Optional override colours for the E/I labels. When None (default), the
labels take |
None
|
i_color
|
str or None
|
Optional override colours for the E/I labels. When None (default), the
labels take |
None
|
Source code in ring/plot.py
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 | |
plot_circulant_weights ¶
plot_circulant_weights(ax, n_theta=1000, width=1.0, offset=0.5, title_fontsize=12)
Circulant Mexican-hat weight matrix J(theta - theta') (Fig. 1, panel b).
Schematic only, with no colorbar and no meaningful weight units.
The profile is a Gaussian minus a constant, exp(-(dt/width)**2) - offset,
so it is positive near the diagonal (local excitation) and negative beyond
dt = width * sqrt(-ln offset) (longer-range inhibition), which is what
the caption and the Introduction claim.
Before 2026-08-02 the offset was absent, so the function was strictly
positive with no inhibitory surround at all, and it read as a Mexican hat
only because an autoscaled diverging colormap painted its near-zero tail
with the negative-end colour. Subtracting offset = 0.5 and taking colour
limits symmetric about zero makes the sign change real and puts it exactly
where an autoscaled midpoint would fall, so the picture looks the same
while the colour scale is honest.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
matplotlib axes
|
|
required |
n_theta
|
int
|
Grid resolution along each angular axis. |
1000
|
width
|
float
|
Gaussian width of the excitatory lobe, in radians. |
1.0
|
offset
|
float
|
Constant subtracted from the Gaussian. Sets the sign change, and must be 0.5 to reproduce the pre-2026-08-02 rendering exactly. |
0.5
|
Source code in ring/plot.py
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 | |
plot_circulant_tuning_curves ¶
plot_circulant_tuning_curves(ax, n_neurons=50, step=5, width2=40.0)
Translation-invariant tuning curves predicted by classical models (Fig. 2C).
Identical bumps tiling the theta axis, shaded light-to-dark so the neuron-specific shift is legible.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
matplotlib axes
|
|
required |
n_neurons
|
int
|
Number of neurons spanning the ring. |
50
|
step
|
int
|
Plot every |
5
|
width2
|
float
|
Squared Gaussian width, in neuron-index units. |
40.0
|
Source code in ring/plot.py
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 | |
plot_flow_schematic ¶
plot_flow_schematic(ax, box_color=style.SCHEMATIC_BOX, edge_color='black', fontsize=6.4, arrow_label_fontsize=7.4, box_w=0.246, box_h=0.345, lw=1.1)
Flow of the paper: data to data-driven RNN, generative process, DMFT.
Laid out three columns by two rows. Two of its neighbours in the top band are aspect-locked, so shortening that band widens this panel; the wide layout is what keeps the boxes undistorted at the resulting aspect (~2.3).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
matplotlib axes
|
|
required |
box_color
|
str
|
Fill and outline of the boxes. |
SCHEMATIC_BOX
|
edge_color
|
str
|
Fill and outline of the boxes. |
SCHEMATIC_BOX
|
fontsize
|
float
|
Box label size. |
6.4
|
arrow_label_fontsize
|
float
|
Size of the N -> infinity label on the synth -> dmft arrow. |
7.4
|
box_w
|
float
|
Box size in axes fractions. |
0.246
|
box_h
|
float
|
Box size in axes fractions. |
0.246
|
lw
|
float
|
Outline and arrow width. |
1.1
|
Source code in ring/plot.py
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 | |
plot_embedding_schematic ¶
plot_embedding_schematic(ax, aspect=0.77, ordered=style.EMBED_ORDERED, disordered=style.EMBED_DISORDERED, grey='#E8E8E8', seed=0)
Ring-embedding schematic: geometric ring -> ordered vs disordered tuning.
A warped closed ring (circular symmetry) is mapped, through a Fourier embedding,
to ordered tuning curves that are identical up to shifts, and, through a Gaussian
embedding, to disordered heterogeneous tuning curves. Portrait "Y" layout (ring
on top, two embedding branches fanning down) so it fits as a full-height left
panel of the spectral-structure figure. aspect is the panel's width/height; pass the real value so the
equal-aspect drawing fills the panel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
matplotlib axes
|
|
required |
aspect
|
float
|
Panel width/height, so the drawing fills the panel without distortion. |
0.77
|
ordered
|
str
|
Colours for the ordered (Fourier) branch, the disordered (Gaussian) branch, and the tuning-box fill. The two branch colours are the SAME pair the spectral panels use for J and its circulant surrogate, so one colour means one thing across the whole figure. |
EMBED_ORDERED
|
disordered
|
str
|
Colours for the ordered (Fourier) branch, the disordered (Gaussian) branch, and the tuning-box fill. The two branch colours are the SAME pair the spectral panels use for J and its circulant surrogate, so one colour means one thing across the whole figure. |
EMBED_ORDERED
|
grey
|
str
|
Colours for the ordered (Fourier) branch, the disordered (Gaussian) branch, and the tuning-box fill. The two branch colours are the SAME pair the spectral panels use for J and its circulant surrogate, so one colour means one thing across the whole figure. |
EMBED_ORDERED
|
seed
|
int
|
Seeds the disordered example curves (determinism). |
0
|
Source code in ring/plot.py
950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 | |
ring.style¶
ring.style ¶
Matplotlib style configuration and small text-formatting helpers.
Imported by every notebook to set consistent fonts, sizes, and PDF/SVG export
settings for paper figures. Also patches matplotlib.ticker.ScalarFormatter
so tick labels that round to zero never render with a leading minus sign
(e.g. "-0.00" -> "0.00"); see fmt0 for the manual-text-annotation
equivalent.
sweep_cmap ¶
sweep_cmap(kind='slate')
The colormap for an ordered-parameter family of curves. See _SWEEP_HUES.
Source code in ring/style.py
391 392 393 | |
sweep_colors ¶
sweep_colors(n, kind='slate', reverse=False)
n colors, low value -> high value, for an ordered-parameter family.
kind names a RAMP ('ocean', 'ember', 'slate'); see the per-figure table
in this module for which figure uses which. The full [0, 1] span is sampled:
these ramps have no unreadable end, so call sites do not clip.
Source code in ring/style.py
396 397 398 399 400 401 402 403 404 | |
field_cmap ¶
field_cmap(kind='ice')
The colormap for a 2-D scalar field, keyed by quantity. See _FIELD_HUES.
Source code in ring/style.py
407 408 409 | |
attach_cbar ¶
attach_cbar(fig, mappable, ax, side='right', ticks=None, ticklabels=None, label=None)
THE standard colorbar: a thin bar attached to ONE panel (never spanning
several panels). side = 'right'/'left' (vertical) or 'top'/'bottom'
(horizontal). Identical thickness (CBAR_SIZE) and gap everywhere -- use this
instead of a hand-rolled inset so every colorbar in the paper matches.
Source code in ring/style.py
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 | |
add_colorbar ¶
add_colorbar(fig, mappable, ax, orientation='vertical', ticks=None, ticklabels=None, label=None, **kw)
Attach a colorbar with the house thickness/pad to one or more axes.
Standardizes bar thickness across figures. For bars placed in an explicit
inset/added axis, size that axis with CBAR_THICK instead and pass it as
cax to fig.colorbar directly.
Source code in ring/style.py
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 | |
panel_letter ¶
panel_letter(ax, letter, x=-0.02, y=1.02, ha='right', va='bottom', **kw)
Draw a panel letter in the house style: 8 pt bold, upright.
Standardizes size/weight/anchor across all figures (position is still
tunable via x, y in axes-fraction coordinates). For figure-level placement
use fig.text(x, y, letter, fontsize=8, fontweight='bold', ...) directly.
Letters are LOWERCASE, matching the captions and in-text callouts.
Source code in ring/style.py
489 490 491 492 493 494 495 496 497 498 | |
fmt0 ¶
fmt0(value, fmt='{:.2f}')
Format a number, mapping near-zero to positive zero (avoids "-0.00").
Tick labels are handled automatically by the ScalarFormatter patch in this
module; use fmt0 for manually-formatted text annotations inside
ax.text / ax.annotate calls, e.g.
ax.text(x, y, f"$\\kappa = {fmt0(k)}$").
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
float
|
Number to format. |
required |
fmt
|
str
|
Python |
'{:.2f}'
|
Returns:
| Name | Type | Description |
|---|---|---|
s |
str
|
Formatted string with the leading minus stripped if it represents a rounded zero; otherwise the unchanged format output. |
Source code in ring/style.py
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 | |
ring.seed¶
ring.seed ¶
Canonical global RNG seeding for deterministic reproducibility.
set_global_seed ¶
set_global_seed(seed)
Seed numpy, torch, and torch.cuda (if available) for deterministic reproducibility.
Source code in ring/seed.py
5 6 7 8 9 10 11 12 13 14 | |