Skip to content

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 T, dt).

required
dt float

Integration step.

required
T_eval float or None

Period at which to save state into X_save. None disables saving.

required
J (Tensor, shape(N, N))

Recurrent weight matrix.

required
x_init (Tensor, shape(N, N_batch))

Initial state for N_batch parallel trajectories.

required
nonlin callable

Pointwise nonlinearity phi(x).

``fn.unity_erf``
omega_func callable or None

Function t -> omega(t). None disables the omega term.

None
J_prime (Tensor or None, shape(N, N))

Required if omega_func is not None.

None
target_mean float or None

If given, adds a stabilizer const * (target_mean - phi(x).mean(0)) to the dynamics.

None
const float

Stabilizer strength; ignored when target_mean is None.

``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; None when T_eval is None.

finished bool

True if all N_t = int(T/dt) steps completed; False if the early-stop fired.

derivs (ndarray, shape(N_batch), optional)

Final per-batch RMS derivatives. Only returned if return_derivs is True.

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
def 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
    ----------
    T : float
        Total integration time.
    tau : float
        Membrane time constant (same units as ``T``, ``dt``).
    dt : float
        Integration step.
    T_eval : float or None
        Period at which to save state into ``X_save``. ``None`` disables saving.
    J : torch.Tensor, shape (N, N)
        Recurrent weight matrix.
    x_init : torch.Tensor, shape (N, N_batch)
        Initial state for ``N_batch`` parallel trajectories.
    nonlin : callable, default ``fn.unity_erf``
        Pointwise nonlinearity ``phi(x)``.
    omega_func : callable or None
        Function ``t -> omega(t)``. ``None`` disables the omega term.
    J_prime : torch.Tensor or None, shape (N, N)
        Required if ``omega_func`` is not None.
    target_mean : float or None
        If given, adds a stabilizer
        ``const * (target_mean - phi(x).mean(0))`` to the dynamics.
    const : float, default ``np.nan``
        Stabilizer strength; ignored when ``target_mean`` is None.
    return_derivs : bool, default False
        If True, also return per-batch RMS derivatives at exit.
    break_if_stopped : bool, default True
        If True, break out of the loop when all batch trajectories'
        RMS derivatives drop below 1e-100 (numerical zero).
    disable_tqdm : bool, default False
        Disable the tqdm progress bar (emits periodic plain-text status
        prints instead).

    Returns
    -------
    x_final : ndarray, shape (N, N_batch)
        Final state.
    X_save : ndarray or None, shape (N_eval, N, N_batch)
        Periodic snapshots of state; ``None`` when ``T_eval`` is None.
    finished : bool
        True if all ``N_t = int(T/dt)`` steps completed; False if the
        early-stop fired.
    derivs : ndarray, shape (N_batch,), optional
        Final per-batch RMS derivatives. Only returned if
        ``return_derivs`` is True.
    """
    device = J.device
    N_t = int(T / dt)
    N, N_batch = x_init.shape
    x = x_init
    x_prev = x.clone()
    check_deriv_iter = int(10 / dt)
    finished = True
    derivs = torch.zeros(N_batch, device=device)

    save = T_eval is not None
    if save:
        N_eval = int(T / T_eval)
        eval_iter = int(T_eval / dt)
        X_save = np.zeros((N_eval, N, N_batch))
        X_save[0] = x.cpu().numpy()

    if disable_tqdm:
        counter = range(1, N_t)
    else:
        from tqdm import tqdm
        counter = tqdm(range(1, N_t))

    for i in counter:
        r = nonlin(x)
        stabilizer = const * (target_mean - r.mean(0))[None, :] if target_mean is not None else 0.
        dxdt = (1. / tau) * (-x + torch.mm(J, r) + stabilizer)
        if omega_func is not None:
            dxdt += (1. / tau) * tau * omega_func(i * dt) * torch.mm(J_prime, r)
        x += dt * dxdt

        if save and i % eval_iter == 0:
            X_save[i // eval_iter] = x.cpu().numpy()

        if i % check_deriv_iter == 0:
            diff = x - x_prev
            derivs = torch.sqrt((diff**2).mean(0))
            if derivs.max().item() <= 1e-100:
                finished = False
                if break_if_stopped:
                    break
            x_prev = x.clone()

        if disable_tqdm and i % 100000 == 0:
            print(f"t = {i*dt}", flush=True)

    x_final = x.cpu().numpy()
    X_save = X_save if save else None

    if return_derivs:
        return x_final, X_save, finished, derivs.cpu().numpy()
    return x_final, X_save, finished

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 Jhat_n = Ghat_x_n / (Ghat_phi_n + lamda) and Uhat_n = Ghat_x_n / (Ghat_phi_n + lamda)^2.

It has the same PLACE in the formula as the lamda of regression.compute_J, but not the same JOB, which is why the default differs. Here the inversion is exactly singular, because this is the N -> infinity limit and Ghat_phi_n -> 0 as n -> inf, so the constant is a numerical guard against dividing by zero and should be as small as the arithmetic allows. In the finite-N inference lamda is the actual ridge of the loss and does real work against the sampling structure of the empirical (1/N) Phi Phi^T, which is what 1e-8 there is sized for.

Keeping this at 1e-12 matters for the stability sweep, since at low gain Ghat_phi_n becomes comparable to 1e-8 and the guard would start suppressing J for real, moving the phase boundary and leaving cells where the homogeneous solution has no instability timescale at all. Pass the finite-N value explicitly if you are comparing this theory against a specific fit rather than mapping the model.

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
class 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
    ----------
    N_theta : int, default 1000
        Number of angular grid points on the ring.
    scale : float, default 1.5
        Wrapped-Gaussian length scale (in units of Fourier-frequency index).
    g : float, default 2.0
        Gain parameter scaling the nonlinearity.
    lamda : float, default 1e-12
        Regularization entering the mean-field kernels as
        ``Jhat_n = Ghat_x_n / (Ghat_phi_n + lamda)`` and
        ``Uhat_n = Ghat_x_n / (Ghat_phi_n + lamda)^2``.

        It has the same PLACE in the formula as the ``lamda`` of
        ``regression.compute_J``, but not the same JOB, which is why the
        default differs. Here the inversion is exactly singular, because this
        is the ``N -> infinity`` limit and ``Ghat_phi_n -> 0`` as ``n -> inf``,
        so the constant is a numerical guard against dividing by zero and
        should be as small as the arithmetic allows. In the finite-``N``
        inference ``lamda`` is the actual ridge of the loss and does real work
        against the sampling structure of the empirical ``(1/N) Phi Phi^T``,
        which is what ``1e-8`` there is sized for.

        Keeping this at ``1e-12`` matters for the stability sweep, since at
        low gain ``Ghat_phi_n`` becomes comparable to ``1e-8`` and the guard
        would start suppressing ``J`` for real, moving the phase boundary and
        leaving cells where the homogeneous solution has no instability
        timescale at all. Pass the finite-``N`` value explicitly if you are
        comparing this theory against a specific fit rather than mapping the
        model.
    """

    def __init__(self, N_theta=1000, scale=1.5, g=2.0, lamda=1e-12):
        self.N_theta = N_theta
        self.scale = scale
        self.g = g
        self.lamda = lamda
        self.theta = np.arange(N_theta) * 2 * np.pi / N_theta
        self.dtheta = self.theta[1] - self.theta[0]

        self.nonlin = lambda x: 1 + fn.unity_erf(self.g * x)
        self.compute_F_function()
        self.compute_Gamma()
        self.compute_J_and_U()

    def compute_F_function(self):
        """(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/covariance ``C_*``.
        - ``self.dF_dC12``, ``self.dF_dC11``: partial derivatives.
        """
        g = self.g

        def F(C_11, C_22, C_12):
            in_sqrt = ((self.g**2) * C_11 + 2/np.pi) * ((self.g**2) * C_22 + 2/np.pi) - ((self.g**2) * C_12)**2
            in_sqrt = np.clip(in_sqrt, a_min=1e-20, a_max=np.inf)
            t_12 = (2/np.pi) * np.arctan((self.g**2) * C_12 / np.sqrt(in_sqrt))
            return 1 + t_12

        def dF_dC12(C_11, C_22, C_12):
            A = ((g**2)*C_11 + (2/np.pi)) * ((g**2)*C_22 + (2/np.pi))
            B = A - ((g**2)*C_12)**2
            return (g**2) * (2/np.pi) * 1./np.sqrt(B)

        def dF_dC11(C_11, C_22, C_12):
            A = ((g**2)*C_11 + (2/np.pi)) * ((g**2)*C_22 + (2/np.pi))
            B = A - ((g**2)*C_12)**2
            dF_dA = -(2/np.pi) * ((g**2)*C_12 / (2*A)) * 1./np.sqrt(B)
            dA_dC11 = (g**2) * ((g**2)*C_22 + (2/np.pi))
            return dF_dA * dA_dC11

        self.F = F
        self.dF_dC12 = dF_dC12
        self.dF_dC11 = dF_dC11

    def compute_Gamma(self):
        """(internal) Build ``Gamma_x`` (input covariance) and ``Gamma_phi`` (output)."""
        self.Gamma_x, self.Gamma_x_ft = tc.wrapped_gaussian_cov(
            eq_var=1., scale=self.scale, N_theta=self.N_theta)
        self.Gamma_phi = self.F(self.Gamma_x[0], self.Gamma_x[0], self.Gamma_x)
        self.Gamma_phi_ft = np.fft.rfft(self.Gamma_phi, norm='forward').real

    def compute_J_and_U(self):
        """(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.
        """
        self.J_ft = self.Gamma_x_ft / (self.Gamma_phi_ft + self.lamda)
        self.J = np.fft.irfft(self.J_ft, norm='forward')
        self.U_ft = self.Gamma_x_ft / (self.Gamma_phi_ft + self.lamda)**2
        self.U = np.fft.irfft(self.U_ft, norm='forward')

    def rfft_sum(self, x):
        """(internal) Reduce real Fourier coefficients ``x`` to the implied real-space sum."""
        return x[0].real + 2 * x[1:].real.sum()

    def J_m_prod(self, m):
        """(internal) Convolve ``m`` with ``J`` via FFT."""
        m_ft = np.fft.rfft(m, norm='forward')
        return np.fft.irfft(self.J_ft * m_ft, norm='forward')

    def J_deriv_m_hat_prod(self, m_hat):
        """(internal) Convolve ``m_hat`` with the derivative of ``J`` via FFT."""
        N_freq = len(self.J_ft)
        n = np.arange(N_freq)
        J_deriv_ft = 1j * n * self.J_ft
        m_hat_ft = np.fft.rfft(m_hat, norm='forward')
        return np.fft.irfft(J_deriv_ft * m_hat_ft, norm='forward')

    def compute_Q(self, 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.
        """
        m_ft = np.fft.rfft(m, norm='forward')
        m_hat_ft = np.fft.rfft(m_hat, norm='forward')
        N_freq = len(self.U_ft)
        n = np.arange(N_freq)
        U_deriv_ft = 1j * n * self.U_ft
        U_double_deriv_ft = -n**2 * self.U_ft
        t1 = self.rfft_sum(self.U_ft * np.abs(m_ft)**2)
        t2 = -self.rfft_sum(U_double_deriv_ft * np.abs(m_hat_ft)**2)
        t3 = 2 * self.rfft_sum(U_deriv_ft * m_hat_ft.conj() * m_ft)
        return t1 + t2 + t3

    def simulate(self, T, dt, T_eval, omega_func=None, m_init=None,
                 use_tqdm=True, tau=1., exclude_Q=False):
        """Euler-integrate the DMFT equations for ``m`` and ``m_hat``.

        Parameters
        ----------
        T : float
            Total integration time.
        dt : float
            Integration step.
        T_eval : float
            Save state every ``T_eval`` time units.
        omega_func : callable or None
            Time-varying drift ``t -> omega(t)``. ``None`` -> zero drift.
        m_init : ndarray, shape (N_theta,), optional
            Initial order parameter. Defaults to ``self.Gamma_phi``.
        use_tqdm : bool, default True
            Show progress bar.
        tau : float, default 1.
            Membrane time constant.
        exclude_Q : bool, default False
            If True, replace ``Q`` with ``Gamma_x[0]`` (no fluctuations).

        Returns
        -------
        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 ``G`` driving the dynamics.
        """
        N_t = int(T / dt)
        N_eval = int(T / T_eval)
        eval_step = int(T_eval / dt)
        t = np.arange(N_eval) * T_eval

        omega = np.zeros(N_t) if omega_func is None else omega_func(np.arange(N_t) * dt)

        m = np.zeros((N_eval, self.N_theta))
        m_hat = np.zeros((N_eval, self.N_theta))
        g_dyn = np.zeros((N_eval, self.N_theta))

        m_current = m_init if m_init is not None else self.Gamma_phi
        m_hat_current = tau * omega[0] * m_current

        m[0] = m_current
        m_hat[0] = m_hat_current
        g_dyn[0] = m_current

        iterator = tqdm(range(1, N_t)) if use_tqdm else range(1, N_t)

        eval_index = 1
        for i in iterator:
            H = self.J_m_prod(m_current) - self.J_deriv_m_hat_prod(m_hat_current)
            Q = self.compute_Q(m_current, m_hat_current) if not exclude_Q else self.Gamma_x[0]
            G = self.F(self.Gamma_x[0], Q, H)

            m_deriv = (-m_current + G) / tau
            m_hat_deriv = (-m_hat_current + tau * omega[i] * G) / tau

            m_current += dt * m_deriv
            m_hat_current += dt * m_hat_deriv

            if i % eval_step == 0 and eval_index < N_eval:
                m[eval_index] = m_current
                m_hat[eval_index] = m_hat_current
                g_dyn[eval_index] = G
                eval_index += 1

        return t, m, m_hat, g_dyn

    def compute_bump_jacobian(self, exclude_Q=False):
        """Compute the Jacobian and eigenvalues at the bump solution.

        Parameters
        ----------
        exclude_Q : bool, default False
            If True, omit the Q-fluctuation contribution.

        Returns
        -------
        jac : ndarray, shape (N_theta, N_theta)
            Jacobian matrix at the bump.
        eigenvals : ndarray, shape (N_theta,)
            Eigenvalues sorted by descending real part.
        """
        G1 = self.dF_dC12(self.Gamma_x[0], self.Gamma_x[0], self.Gamma_x)
        G2 = self.dF_dC11(self.Gamma_x[0], self.Gamma_x[0], self.Gamma_x)

        T1 = G1[:, None] * circulant(self.J)
        T2 = G2[:, None] * 2 * self.J[None, :] if not exclude_Q else 0.

        jac = -np.eye(self.N_theta) + (T1 + T2) / self.N_theta
        eigenvals = np.linalg.eigvals(jac)
        eigenvals = eigenvals[np.argsort(eigenvals.real)[::-1]]
        return jac, eigenvals

    def find_homogeneous_solution(self, tol=1e-14, max_iter=2000, exclude_Q=False):
        """Locate the homogeneous (theta-independent) fixed point ``m0`` via bisection.

        Parameters
        ----------
        tol : float, default 1e-14
            Convergence tolerance on the residual.
        max_iter : int, default 2000
            Maximum bisection iterations.
        exclude_Q : bool, default False
            If True, replace Q with Gamma_x[0] in the fixed-point equation.

        Returns
        -------
        m0 : float
            Homogeneous fixed-point value.

        Raises
        ------
        ValueError
            If bisection fails to converge within ``max_iter`` iterations.
        """
        def compute_err(m0):
            Q_homo = self.U.mean() * m0**2 if not exclude_Q else self.Gamma_x[0]
            h_homo = self.J.mean() * m0
            return -m0 + self.F(Q_homo, self.Gamma_x[0], h_homo)

        # Bisection bounds; the solution is typically close to 1.
        left, right = 1., 10.
        for _ in range(max_iter):
            m0 = (left + right) / 2
            err = compute_err(m0)
            if abs(err) < tol:
                return m0
            if err > 0:
                left = m0
            else:
                right = m0
        raise ValueError(
            f"Failed to converge within {max_iter} iterations, g = {self.g}, scale = {self.scale}")

    def compute_homogeneous_jacobian(self, m0=None, exclude_Q=False, exclude_Q_for_m0=False):
        """Compute the Jacobian and eigenvalues at the homogeneous fixed point.

        Parameters
        ----------
        m0 : float, optional
            Homogeneous solution value. Computed via ``find_homogeneous_solution``
            if not provided.
        exclude_Q : bool, default False
            If True, omit the Q-fluctuation contribution.
        exclude_Q_for_m0 : bool, default False
            If True (and ``m0`` is computed here), pass ``exclude_Q=True`` to
            ``find_homogeneous_solution``.

        Returns
        -------
        jac : ndarray, shape (N_theta, N_theta)
            Jacobian matrix at the homogeneous solution.
        eigenvals : ndarray, shape (N_theta,)
            Eigenvalues sorted by descending real part.
        """
        if m0 is None:
            m0 = self.find_homogeneous_solution(exclude_Q=exclude_Q_for_m0)

        Q_homo = self.U.mean() * m0**2 if not exclude_Q else self.Gamma_x[0]
        h_homo = self.J.mean() * m0

        t1 = self.dF_dC12(Q_homo, self.Gamma_x[0], h_homo)
        t3 = self.dF_dC11(Q_homo, self.Gamma_x[0], h_homo)
        t4 = 2 * self.U.mean() * m0
        Q_term = t3 * t4 if not exclude_Q else 0.

        jac = -np.eye(self.N_theta) + (t1 * circulant(self.J) + Q_term) / self.N_theta
        eigenvals = np.linalg.eigvals(jac)
        eigenvals = eigenvals[np.argsort(eigenvals.real)[::-1]]
        return jac, eigenvals

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/covariance C_*.
  • 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
def compute_F_function(self):
    """(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/covariance ``C_*``.
    - ``self.dF_dC12``, ``self.dF_dC11``: partial derivatives.
    """
    g = self.g

    def F(C_11, C_22, C_12):
        in_sqrt = ((self.g**2) * C_11 + 2/np.pi) * ((self.g**2) * C_22 + 2/np.pi) - ((self.g**2) * C_12)**2
        in_sqrt = np.clip(in_sqrt, a_min=1e-20, a_max=np.inf)
        t_12 = (2/np.pi) * np.arctan((self.g**2) * C_12 / np.sqrt(in_sqrt))
        return 1 + t_12

    def dF_dC12(C_11, C_22, C_12):
        A = ((g**2)*C_11 + (2/np.pi)) * ((g**2)*C_22 + (2/np.pi))
        B = A - ((g**2)*C_12)**2
        return (g**2) * (2/np.pi) * 1./np.sqrt(B)

    def dF_dC11(C_11, C_22, C_12):
        A = ((g**2)*C_11 + (2/np.pi)) * ((g**2)*C_22 + (2/np.pi))
        B = A - ((g**2)*C_12)**2
        dF_dA = -(2/np.pi) * ((g**2)*C_12 / (2*A)) * 1./np.sqrt(B)
        dA_dC11 = (g**2) * ((g**2)*C_22 + (2/np.pi))
        return dF_dA * dA_dC11

    self.F = F
    self.dF_dC12 = dF_dC12
    self.dF_dC11 = dF_dC11

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
def compute_Gamma(self):
    """(internal) Build ``Gamma_x`` (input covariance) and ``Gamma_phi`` (output)."""
    self.Gamma_x, self.Gamma_x_ft = tc.wrapped_gaussian_cov(
        eq_var=1., scale=self.scale, N_theta=self.N_theta)
    self.Gamma_phi = self.F(self.Gamma_x[0], self.Gamma_x[0], self.Gamma_x)
    self.Gamma_phi_ft = np.fft.rfft(self.Gamma_phi, norm='forward').real

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
def compute_J_and_U(self):
    """(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.
    """
    self.J_ft = self.Gamma_x_ft / (self.Gamma_phi_ft + self.lamda)
    self.J = np.fft.irfft(self.J_ft, norm='forward')
    self.U_ft = self.Gamma_x_ft / (self.Gamma_phi_ft + self.lamda)**2
    self.U = np.fft.irfft(self.U_ft, norm='forward')

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
def rfft_sum(self, x):
    """(internal) Reduce real Fourier coefficients ``x`` to the implied real-space sum."""
    return x[0].real + 2 * x[1:].real.sum()

J_m_prod

J_m_prod(m)

(internal) Convolve m with J via FFT.

Source code in ring/dmft.py
136
137
138
139
def J_m_prod(self, m):
    """(internal) Convolve ``m`` with ``J`` via FFT."""
    m_ft = np.fft.rfft(m, norm='forward')
    return np.fft.irfft(self.J_ft * m_ft, norm='forward')

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
def J_deriv_m_hat_prod(self, m_hat):
    """(internal) Convolve ``m_hat`` with the derivative of ``J`` via FFT."""
    N_freq = len(self.J_ft)
    n = np.arange(N_freq)
    J_deriv_ft = 1j * n * self.J_ft
    m_hat_ft = np.fft.rfft(m_hat, norm='forward')
    return np.fft.irfft(J_deriv_ft * m_hat_ft, norm='forward')

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
def compute_Q(self, 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.
    """
    m_ft = np.fft.rfft(m, norm='forward')
    m_hat_ft = np.fft.rfft(m_hat, norm='forward')
    N_freq = len(self.U_ft)
    n = np.arange(N_freq)
    U_deriv_ft = 1j * n * self.U_ft
    U_double_deriv_ft = -n**2 * self.U_ft
    t1 = self.rfft_sum(self.U_ft * np.abs(m_ft)**2)
    t2 = -self.rfft_sum(U_double_deriv_ft * np.abs(m_hat_ft)**2)
    t3 = 2 * self.rfft_sum(U_deriv_ft * m_hat_ft.conj() * m_ft)
    return t1 + t2 + t3

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 T_eval time units.

required
omega_func callable or None

Time-varying drift t -> omega(t). None -> zero drift.

None
m_init (ndarray, shape(N_theta))

Initial order parameter. Defaults to self.Gamma_phi.

None
use_tqdm bool

Show progress bar.

True
tau float

Membrane time constant.

1.
exclude_Q bool

If True, replace Q with Gamma_x[0] (no fluctuations).

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 G driving the dynamics.

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
def simulate(self, T, dt, T_eval, omega_func=None, m_init=None,
             use_tqdm=True, tau=1., exclude_Q=False):
    """Euler-integrate the DMFT equations for ``m`` and ``m_hat``.

    Parameters
    ----------
    T : float
        Total integration time.
    dt : float
        Integration step.
    T_eval : float
        Save state every ``T_eval`` time units.
    omega_func : callable or None
        Time-varying drift ``t -> omega(t)``. ``None`` -> zero drift.
    m_init : ndarray, shape (N_theta,), optional
        Initial order parameter. Defaults to ``self.Gamma_phi``.
    use_tqdm : bool, default True
        Show progress bar.
    tau : float, default 1.
        Membrane time constant.
    exclude_Q : bool, default False
        If True, replace ``Q`` with ``Gamma_x[0]`` (no fluctuations).

    Returns
    -------
    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 ``G`` driving the dynamics.
    """
    N_t = int(T / dt)
    N_eval = int(T / T_eval)
    eval_step = int(T_eval / dt)
    t = np.arange(N_eval) * T_eval

    omega = np.zeros(N_t) if omega_func is None else omega_func(np.arange(N_t) * dt)

    m = np.zeros((N_eval, self.N_theta))
    m_hat = np.zeros((N_eval, self.N_theta))
    g_dyn = np.zeros((N_eval, self.N_theta))

    m_current = m_init if m_init is not None else self.Gamma_phi
    m_hat_current = tau * omega[0] * m_current

    m[0] = m_current
    m_hat[0] = m_hat_current
    g_dyn[0] = m_current

    iterator = tqdm(range(1, N_t)) if use_tqdm else range(1, N_t)

    eval_index = 1
    for i in iterator:
        H = self.J_m_prod(m_current) - self.J_deriv_m_hat_prod(m_hat_current)
        Q = self.compute_Q(m_current, m_hat_current) if not exclude_Q else self.Gamma_x[0]
        G = self.F(self.Gamma_x[0], Q, H)

        m_deriv = (-m_current + G) / tau
        m_hat_deriv = (-m_hat_current + tau * omega[i] * G) / tau

        m_current += dt * m_deriv
        m_hat_current += dt * m_hat_deriv

        if i % eval_step == 0 and eval_index < N_eval:
            m[eval_index] = m_current
            m_hat[eval_index] = m_hat_current
            g_dyn[eval_index] = G
            eval_index += 1

    return t, m, m_hat, g_dyn

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
def compute_bump_jacobian(self, exclude_Q=False):
    """Compute the Jacobian and eigenvalues at the bump solution.

    Parameters
    ----------
    exclude_Q : bool, default False
        If True, omit the Q-fluctuation contribution.

    Returns
    -------
    jac : ndarray, shape (N_theta, N_theta)
        Jacobian matrix at the bump.
    eigenvals : ndarray, shape (N_theta,)
        Eigenvalues sorted by descending real part.
    """
    G1 = self.dF_dC12(self.Gamma_x[0], self.Gamma_x[0], self.Gamma_x)
    G2 = self.dF_dC11(self.Gamma_x[0], self.Gamma_x[0], self.Gamma_x)

    T1 = G1[:, None] * circulant(self.J)
    T2 = G2[:, None] * 2 * self.J[None, :] if not exclude_Q else 0.

    jac = -np.eye(self.N_theta) + (T1 + T2) / self.N_theta
    eigenvals = np.linalg.eigvals(jac)
    eigenvals = eigenvals[np.argsort(eigenvals.real)[::-1]]
    return jac, eigenvals

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 max_iter iterations.

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
def find_homogeneous_solution(self, tol=1e-14, max_iter=2000, exclude_Q=False):
    """Locate the homogeneous (theta-independent) fixed point ``m0`` via bisection.

    Parameters
    ----------
    tol : float, default 1e-14
        Convergence tolerance on the residual.
    max_iter : int, default 2000
        Maximum bisection iterations.
    exclude_Q : bool, default False
        If True, replace Q with Gamma_x[0] in the fixed-point equation.

    Returns
    -------
    m0 : float
        Homogeneous fixed-point value.

    Raises
    ------
    ValueError
        If bisection fails to converge within ``max_iter`` iterations.
    """
    def compute_err(m0):
        Q_homo = self.U.mean() * m0**2 if not exclude_Q else self.Gamma_x[0]
        h_homo = self.J.mean() * m0
        return -m0 + self.F(Q_homo, self.Gamma_x[0], h_homo)

    # Bisection bounds; the solution is typically close to 1.
    left, right = 1., 10.
    for _ in range(max_iter):
        m0 = (left + right) / 2
        err = compute_err(m0)
        if abs(err) < tol:
            return m0
        if err > 0:
            left = m0
        else:
            right = m0
    raise ValueError(
        f"Failed to converge within {max_iter} iterations, g = {self.g}, scale = {self.scale}")

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 find_homogeneous_solution if not provided.

None
exclude_Q bool

If True, omit the Q-fluctuation contribution.

False
exclude_Q_for_m0 bool

If True (and m0 is computed here), pass exclude_Q=True to find_homogeneous_solution.

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
def compute_homogeneous_jacobian(self, m0=None, exclude_Q=False, exclude_Q_for_m0=False):
    """Compute the Jacobian and eigenvalues at the homogeneous fixed point.

    Parameters
    ----------
    m0 : float, optional
        Homogeneous solution value. Computed via ``find_homogeneous_solution``
        if not provided.
    exclude_Q : bool, default False
        If True, omit the Q-fluctuation contribution.
    exclude_Q_for_m0 : bool, default False
        If True (and ``m0`` is computed here), pass ``exclude_Q=True`` to
        ``find_homogeneous_solution``.

    Returns
    -------
    jac : ndarray, shape (N_theta, N_theta)
        Jacobian matrix at the homogeneous solution.
    eigenvals : ndarray, shape (N_theta,)
        Eigenvalues sorted by descending real part.
    """
    if m0 is None:
        m0 = self.find_homogeneous_solution(exclude_Q=exclude_Q_for_m0)

    Q_homo = self.U.mean() * m0**2 if not exclude_Q else self.Gamma_x[0]
    h_homo = self.J.mean() * m0

    t1 = self.dF_dC12(Q_homo, self.Gamma_x[0], h_homo)
    t3 = self.dF_dC11(Q_homo, self.Gamma_x[0], h_homo)
    t4 = 2 * self.U.mean() * m0
    Q_term = t3 * t4 if not exclude_Q else 0.

    jac = -np.eye(self.N_theta) + (t1 * circulant(self.J) + Q_term) / self.N_theta
    eigenvals = np.linalg.eigvals(jac)
    eigenvals = eigenvals[np.argsort(eigenvals.real)[::-1]]
    return jac, eigenvals

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' or 'torch'. Torch ops use the default torch device.

'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
def 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
    ----------
    eq_var : float
        Equilibrium variance.
    scale : float
        Gaussian length scale (in units of Fourier-frequency index).
    N_theta : int
        Number of angular grid points.
    backend : str, default 'numpy'
        ``'numpy'`` or ``'torch'``. Torch ops use the default torch device.

    Returns
    -------
    Gamma : ndarray or torch.Tensor, shape (N_theta,)
        Real-space wraparound covariance.
    Gamma_ft : ndarray or torch.Tensor, shape (N_theta // 2 + 1,)
        Fourier-space (real) covariance.
    """
    N_freq = N_theta // 2 + 1
    if backend == 'numpy':
        freq_range = np.arange(N_freq)
        Gamma_ft = (eq_var / np.sqrt(2 * np.pi) / scale) * np.exp(-freq_range**2 / (2 * scale**2))
        Gamma = np.fft.irfft(Gamma_ft, norm='forward')
    else:  # torch
        freq_range = torch.arange(N_freq)
        Gamma_ft = (eq_var / np.sqrt(2 * np.pi) / scale) * torch.exp(-freq_range**2 / (2 * scale**2))
        Gamma = torch.fft.irfft(Gamma_ft, norm='forward')
    return Gamma, Gamma_ft

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). N_theta is inferred as 2 * (N_freq - 1).

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
def 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
    ----------
    N : int
        Number of curves to sample.
    Gamma_ft : ndarray, shape (N_freq,)
        Fourier-space covariance spectrum (real). ``N_theta`` is inferred
        as ``2 * (N_freq - 1)``.
    cutoff : int, optional
        If given, zero out spectrum beyond this index (high-frequency cutoff).
        Default uses all frequencies.

    Returns
    -------
    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.
    """
    N_freq = len(Gamma_ft)
    N_theta = (N_freq - 1) * 2
    if cutoff is None:
        cutoff = N_freq
    X_ft = np.zeros((N_freq, N), dtype=complex)
    X_ft[:cutoff, :] = (np.random.randn(cutoff, N) + 1j * np.random.randn(cutoff, N)) / np.sqrt(2.)
    X_ft[0, :] = X_ft[0, :].real * np.sqrt(2.)
    X_ft *= np.sqrt(np.clip(Gamma_ft[:, None], a_min=0, a_max=np.inf))
    X = np.fft.irfft(X_ft, axis=0, norm='forward')
    return X

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 (sigma).

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
def 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
    ----------
    N_samples : int
        Number of tuning curves to sample.
    N_theta : int
        Number of angular grid points.
    scale : float
        Wraparound-Gaussian Fourier decay scale (``sigma``).
    beta : float
        Response sharpness of the nonlinearity.

    Returns
    -------
    X : ndarray, shape (N_theta, N_samples)
        Input-current tuning curves.
    Phi : ndarray, shape (N_theta, N_samples)
        Firing-rate tuning curves.
    """
    _, Gamma_x_ft = wrapped_gaussian_cov(eq_var=1., scale=scale, N_theta=N_theta)
    X = sample_tcs(N=N_samples, Gamma_ft=Gamma_x_ft)
    Phi = fn.nonlin_idealized(X, beta=beta)
    return X, Phi

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. fname is the absolute path to the NWB file; subject_id is the trailing subject identifier from the directory name; has_optogenetics is True if the session is the +ogen.nwb variant.

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
def get_session_info():
    """Enumerate NWB sessions in ``DATA_DIR``.

    Returns
    -------
    sessions : list of (fname, subject_id, has_optogenetics) tuples
        Sorted by filename. ``fname`` is the absolute path to the NWB
        file; ``subject_id`` is the trailing subject identifier from the
        directory name; ``has_optogenetics`` is True if the session is
        the ``+ogen.nwb`` variant.
    """
    if not os.path.isdir(DATA_DIR):
        raise FileNotFoundError(
            f"Raw Peyrache sessions not found at {DATA_DIR}.\n"
            "These are the ~52 GB NWB recordings from DANDI Dandiset 000939 "
            "(https://dandiarchive.org/dandiset/000939), which are not in the repository.\n"
            "Download them and set RING_DATA_DIR to the directory holding the sub-* "
            "session folders.\n"
            "Reproducing the paper's figures does not require them; the cached tuning "
            "curves in data/mouse_data/tc_data.npz are enough."
        )
    session_info = []
    for dirname in os.listdir(DATA_DIR):
        path = os.path.join(DATA_DIR, dirname)
        if os.path.isfile(path):
            continue
        subj = dirname.split("-")[-1]
        fname = f"sub-{subj}_behavior+ecephys"
        full_path_ogen = os.path.join(DATA_DIR, dirname, fname + "+ogen.nwb")
        full_path_standard = os.path.join(DATA_DIR, dirname, fname + ".nwb")
        if os.path.exists(full_path_ogen):
            session_info.append((full_path_ogen, subj, True))
        elif os.path.exists(full_path_standard):
            session_info.append((full_path_standard, subj, False))
    return sorted(session_info)

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 hd_idx entries are unconditionally masked out.

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
def 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
    ----------
    N_theta : int
        Number of angular bins on the ring.
    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).
    spike_time_idx : ndarray, shape (N_spikes,)
        Time-bin indices at which spikes occurred.
    mask : ndarray of bool or None, shape (N_bins,)
        Optional per-time-bin mask (e.g. cross-validation fold). Negative
        ``hd_idx`` entries are unconditionally masked out.

    Returns
    -------
    angular_occupancy_counts : ndarray, shape (N_theta,)
    angular_spike_counts : ndarray, shape (N_theta,)
    """
    N_bins = len(hd_idx)
    mask = np.ones(N_bins, dtype=bool) if mask is None else mask.copy()
    mask[hd_idx < 0] = False

    masked_spike_time_idx = spike_time_idx[np.in1d(spike_time_idx, np.arange(N_bins)[mask])]
    angular_occupancy_counts = np.zeros(N_theta)
    angular_spike_counts = np.zeros(N_theta)

    unique_hd_idx, hd_idx_counts = np.unique(hd_idx[mask], return_counts=True)
    angular_occupancy_counts[unique_hd_idx] = hd_idx_counts

    hd_idxs_with_spikes = hd_idx[masked_spike_time_idx]
    unique_hd_idx_with_spikes, hd_idx_with_spikes_counts = np.unique(hd_idxs_with_spikes, return_counts=True)
    angular_spike_counts[unique_hd_idx_with_spikes] = hd_idx_with_spikes_counts

    return angular_occupancy_counts, angular_spike_counts

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
def 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
    ----------
    N_theta : int
        Number of angular bins on the ring.
    hd_idx : ndarray, shape (N_bins,)
        Per-time-bin angular bin index; negative entries flag invalid bins.
    spike_time_idx : ndarray, shape (N_spikes,)
        Time-bin indices at which spikes occurred.
    mask : ndarray of bool or None, shape (N_bins,)
        Optional per-time-bin mask (e.g. cross-validation fold).

    Returns
    -------
    tc : ndarray, shape (N_theta,)
        Firing-rate tuning curve (Hz).
    """
    aoc, asc = compute_angular_occupancy_and_spike_counts(N_theta, hd_idx, spike_time_idx, mask)
    tc = asc / (aoc * DATA_DT)
    tc[tc == 0.] = tc.mean() * 1e-3
    return tc

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
def compute_poisson_ll(tuning_curve, hd_idx, temporal_spike_counts, mask=None):
    """Poisson log-likelihood of observed spike counts given a tuning curve.

    Parameters
    ----------
    tuning_curve : ndarray, shape (N_theta,)
        Firing-rate tuning curve (Hz).
    hd_idx : ndarray, shape (N_bins,)
        Per-time-bin angular bin index; negatives are masked.
    temporal_spike_counts : ndarray, shape (N_bins,)
        Spike count per time bin.
    mask : ndarray of bool or None, shape (N_bins,)
        Optional cross-validation mask.

    Returns
    -------
    ll : float
        Summed log-pmf across the masked bins.
    """
    N_bins = len(hd_idx)
    mask = np.ones(N_bins, dtype=bool) if mask is None else mask.copy()
    mask[hd_idx < 0] = False
    poisson_rates = tuning_curve[hd_idx[mask]] * DATA_DT
    poisson_observations = temporal_spike_counts[mask]
    return poisson.logpmf(k=poisson_observations, mu=poisson_rates).sum()

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 2*K alternating chunks.

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
def 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
    ----------
    N_bins : int
        Total number of time bins.
    K : int
        Number of "True" chunks (and number of "False" chunks); total
        ``2*K`` alternating chunks.

    Returns
    -------
    mask : ndarray of bool, shape (N_bins,)
    """
    if K <= 0 or N_bins <= 0:
        return np.array([])
    chunk_size = N_bins // (2 * K)
    remainder = N_bins % (2 * K)
    mask = np.zeros(N_bins, dtype=bool)
    current_value = True
    start_index = 0
    for _ in range(2 * K):
        this_chunk_size = chunk_size + (1 if remainder > 0 else 0)
        remainder -= 1
        mask[start_index:start_index + this_chunk_size] = current_value
        start_index += this_chunk_size
        current_value = not current_value
    return mask

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 behavior/CompassDirection/head-direction and units/spike_times to be present, plus an epochs table with a wake_square tag.

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
def 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
    ----------
    nwbfile : pynwb NWBFile (already-opened)
        Session to process. Expects ``behavior/CompassDirection/head-direction``
        and ``units/spike_times`` to be present, plus an ``epochs`` table
        with a ``wake_square`` tag.
    N_theta : int, default 100
        Number of angular bins.
    sigma_vals : ndarray, default ``np.logspace(-1, 2, 100)``
        Gaussian smoothing widths (in bin units) to sweep.
    K : int, default 4
        Number of alternating-chunk cross-validation folds.

    Returns
    -------
    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.
    """
    # Behavioral epoch for the "wake_square" task.
    epoch_df = nwbfile.epochs.to_dataframe()
    ti_nominal, tf_nominal = epoch_df[epoch_df["tags"] == "wake_square"][["start_time", "stop_time"]].values[0]

    # Head-direction track.
    hd_spatial_series = nwbfile.processing["behavior"].data_interfaces["CompassDirection"].spatial_series["head-direction"]
    hd_full = hd_spatial_series.data[:]
    t_full = hd_spatial_series.timestamps[:]

    ti_idx = np.argmin((ti_nominal - t_full)**2)
    tf_idx = np.argmin((tf_nominal - t_full)**2)
    N_bins = tf_idx - ti_idx
    ti, tf = t_full[[ti_idx, tf_idx]]

    hd = hd_full[ti_idx:tf_idx].copy()
    d_theta = 2 * np.pi / N_theta
    hd[np.isnan(hd)] = -1
    hd_idx = np.floor(hd / d_theta).astype(int)

    mask = generate_alternating_mask(N_bins, K=K)
    masks = (mask, ~mask)

    num_units = len(nwbfile.units)
    opt_tcs = np.zeros((num_units, 2, N_theta))
    opt_sigmas = np.zeros((num_units, 2))
    plain_tcs = np.zeros((num_units, 2, N_theta))

    for unit_idx in tqdm(range(num_units), desc="Computing tuning curves"):
        spike_times = nwbfile.units["spike_times"][unit_idx][:]
        within_epoch_spike_times = spike_times[(spike_times >= ti) & (spike_times < tf)]
        spike_time_idx = np.floor((within_epoch_spike_times - ti) / DATA_DT).astype(int)

        temporal_spike_counts = np.zeros(N_bins)
        unique_spike_time_idx, spike_time_idx_counts = np.unique(spike_time_idx, return_counts=True)
        temporal_spike_counts[unique_spike_time_idx] = spike_time_idx_counts

        for mask_idx, mask in enumerate(masks):
            ll_vals = np.zeros(len(sigma_vals))
            smoothed_tcs = np.zeros((len(sigma_vals), N_theta))
            tuning_curve = compute_tuning_curve(N_theta, hd_idx, spike_time_idx, mask=mask)
            plain_tcs[unit_idx, mask_idx] = tuning_curve

            for i in range(len(sigma_vals)):
                smoothed_tcs[i] = gaussian_filter1d(tuning_curve, sigma=sigma_vals[i], mode='wrap')
                ll_vals[i] = compute_poisson_ll(smoothed_tcs[i], hd_idx, temporal_spike_counts, mask=~mask)

            opt_idx = ll_vals.argmax()
            opt_tcs[unit_idx, mask_idx] = smoothed_tcs[opt_idx]
            opt_sigmas[unit_idx, mask_idx] = sigma_vals[opt_idx]

    return plain_tcs, opt_tcs, opt_sigmas

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
def 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.
    """
    session_info = get_session_info()
    all_hd_masks, all_exc_masks, all_fs_masks = [], [], []
    all_plain_tcs, all_opt_tcs, all_opt_sigmas = [], [], []
    all_num_units = []
    all_mouse_nums, all_mouse_names, all_has_ogen = [], [], []

    for session_idx, (fname, subject_id, has_ogen) in enumerate(session_info):
        print(f"Processing session {session_idx + 1}/{len(session_info)}: {subject_id}")
        io = NWBHDF5IO(fname, mode="r")
        nwbfile = io.read()

        num_units = len(nwbfile.units)
        hd_mask = nwbfile.units["is_head_direction"][:].astype(bool)
        exc_mask = nwbfile.units["is_excitatory"][:].astype(bool)
        fs_mask = nwbfile.units["is_fast_spiking"][:].astype(bool)

        plain_tcs, opt_tcs, opt_sigmas = process_file(nwbfile)

        all_hd_masks.append(hd_mask)
        all_exc_masks.append(exc_mask)
        all_fs_masks.append(fs_mask)
        all_plain_tcs.append(plain_tcs)
        all_opt_tcs.append(opt_tcs)
        all_opt_sigmas.append(opt_sigmas)
        all_num_units.append(num_units)
        all_mouse_nums.extend([session_idx] * num_units)
        all_mouse_names.extend([subject_id] * num_units)
        all_has_ogen.extend([has_ogen] * num_units)

        io.close()

    np.savez(
        os.path.join(OUTPUT_DIR, "tc_data.npz"),
        hd_mask=np.concatenate(all_hd_masks),
        exc_mask=np.concatenate(all_exc_masks),
        fs_mask=np.concatenate(all_fs_masks),
        plain_tcs=np.concatenate(all_plain_tcs, axis=0),
        opt_tcs=np.concatenate(all_opt_tcs, axis=0),
        opt_sigmas=np.concatenate(all_opt_sigmas, axis=0),
        fnames=[info[0] for info in session_info],
        unit_counts=np.array(all_num_units),
        mouse_nums=np.array(all_mouse_nums),
        mouse_names=np.array(all_mouse_names),
        has_ogen=np.array(all_has_ogen),
    )

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
def load_tuning_curve_data():
    """(internal) Load tuning curves from ``TC_DATA_PATH``, dropping all-zero rows.

    Returns
    -------
    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.
    """
    data = np.load(TC_DATA_PATH, "r")
    tcs = data['opt_tcs'].mean(1)
    nz_mask = ~np.all(tcs == 0, axis=1)
    tcs = tcs[nz_mask]
    plain_tcs = data['plain_tcs'][nz_mask]
    hd_mask = data['hd_mask'][nz_mask]
    fs_mask = data['fs_mask'][nz_mask]
    exc_mask = data['exc_mask'][nz_mask]
    num_units = np.sum(nz_mask)
    return tcs, plain_tcs, hd_mask, fs_mask, exc_mask, num_units

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
def prepare_Phi(tcs, hd_mask):
    """(internal) Select HD-classified units, mean-normalize, and transpose to (N_theta, N)."""
    Phi = tcs[hd_mask].copy()
    scalings = 1. / Phi.mean(axis=1)
    Phi = Phi * scalings[:, None]
    return Phi.T  # shape = (N_theta, N)

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
def load_data_Phi():
    """Load ``Phi`` for the HD-classified subset of mouse units.

    Returns
    -------
    Phi : ndarray, shape (N_theta, N)
        Mean-normalized tuning curves transposed to (N_theta, N).
    """
    tcs, _, hd_mask, _, _, _ = load_tuning_curve_data()
    return prepare_Phi(tcs, hd_mask)

nonlin

nonlin(x, beta=2)

Softplus nonlinearity. Thin wrapper around fn.softplus(x, beta).

Source code in ring/data_driven.py
79
80
81
def nonlin(x, beta=2):
    """Softplus nonlinearity. Thin wrapper around ``fn.softplus(x, beta)``."""
    return fn.softplus(x, beta=beta)

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
def inv_nonlin(phi, beta=2):
    """(internal) Inverse softplus: ``log(exp(beta * phi) - 1) / beta``.

    Supports numpy or torch input; raises TypeError otherwise.
    """
    if isinstance(phi, np.ndarray):
        return np.log(np.exp(beta * phi) - 1) / beta
    elif isinstance(phi, torch.Tensor):
        return torch.log(torch.exp(beta * phi) - 1) / beta
    else:
        raise TypeError("Input must be either a NumPy array or a PyTorch tensor")

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
def resample_curves_fft(X, N_new):
    """(internal) FFT-based resampling of curves from ``N_original`` to ``N_new`` points.

    Parameters
    ----------
    X : ndarray, shape (N_original, N_curves)
    N_new : int

    Returns
    -------
    X_resampled : ndarray, shape (N_new, N_curves)
    """
    N_original, N_curves = X.shape
    X_fft = np.fft.rfft(X, axis=0)
    new_fft = np.zeros((N_new // 2 + 1, N_curves), dtype=complex)
    new_fft[:min(X_fft.shape[0], new_fft.shape[0])] = X_fft[:min(X_fft.shape[0], new_fft.shape[0])]
    new_fft *= N_new / N_original
    return np.fft.irfft(new_fft, n=N_new, axis=0)

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
def 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
    ----------
    Phi : ndarray, shape (N_theta_orig, N)
    N_theta : int, default 500
        Output resolution after FFT resampling.
    sigma : float, default 2
        Gaussian smoothing width in bin units.
    normalize : bool, default True
        If True, apply Sinkhorn-iterate normalization.
    normalize_across_neurons : bool, default True
        If True, normalize across both axes; otherwise only across theta.

    Returns
    -------
    X_smooth_norm_resampled : ndarray, shape (N_theta, N)
    Phi_smooth_norm_resampled : ndarray, shape (N_theta, N)
    """
    X = inv_nonlin(Phi, beta=2.)
    X_smooth = gaussian_filter1d(X, axis=0, sigma=sigma, mode='wrap')
    Phi_smooth = nonlin(X_smooth, beta=2.)
    Phi_smooth_norm = Phi_smooth.copy()
    if normalize:
        if normalize_across_neurons:
            _sinkhorn_normalize(Phi_smooth_norm)
        else:
            Phi_smooth_norm /= Phi_smooth_norm.mean(0, keepdims=True)
        X_smooth_norm = inv_nonlin(Phi_smooth_norm, beta=2.)
    else:
        X_smooth_norm = X_smooth
    X_smooth_norm_resampled = resample_curves_fft(X_smooth_norm, N_theta)
    Phi_smooth_norm_resampled = nonlin(X_smooth_norm_resampled, beta=2.)
    return X_smooth_norm_resampled, Phi_smooth_norm_resampled

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 N-normalized convention of regression.compute_J (see its Notes).

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
def compute_weights(X, Phi, lamda=1e-8):
    """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
    ----------
    X : ndarray, shape (N_theta, N)
        Preactivation tuning curves.
    Phi : ndarray, shape (N_theta, N)
        Output (post-nonlinearity) tuning curves.
    lamda : float, default 1e-8
        Ridge regularization strength, in the ``N``-normalized convention of
        ``regression.compute_J`` (see its Notes).

    Returns
    -------
    J : ndarray, shape (N, N)
        Recurrent weight matrix.
    J_prime : ndarray, shape (N, N)
        Skew coupling matrix (for omega drift).
    """
    J, _ = regression.compute_J(X, Phi, lamda=lamda)
    N_theta = X.shape[0]
    dtheta = 2 * np.pi / N_theta
    dX = np.diff(X, axis=0) / dtheta
    dX = np.concatenate(((X[0:1] - X[-1:]) / dtheta, dX), axis=0)
    J_prime, _ = regression.compute_J(X=dX, Phi=Phi, lamda=lamda)
    return J, J_prime

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 omega_func is not None.

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 auto-selects CUDA if available, else CPU.

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
def run_simulation(J, x_init, T, tau, dt, T_eval,
                   J_prime=None, omega_func=None, c_const=1., 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
    ----------
    J : ndarray, shape (N, N)
        Recurrent weights.
    x_init : ndarray, shape (N, N_batch)
        Initial states.
    T, tau, dt, T_eval : float
        Integration time, time constant, step, save period.
    J_prime : ndarray, shape (N, N), optional
        Required if ``omega_func`` is not None.
    omega_func : callable or None
        Time-varying drift.
    c_const : float, default 1.
        Mean-stabilizer strength.
    device : str or int or None, default None
        Torch device. ``None`` auto-selects CUDA if available, else CPU.

    Returns
    -------
    x_save : ndarray, shape (N_eval, N, N_batch)
        Saved state snapshots.
    """
    device = _auto_device(device)
    _, x_save, _ = sim.run_sim(
        T=T, tau=tau, dt=dt, T_eval=T_eval,
        J=torch.Tensor(J).to(device),
        J_prime=torch.Tensor(J_prime).to(device) if J_prime is not None else None,
        x_init=torch.Tensor(x_init).to(device),
        nonlin=nonlin,
        disable_tqdm=False, target_mean=1., const=c_const,
        omega_func=omega_func, break_if_stopped=False)
    return x_save

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))

m[t, a, b] = sum_i x_save[t, i, b] * X[a, i].

Source code in ring/data_driven.py
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
def compute_m(x_save, X):
    """Project trajectories onto tuning-curve basis via tensor contraction.

    Parameters
    ----------
    x_save : ndarray, shape (T_eval, N, N_batch)
        Trajectories.
    X : ndarray, shape (N_theta, N)
        Tuning-curve basis.

    Returns
    -------
    m : ndarray, shape (T_eval, N_theta, N_batch)
        ``m[t, a, b] = sum_i x_save[t, i, b] * X[a, i]``.
    """
    return np.einsum('tib,ai->tab', x_save, X, optimize='optimal')

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
def 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
    ----------
    hd : ndarray, shape (T,)
        Continuous (possibly unwrapped) angles.

    Returns
    -------
    hd_plot : ndarray, shape (T,)
        Mod-2pi-wrapped; entries flanking a > pi jump are NaN.
    """
    hd_plot = np.mod(hd, 2 * np.pi)
    discontinuities = np.where(np.abs(np.diff(hd_plot)) > np.pi)[0]
    for idx in discontinuities:
        hd_plot[idx:idx + 2] = np.nan
    return hd_plot

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 m rows.

required
hd_dt float

Time step between hd samples.

required
vmin float

Lower bound for the imshow colormap (vmax is auto-set to the 97.5 percentile of m).

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
def plot_head_direction(ax, m, hd, m_dt, hd_dt, vmin=0):
    """Plot ``m`` as a heatmap with the head-direction track overlaid.

    Parameters
    ----------
    ax : matplotlib axis
    m : ndarray, shape (T_eval, N_theta)
    hd : ndarray, shape (T_hd,)
    m_dt : float
        Time step between ``m`` rows.
    hd_dt : float
        Time step between ``hd`` samples.
    vmin : float, default 0
        Lower bound for the imshow colormap (vmax is auto-set to the 97.5
        percentile of ``m``).
    """
    vmax = np.percentile(m.flatten(), 97.5)
    T = m_dt * len(m)
    ax.imshow(m.T[::-1], extent=(0, T, 0, 2 * np.pi), aspect='auto',
              cmap=style.field_cmap('ice'), vmin=vmin, vmax=vmax)

    hd_time = np.arange(int(T / hd_dt)) * hd_dt
    ax.plot(hd_time, hd[:len(hd_time)], lw=1, c=style.HD_COLOR, label='Head Direction')

    ax.set_yticks([0, np.pi, 2 * np.pi], ['0', 'π', '2π'])
    ax.set_xlabel("time (s)")
    ax.set_ylabel("$\\theta$", rotation=0, va='center')

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 (0) or the standard method (1). None auto-picks the smaller-dim option.

None
return_V bool

Also return the eigenvector matrix V.

False
return_eig bool

Also return eigenvalues w.

False
N_retain int

Number of PCs to use for the projection of X; default keeps all.

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
def 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
    ----------
    X : ndarray, shape (N_theta, N)
        Tuning-curve matrix (samples x features).
    x_save : ndarray, shape (T_eval, N, N_batch)
        Trajectories to project.
    N_pcs : int, default 3
        Number of principal components.
    comp_axis : int or None, default None
        Force the kernel method (``0``) or the standard method (``1``).
        ``None`` auto-picks the smaller-dim option.
    return_V : bool, default False
        Also return the eigenvector matrix ``V``.
    return_eig : bool, default False
        Also return eigenvalues ``w``.
    N_retain : int, optional
        Number of PCs to use for the projection of ``X``; default keeps all.

    Returns
    -------
    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.
    """
    N_theta, N = X.shape
    mu = X.mean(0)
    X_ctd = X - mu
    x_save_ctd = x_save - mu[None, :, None]

    use_kernel = (comp_axis == 0) if comp_axis is not None else (N_theta < N)

    if use_kernel:
        K = np.dot(X_ctd, X_ctd.T) / N_theta  # (N_theta, N_theta)
        w_K, U = np.linalg.eigh(K)
        w_K, U = w_K[::-1], U[:, ::-1]
        V = np.zeros((N, N_pcs))
        for i in range(N_pcs):
            V[:, i] = np.dot(X_ctd.T, U[:, i]) / np.sqrt(w_K[i] * N_theta)
        w = w_K
    else:
        C = np.dot(X_ctd.T, X_ctd) / N_theta
        w, V = np.linalg.eigh(C)
        w, V = w[::-1], V[:, ::-1]
        V = V[:, :N_pcs]

    if N_retain is None:
        N_retain = N
    pcs = X_ctd @ V[:, :N_retain]
    pcs_traj = np.einsum('tib,ik->tkb', x_save_ctd, V, optimize='optimal')

    if return_V:
        return (pcs, pcs_traj, V, w) if return_eig else (pcs, pcs_traj, V)
    return (pcs, pcs_traj, w) if return_eig else (pcs, pcs_traj)

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 pcs as a scatter cloud instead of a connected line.

False
cloud_color (str, float, float)

Appearance of the torus=True manifold cloud. The defaults reproduce the original dense black cloud; the torus figure passes a lighter, smaller cloud so the coloured trajectories on top of it stay readable.

'black'
cloud_alpha (str, float, float)

Appearance of the torus=True manifold cloud. The defaults reproduce the original dense black cloud; the torus figure passes a lighter, smaller cloud so the coloured trajectories on top of it stay readable.

'black'
cloud_s (str, float, float)

Appearance of the torus=True manifold cloud. The defaults reproduce the original dense black cloud; the torus figure passes a lighter, smaller cloud so the coloured trajectories on top of it stay readable.

'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
def 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
    ----------
    ax : matplotlib 3D axis
    pcs : ndarray, shape (N_theta, >= 3)
    pcs_traj : ndarray, shape (T_eval, 3, N_batch)
    torus : bool, default False
        If True, render ``pcs`` as a scatter cloud instead of a connected line.
    cloud_color, cloud_alpha, cloud_s : str, float, float
        Appearance of the ``torus=True`` manifold cloud. The defaults reproduce
        the original dense black cloud; the torus figure passes a lighter, smaller
        cloud so the coloured trajectories on top of it stay readable.
    traj_lw : float or None
        Trajectory line width. None keeps the rcParams default.
    end_s, start_s : float
        Marker sizes for the trajectory end dot and start cross. Smaller values
        stop the black markers from swamping the trajectory colours.
    """
    ax.xaxis.pane.fill = False
    ax.yaxis.pane.fill = False
    ax.zaxis.pane.fill = False
    ax.grid(False)

    if torus:
        ax.scatter(pcs[:, 0], pcs[:, 1], pcs[:, 2], lw=0, s=cloud_s,
                   alpha=cloud_alpha, c=cloud_color)
    else:
        ax.plot(pcs[:, 0], pcs[:, 1], pcs[:, 2], c='0.6', ls='-', zorder=0)

    # Trajectories are indexed by their initial angle on the ring, which is
    # cyclic, so they take ANGLE_CMAP. Reading it from ring.style keeps every
    # caller on the same map.
    n_trajectories = pcs_traj.shape[2]
    colors = style.ANGLE_CMAP(np.linspace(0, 1, n_trajectories))

    for ic_idx in range(n_trajectories):
        color = colors[ic_idx]
        ax.scatter(pcs_traj[-1, 0, ic_idx], pcs_traj[-1, 1, ic_idx], pcs_traj[-1, 2, ic_idx],
                   lw=0, s=end_s, c='black', marker='.')
        ax.scatter(pcs_traj[0, 0, ic_idx], pcs_traj[0, 1, ic_idx], pcs_traj[0, 2, ic_idx],
                   lw=0.4, s=start_s, c='black', marker='x')
        ax.plot(pcs_traj[:, 0, ic_idx], pcs_traj[:, 1, ic_idx], pcs_traj[:, 2, ic_idx],
                c=color, lw=traj_lw)

    ax.set_xticklabels([])
    ax.set_yticklabels([])
    ax.set_zticklabels([])
    ax.view_init(elev=20, azim=120)

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, y span the plane in which phase_a traces a closed circle, obtained by regressing its cosine and sine onto the block;
  • z is the residual direction that best encodes phase_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 pcs @ frame.T and to trajectories as np.einsum('tkb,mk->tmb', pcs_traj, frame).

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
def 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``, ``y`` span the plane in which ``phase_a`` traces a closed circle,
      obtained by regressing its cosine and sine onto the block;
    - ``z`` is the residual direction that best encodes ``phase_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
    ----------
    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.
    phase_a : ndarray, shape (N_points,)
        Toroidal phase to place in the plotted plane, in radians.
    phase_b : ndarray, shape (N_points,)
        The other toroidal phase, in radians, which sets the third axis.

    Returns
    -------
    frame : ndarray, shape (3, N_pcs)
        Orthonormal rows. Apply to the manifold as ``pcs @ frame.T`` and to
        trajectories as ``np.einsum('tkb,mk->tmb', pcs_traj, frame)``.
    """
    B = np.asarray(pcs, dtype=float)
    B = B - B.mean(0)

    def _fit(target):
        c, *_ = np.linalg.lstsq(B, target - target.mean(), rcond=None)
        norm = np.linalg.norm(c)
        if norm < 1e-12:
            raise ValueError("phase is not represented in the supplied PC block")
        return c / norm

    axes = []
    for v in (_fit(np.cos(phase_a)), _fit(np.sin(phase_a)), _fit(np.cos(phase_b))):
        for u in axes:
            v = v - (v @ u) * u
        norm = np.linalg.norm(v)
        if norm < 1e-12:
            raise ValueError("degenerate display frame; the phases are collinear "
                             "in this PC block")
        axes.append(v / norm)
    return np.array(axes)

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
def compute_distances_to_ring(X, x_save, device='cpu'):
    """(internal) Closest-tuning-curve distance per timestep, normalized by sqrt(N)."""
    X_torch = torch.Tensor(X).to(device)
    x_save_torch = torch.Tensor(x_save).to(device)
    distances = []
    for t_idx in tqdm(range(len(x_save))):
        X_dyn = x_save_torch[t_idx, :]
        A = X_dyn[None, :, :] - X_torch[:, :, None]
        dist_matrix = torch.linalg.norm(A, dim=1)
        nearest_dist = torch.min(dist_matrix, dim=0).values
        distances.append(nearest_dist.cpu().numpy())
    distances = np.array(distances)
    N = X.shape[1]
    return distances / np.sqrt(N)  # not squared

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
def 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
    ----------
    X : ndarray, shape (N_theta, N)
    x_save : ndarray, shape (T_eval, N, N_batch)
    device : str, default 'cpu'
    chunk_size : int, default 10
        Number of batch elements per GPU chunk.

    Returns
    -------
    all_dists : ndarray, shape (T_eval, N_batch)
        Normalized closest-tuning-curve distance per timestep per batch.
    """
    N_chunks = int(np.ceil(x_save.shape[-1] / chunk_size))
    all_dists = np.zeros((x_save.shape[0], x_save.shape[2]))
    for i in range(N_chunks):
        print('chunk =', i + 1, 'of', N_chunks)
        i1, i2 = i * chunk_size, (i + 1) * chunk_size
        all_dists[:, i1:i2] = compute_distances_to_ring(X, x_save[:, :, i1:i2], device=device)
    return all_dists

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
def 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
    ----------
    data : ndarray, shape (N_curves, N_theta)
    return_idx : bool, default False
        If True, return integer bin indices (floor) instead of float angles.

    Returns
    -------
    com : ndarray, shape (N_curves,)
        Either angles in [0, 2*pi) (default) or integer bin indices.
    """
    result = analysis.circular_center_of_mass(data)
    if return_idx:
        return np.floor(result * data.shape[1] / (2 * np.pi)).astype(int)
    return result

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))

J reindexed so units appear in circular order.

order (ndarray, shape(N))

Sorting permutation (apply via arr[order]).

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
def sort_weight_matrix(J, Phi):
    """Sort ``J`` rows and columns by the circular COM of ``Phi``'s tuning curves.

    Parameters
    ----------
    J : ndarray, shape (N, N)
    Phi : ndarray, shape (N_theta, N)

    Returns
    -------
    J_srt : ndarray, shape (N, N)
        ``J`` reindexed so units appear in circular order.
    order : ndarray, shape (N,)
        Sorting permutation (apply via ``arr[order]``).
    """
    order = np.argsort(circular_com(Phi.T, True))
    J_srt = J[order, :][:, order]
    return J_srt, order

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
def load_hd_timeseries_data(file_path=HD_TIMESERIES_PATH):
    """(internal) Load (hd, dt) from a Peyrache-style npz."""
    print("loading", file_path)
    with np.load(file_path) as data:
        hd = data['hd']
        data_dt = data['dt'].item()
    return hd, data_dt

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
def 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.
    """
    non_nan_indices = np.where(~np.isnan(hd))[0]
    if len(non_nan_indices) == 0 or len(non_nan_indices) == len(hd):
        return hd
    all_indices = np.arange(len(hd))
    z = np.exp(1j * hd[non_nan_indices])
    real_interp = np.interp(all_indices, non_nan_indices, np.real(z))
    imag_interp = np.interp(all_indices, non_nan_indices, np.imag(z))
    return np.mod(np.angle(real_interp + 1j * imag_interp), 2 * np.pi)

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
def 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
    -------
    hd_unwrap_smooth : ndarray
    omega : ndarray
        Angular velocity = d(hd)/dt of the smoothed series.
    """
    hd = interpolate_angle_nans(hd)
    hd_unwrap = np.unwrap(hd)
    hd_unwrap = np.concatenate((np.ones(2000) * hd_unwrap[0], hd_unwrap))
    hd_unwrap_smooth = gaussian_filter1d(hd_unwrap, sigma=smoothing_sigma)
    omega = np.diff(np.unwrap(hd_unwrap_smooth)) / data_dt
    return hd_unwrap_smooth, omega

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
def load_hd_and_omega():
    """Load mouse HD timeseries and compute its smoothed angular velocity.

    Returns
    -------
    hd : ndarray
    omega : ndarray
    data_dt : float
    """
    hd, data_dt = load_hd_timeseries_data()
    hd, omega = preprocess_hd_data(hd, data_dt)
    return hd, omega, data_dt

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 N_theta // 2 + 1).

required
device int or None

None -> numpy on CPU; otherwise the torch CUDA device index.

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
def 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
    ----------
    N_samples : int
        Number of independent draws.
    N_freq : int
        Number of Fourier frequencies (typically ``N_theta // 2 + 1``).
    device : int or None
        ``None`` -> numpy on CPU; otherwise the torch CUDA device index.

    Returns
    -------
    z : ndarray or torch.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.
    """
    if device is None:  # numpy
        z = (np.random.randn(N_samples, N_freq) + 1j * np.random.randn(N_samples, N_freq)) / np.sqrt(2)
        z[:, 0] = z[:, 0].real * np.sqrt(2)
    else:  # torch
        z_real = torch.randn(N_samples, N_freq, device=device)
        z_imag = torch.randn(N_samples, N_freq, device=device)
        z = (z_real + 1j * z_imag) / np.sqrt(2)
        z[:, 0] = z[:, 0].real * np.sqrt(2)
    return z

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 for CPU/numpy.

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 return_Gamma_x_ft is True.

Gamma_x_ft same type, shape (N_theta // 2 + 1,), optional

Returned only if return_Gamma_x_ft is True.

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
def 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
    ----------
    scale : float
        Wraparound-Gaussian length scale.
    bias : float
        Offset subtracted before the nonlinearity.
    beta : float
        Sharpness of the softplus nonlinearity.
    N_samples : int
        Number of independent samples.
    N_theta : int
        Number of angular grid points.
    device : int or None
        CUDA device index, or ``None`` for CPU/numpy.
    return_Gamma_x_ft : bool, default False
        Also return the Fourier-space covariance.
    normalize : bool, default False
        Normalize each sample by its mean before returning (avoids the
        all-zero collapse for some parameter combinations).

    Returns
    -------
    Phi_m : ndarray or torch.Tensor, shape (N_samples, N_theta)
    X_m : same type/shape, optional
        Returned only if ``return_Gamma_x_ft`` is True.
    Gamma_x_ft : same type, shape (N_theta // 2 + 1,), optional
        Returned only if ``return_Gamma_x_ft`` is True.
    """
    N_freq = N_theta // 2 + 1
    eq_var = 1.
    backend = 'numpy' if device is None else 'torch'

    _, Gamma_x_ft = tc.wrapped_gaussian_cov(eq_var, scale, N_theta, backend=backend)
    if device is not None:
        Gamma_x_ft = Gamma_x_ft.to(device)

    z = sample_z(N_samples, N_freq, device)

    if device is None:
        X_m = np.fft.irfft(z * np.sqrt(Gamma_x_ft)[None, :], axis=1, norm='forward')
    else:
        X_m = torch.fft.irfft(z * torch.sqrt(Gamma_x_ft)[None, :], dim=1, norm='forward')

    Phi_m = fn.softplus(X_m - bias, beta=beta)

    if normalize:
        if device is None:
            Phi_m = Phi_m / (Phi_m.mean(1, keepdims=True) + 1e-30)
        else:
            Phi_m = Phi_m / (Phi_m.mean(1, keepdim=True) + 1e-30)

    if return_Gamma_x_ft:
        return Phi_m, X_m, Gamma_x_ft
    return Phi_m

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
def 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
    ----------
    params : sequence of 3 floats
        (scale, bias, beta).
    N_samples : int
    N_theta : int
    device : int or None

    Returns
    -------
    Gamma_phi : ndarray or torch.Tensor, shape (N_theta,)
    Gamma_phi_ft : ndarray or torch.Tensor, shape (N_theta // 2 + 1,)
    """
    Phi_m = gen_Phi_m(*params, N_samples, N_theta, device=device, normalize=True)
    Gamma_phi, Gamma_phi_ft = fn.calc_C(Phi_m)
    return Gamma_phi, Gamma_phi_ft

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 compute_cov_from_params.

required
N_theta

Forwarded to compute_cov_from_params.

required
device

Forwarded to compute_cov_from_params.

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
def 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
    ----------
    params : sequence of 3 floats
        (scale, bias, beta).
    Gamma_phi_data_ft : ndarray, shape (>= 20,)
        Target Fourier-space covariance.
    N_samples, N_theta, device :
        Forwarded to ``compute_cov_from_params``.

    Returns
    -------
    err : float
    """
    _, Gamma_phi_ft = compute_cov_from_params(params, N_samples, N_theta, device)
    if device is None:
        err = np.sqrt(np.sum((Gamma_phi_ft[:20] - Gamma_phi_data_ft[:20])**2))
    else:
        err = torch.sqrt(torch.sum(
            (Gamma_phi_ft[:20] - torch.from_numpy(Gamma_phi_data_ft[:20]).to(device))**2))
        err = err.item()
    return err
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

{'scale', 'bias', 'beta', 'loss'} at the minimum.

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
def 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
    ----------
    Gamma_phi_data_ft : ndarray, shape (>= 20,)
        Target Fourier coefficients.

    Returns
    -------
    best_params : dict
        ``{'scale', 'bias', 'beta', 'loss'}`` at the minimum.
    loss_vals : ndarray, shape (N_SCALE_POINTS, N_BIAS_POINTS, N_BETA_POINTS)
        Full grid of loss values.
    """
    # Pin the RNG so grid_search_results.npz is bit-reproducible.
    set_global_seed(42)

    scale_vals = np.linspace(SCALE_BOUNDS[0], SCALE_BOUNDS[1], N_SCALE_POINTS)
    bias_vals = np.linspace(BIAS_BOUNDS[0], BIAS_BOUNDS[1], N_BIAS_POINTS)
    beta_vals = np.linspace(BETA_BOUNDS[0], BETA_BOUNDS[1], N_BETA_POINTS)
    loss_vals = np.zeros((len(scale_vals), len(bias_vals), len(beta_vals)))

    device = torch.device(f'cuda:{DEVICE}') if isinstance(DEVICE, int) else None

    for i, scale in enumerate(scale_vals):
        print(f"Processing scale {i+1}/{len(scale_vals)}")
        for j, bias in enumerate(bias_vals):
            for k, beta in enumerate(beta_vals):
                loss_vals[i, j, k] = eval_loss(
                    [scale, bias, beta], Gamma_phi_data_ft,
                    N_SAMPLES, N_THETA, device=device)

        # Track + checkpoint best-so-far each scale-slab.
        min_idx = np.unravel_index(np.argmin(loss_vals), loss_vals.shape)
        current_best = {
            'scale': scale_vals[min_idx[0]],
            'bias': bias_vals[min_idx[1]],
            'beta': beta_vals[min_idx[2]],
            'loss': loss_vals[min_idx],
        }
        np.savez(OUTPUT_RESULTS_FILE,
                 scale_vals=scale_vals, bias_vals=bias_vals, beta_vals=beta_vals,
                 loss_vals=loss_vals,
                 bounds=[SCALE_BOUNDS, BIAS_BOUNDS, BETA_BOUNDS],
                 best_params=current_best)

    min_idx = np.unravel_index(np.argmin(loss_vals), loss_vals.shape)
    best_params = {
        'scale': scale_vals[min_idx[0]],
        'bias': bias_vals[min_idx[1]],
        'beta': beta_vals[min_idx[2]],
        'loss': loss_vals[min_idx],
    }
    return best_params, loss_vals

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
def main():
    """Script entry point: load ``INPUT_GAMMA_FILE`` and run the grid search."""
    print("Starting grid search with parameters:")
    print(f"  N_THETA: {N_THETA}")
    print(f"  N_SAMPLES: {N_SAMPLES}")
    print(f"  Device: {DEVICE}")
    print(f"  Grid resolution: {N_SCALE_POINTS}x{N_BIAS_POINTS}x{N_BETA_POINTS}")
    print(f"  Input file: {INPUT_GAMMA_FILE}")
    print(f"  Output file: {OUTPUT_RESULTS_FILE}")

    with np.load(INPUT_GAMMA_FILE) as data:
        Gamma_phi_data_ft = data['Gamma_phi_data_ft']
    print("\nInput data loaded successfully.")

    best_params, loss_vals = run_grid_search(Gamma_phi_data_ft)
    print("\nGrid search completed successfully!")
    print("\nBest parameters found:")
    for param, value in best_params.items():
        print(f"  {param}: {value}")

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 N-normalized convention described below.

required
method (opt, primal, dual, leave_one_out)

Solver variant:

  • 'opt': auto-select 'dual' if N_theta < N, else 'primal'.
  • 'primal': invert Phi.T @ Phi / N_theta + (N * lamda) * I (N x N). Cheaper when N <= N_theta.
  • 'dual': invert Phi @ Phi.T / N + (lamda * N_theta) * I (N_theta x N_theta). Cheaper when N_theta < N.
  • 'leave_one_out': for each neuron i, solve the regression excluding column i of Phi (leave-one-out cross-validation style). Slow (O(N) regressions); J_uc is not returned. Its ridge coefficient uses N - 1, not N, because that regression has N - 1 predictors.
'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. None when method='leave_one_out'.

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
def 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
    ----------
    X : ndarray, shape (N_theta, N)
        Target activity (e.g. preactivations or trajectories).
    Phi : ndarray, shape (N_theta, N)
        Predictor activity (e.g. tuning curves).
    lamda : float
        Ridge regularization strength, in the ``N``-normalized convention
        described below.
    method : {'opt', 'primal', 'dual', 'leave_one_out'}, default 'opt'
        Solver variant:

        - ``'opt'``: auto-select ``'dual'`` if ``N_theta < N``, else ``'primal'``.
        - ``'primal'``: invert ``Phi.T @ Phi / N_theta + (N * lamda) * I`` (``N x N``).
          Cheaper when ``N <= N_theta``.
        - ``'dual'``: invert ``Phi @ Phi.T / N + (lamda * N_theta) * I``
          (``N_theta x N_theta``). Cheaper when ``N_theta < N``.
        - ``'leave_one_out'``: for each neuron ``i``, solve the regression
          excluding column ``i`` of ``Phi`` (leave-one-out cross-validation
          style). Slow (O(N) regressions); ``J_uc`` is not returned. Its ridge
          coefficient uses ``N - 1``, not ``N``, because that regression has
          ``N - 1`` predictors.

    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
    -------
    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. ``None``
        when ``method='leave_one_out'``.
    """
    N_theta, N = Phi.shape
    if method == 'opt':
        method = 'dual' if N_theta < N else 'primal'

    if method == 'dual':
        K = (Phi @ Phi.T) / N + (lamda * N_theta) * np.eye(N_theta)
        K_inv = np.linalg.inv(K)
        A = np.eye(N) - (1 / N) * (Phi.T @ K_inv @ Phi)
        J_uc = (1 / N) * (X.T @ K_inv @ Phi)
        J = J_uc - A * (np.diag(J_uc) / np.diag(A))[:, None]
        return J, J_uc

    elif method == 'primal':
        M = (Phi.T @ Phi) / N_theta + np.eye(N) * (N * lamda)
        M_inv = np.linalg.inv(M)
        J_uc = ((X.T @ Phi) / N_theta) @ M_inv
        J = J_uc - M_inv * (np.diag(J_uc) / np.diag(M_inv))[:, None]
        return J, J_uc

    elif method == 'leave_one_out':
        J = np.zeros((N, N))
        for i in range(N):
            mask = np.ones(N, dtype=bool)
            mask[i] = False
            Phi_excl = Phi[:, mask]
            X_i = X[:, i]
            M_excl = (Phi_excl.T @ Phi_excl) / N_theta + np.eye(N - 1) * ((N - 1) * lamda)
            J_i = np.linalg.inv(M_excl) @ ((1 / N_theta) * (Phi_excl.T @ X_i))
            J[mask, i] = J_i
        return J, None

    else:
        raise ValueError(f"method must be one of 'opt', 'primal', 'dual', 'leave_one_out'; got {method!r}")

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
def circular_center_of_mass(tuning_curves):
    """Angular center of mass of one or more tuning curves.

    Parameters
    ----------
    tuning_curves : ndarray, shape (N_curves, N_theta)

    Returns
    -------
    coms : ndarray, shape (N_curves,)
        Angular positions in [0, 2*pi).
    """
    theta = np.linspace(0, 2 * np.pi, tuning_curves.shape[1], endpoint=False)
    x_comp = np.sum(tuning_curves * np.cos(theta), axis=1)
    y_comp = np.sum(tuning_curves * np.sin(theta), axis=1)
    return np.arctan2(y_comp, x_comp) % (2 * np.pi)

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
def center_tuning_curves(tuning_curves):
    """Roll each tuning curve so its circular center of mass is at index 0.

    Parameters
    ----------
    tuning_curves : ndarray, shape (N_curves, N_theta)

    Returns
    -------
    centered : ndarray, shape (N_curves, N_theta)
    """
    n_angles = tuning_curves.shape[1]
    coms = circular_center_of_mass(tuning_curves)
    shifts = (-(n_angles * coms / (2 * np.pi)).round()).astype(int)
    centered = np.zeros_like(tuning_curves)
    for i, shift in enumerate(shifts):
        centered[i] = np.roll(tuning_curves[i], shift)
    return centered

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
def 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
    ----------
    signal : ndarray, shape (N,)
    z_thresh : float

    Returns
    -------
    maxima : ndarray of int
    """
    # diff[i] is the rise into bin i, with diff[0] wrapping from the last bin.
    diff = np.concatenate(([signal[0] - signal[-1]], np.diff(signal)))
    # Bin i is a local maximum when the rise into it is positive and the rise out of it is
    # negative. Rolling keeps that test defined at the last bin, which np.diff cannot reach.
    sign_change = np.sign(np.roll(diff, -1)) - np.sign(diff)
    maxima = np.where(sign_change == -2)[0]
    return maxima[(signal[maxima] - signal.mean()) / signal.std() > z_thresh]

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
def select_mice_by_cell_count(mouse_nums, n_mice):
    """Select the ``n_mice`` mice with the most recorded cells.

    Parameters
    ----------
    mouse_nums : ndarray, shape (N_curves,)
        Per-cell mouse-id labels.
    n_mice : int
        Number of mice to keep.

    Returns
    -------
    selected : ndarray, shape (n_mice,)
        Mouse-id values, ordered by descending cell count.
    """
    total_mice = int(np.max(mouse_nums) + 1)
    counts = np.array([np.sum(mouse_nums == i) for i in range(total_mice)])
    return np.argsort(counts)[::-1][:n_mice]

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
def compute_mean_and_std_profiles(tuning_curves):
    """COM-centered mean and std profiles across one set of tuning curves.

    Parameters
    ----------
    tuning_curves : ndarray, shape (N_curves, N_theta)

    Returns
    -------
    mean_profile : ndarray, shape (N_theta,)
    std_profile : ndarray, shape (N_theta,)
    """
    tuning_curves_centered = center_tuning_curves(tuning_curves)
    return tuning_curves_centered.mean(0), tuning_curves_centered.std(0)

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
def compute_mean_and_std_profiles_for_all_mice(Phi_m_data, mouse_nums):
    """Per-mouse mean + std profiles.

    Parameters
    ----------
    Phi_m_data : ndarray, shape (N_curves, N_theta)
    mouse_nums : ndarray, shape (N_curves,)

    Returns
    -------
    means : ndarray, shape (n_mice, N_theta)
    stds : ndarray, shape (n_mice, N_theta)
    """
    all_mus, all_stds = [], []
    n_mice = int(np.max(mouse_nums) + 1)
    for mouse_num in range(n_mice):
        mu, std = compute_mean_and_std_profiles(Phi_m_data[mouse_nums == mouse_num])
        all_mus.append(mu)
        all_stds.append(std)
    return np.array(all_mus), np.array(all_stds)

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-n_mice; element m is the array of COMs for mouse m.

Source code in ring/analysis.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
def compute_coms_for_all_mice(Phi_m_data, mouse_nums):
    """Per-mouse list of tuning-curve COMs.

    Parameters
    ----------
    Phi_m_data : ndarray, shape (N_curves, N_theta)
    mouse_nums : ndarray, shape (N_curves,)

    Returns
    -------
    mouse_coms : list of ndarray
        Length-``n_mice``; element ``m`` is the array of COMs for mouse ``m``.
    """
    n_mice = int(np.max(mouse_nums) + 1)
    return [circular_center_of_mass(Phi_m_data[mouse_nums == m]) for m in range(n_mice)]

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 max_peaks - 1 peaks per curve.

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
def compute_peak_counts(tuning_curves, z_thresh, max_peaks=6):
    """Normalized histogram of number-of-peaks across tuning curves.

    Parameters
    ----------
    tuning_curves : ndarray, shape (N_curves, N_theta)
    z_thresh : float
        Z-score threshold for peak detection.
    max_peaks : int, default 6
        Histogram extends to ``max_peaks - 1`` peaks per curve.

    Returns
    -------
    hist : ndarray, shape (max_peaks - 1,)
        Probabilities (sums to 1).
    """
    peak_counts = np.array([len(find_local_maxima(tc, z_thresh)) for tc in tuning_curves])
    counts = np.array([(peak_counts == i).sum() for i in range(1, max_peaks)]).astype(float)
    return counts / counts.sum()

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
def get_peak_values(tuning_curves, num_peaks):
    """Top-``num_peaks`` peak heights per curve (NaN-padded for short rows).

    Parameters
    ----------
    tuning_curves : ndarray, shape (N_curves, N_theta)
    num_peaks : int

    Returns
    -------
    results : ndarray, shape (N_curves, num_peaks)
        Sorted descending; missing values are NaN.
    """
    results = np.zeros((len(tuning_curves), num_peaks)) * np.nan
    for i, tc in enumerate(tuning_curves):
        maxima = find_local_maxima(tc, z_thresh=1)
        max_vals = np.sort(tc[maxima])[::-1]
        n = min(num_peaks, len(max_vals))
        results[i, :n] = max_vals[:n]
    return results

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
def 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
    ----------
    tuning_curves : ndarray, shape (N_curves, N_theta)

    Returns
    -------
    scores : ndarray, shape (N_curves,)
        Pearson r in [-1, 1].
    """
    def _com_bin(x):
        # Inline integer-bin COM. Uses the average-with-weights form rather
        # than the module-level circular_center_of_mass, because the released
        # results were computed with this form and the two differ in the last
        # float bits.
        theta = np.arange(len(x)) * 2 * np.pi / len(x)
        cos_avg = np.average(np.cos(theta), weights=x)
        sin_avg = np.average(np.sin(theta), weights=x)
        angle = np.mod(np.arctan2(sin_avg, cos_avg), 2 * np.pi)
        return int(np.round(angle * len(x) / (2 * np.pi)))

    scores = []
    for tc in tuning_curves:
        com = _com_bin(tc)
        reversed_tc = np.roll(tc, -2 * com - 1)[::-1]
        scores.append(pearsonr(tc, reversed_tc)[0])
    return np.array(scores)

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
def compute_bits_per_spike(tuning_curves):
    """Per-curve bits-per-spike (mean of ``tc * log2(tc)``).

    Parameters
    ----------
    tuning_curves : ndarray, shape (N_curves, N_theta)

    Returns
    -------
    bits : ndarray, shape (N_curves,)
    """
    return (tuning_curves * np.log2(tuning_curves)).mean(1)

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 {dataset, statistic, p_value, corrected_p_value, rejected}.

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
def analyze_circular_datasets(datasets, alpha=0.05):
    """Kuiper uniformity test per dataset + Benjamini-Hochberg FDR correction.

    Parameters
    ----------
    datasets : list of ndarray
        Each entry is an array of angular values to test against uniformity.
    alpha : float, default 0.05
        FDR target significance level.

    Returns
    -------
    results : list of dict
        Per-dataset ``{dataset, statistic, p_value, corrected_p_value, rejected}``.
    """
    results = []
    p_values = []
    for i, data in enumerate(datasets):
        statistic, p_value = kuiper(data, lambda x: x / (2 * np.pi))
        results.append({'dataset': i + 1, 'statistic': statistic, 'p_value': p_value})
        p_values.append(p_value)

    rejected, corrected_p_values, _, _ = multipletests(p_values, alpha=alpha, method='fdr_bh')
    for i, result in enumerate(results):
        result['corrected_p_value'] = corrected_p_values[i]
        result['rejected'] = rejected[i]
    return results

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 compute_coms_for_all_mice.

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
def analyze_and_print_stats(mouse_coms):
    """Run uniformity tests on per-mouse COM distributions; print a summary.

    Parameters
    ----------
    mouse_coms : list of ndarray
        From ``compute_coms_for_all_mice``.
    """
    results = analyze_circular_datasets(mouse_coms)
    p_vals = np.array([r['p_value'] for r in results])
    p_vals_corrected = np.array([r['corrected_p_value'] for r in results])

    print("\nUniformity Test Results:")
    print(f"Number of mice: {len(p_vals)}")
    print(f"Mice with p < 0.05 (uncorrected): {np.sum(p_vals < 0.05)}")
    print(f"Mice with p < 0.05 (FDR-corrected): {np.sum(p_vals_corrected < 0.05)}")
    print("\nP-value ranges:")
    print(f"Uncorrected: {p_vals.min():.1e} - {p_vals.max():.1e}")
    print(f"FDR-corrected: {p_vals_corrected.min():.1e} - {p_vals_corrected.max():.1e}")

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: peak_counts (list of (data, model) tuples per threshold), peak_values (data, model), symmetry (data, model), information (data, model).

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
def analyze_tuning_curves(data_curves, model_curves, z_thresholds=[1.0, 0.5, 0.0]):
    """Run all four data-vs-model comparison metrics.

    Parameters
    ----------
    data_curves : ndarray, shape (N_curves, N_theta)
    model_curves : ndarray, shape (N_curves, N_theta)
    z_thresholds : list of float, default [1.0, 0.5, 0.0]
        Thresholds for peak detection in the peak-count histogram.

    Returns
    -------
    results : dict
        Keys: ``peak_counts`` (list of (data, model) tuples per threshold),
        ``peak_values`` (data, model), ``symmetry`` (data, model),
        ``information`` (data, model).
    """
    return {
        'peak_counts': [(compute_peak_counts(data_curves, z),
                         compute_peak_counts(model_curves, z))
                        for z in z_thresholds],
        'peak_values': (get_peak_values(data_curves, 3),
                        get_peak_values(model_curves, 3)),
        'symmetry': (compute_symmetry_scores(data_curves),
                     compute_symmetry_scores(model_curves)),
        'information': (compute_bits_per_spike(data_curves),
                        compute_bits_per_spike(model_curves)),
    }

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
def save_analysis_results(results, filename='tuning_curve_analysis.npz'):
    """Serialize the dict from ``analyze_tuning_curves`` to compressed npz.

    Parameters
    ----------
    results : dict
    filename : str
    """
    np.savez_compressed(
        filename,
        peak_counts_data=[x[0] for x in results['peak_counts']],
        peak_counts_model=[x[1] for x in results['peak_counts']],
        peak_values_data=results['peak_values'][0],
        peak_values_model=results['peak_values'][1],
        symmetry_data=results['symmetry'][0],
        symmetry_model=results['symmetry'][1],
        information_data=results['information'][0],
        information_model=results['information'][1],
    )

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 analyze_tuning_curves.

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
def load_analysis_results(filename='tuning_curve_analysis.npz'):
    """Inverse of ``save_analysis_results``.

    Parameters
    ----------
    filename : str

    Returns
    -------
    results : dict
        Same structure produced by ``analyze_tuning_curves``.
    """
    data = np.load(filename)
    return {
        'peak_counts': list(zip(data['peak_counts_data'], data['peak_counts_model'])),
        'peak_values': (data['peak_values_data'], data['peak_values_model']),
        'symmetry': (data['symmetry_data'], data['symmetry_model']),
        'information': (data['information_data'], data['information_model']),
    }

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
def unity_erf(x):
    """Error-function nonlinearity normalized so ``phi'(0) = 1``.

    ``phi(x) = erf(sqrt(pi) * x / 2)``.

    Parameters
    ----------
    x : float or ndarray or torch.Tensor
        Input.

    Returns
    -------
    Same type and shape as `x`.
    """
    if isinstance(x, torch.Tensor):
        return torch.erf(np.sqrt(np.pi) * x / 2.)
    return erf(np.sqrt(np.pi) * x / 2.)

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
def unity_erf_deriv(x):
    """Derivative of ``unity_erf``: ``exp(-pi * x^2 / 4)``.

    Parameters
    ----------
    x : float or ndarray or torch.Tensor
        Input.

    Returns
    -------
    Same type and shape as `x`.
    """
    if isinstance(x, torch.Tensor):
        return torch.exp(-(np.pi * x**2) / 4)
    return np.exp(-(np.pi * x**2) / 4)

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
def 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
    ----------
    x : float or ndarray or torch.Tensor
        Input.
    beta : float
        Response sharpness.

    Returns
    -------
    Same type and shape as `x`.
    """
    return 1 + unity_erf(beta * x)

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 beta -> inf.

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
def softplus(x, beta=1.):
    """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
    ----------
    x : float or ndarray or torch.Tensor
        Input. Python floats are promoted to a 1-element numpy array.
    beta : float
        Sharpness parameter; approaches ReLU as ``beta -> inf``.

    Returns
    -------
    Same type and shape as the (possibly promoted) input.
    """
    if isinstance(x, (int, float)):
        x = np.array([x], dtype=float)
    if isinstance(x, torch.Tensor):
        result = torch.zeros_like(x)
        mask_pos = x >= 0
        result[mask_pos] = x[mask_pos] + torch.log(1 + torch.exp(-beta * x[mask_pos])) / beta
        result[~mask_pos] = torch.log(1 + torch.exp(beta * x[~mask_pos])) / beta
    else:
        result = np.zeros_like(x)
        mask_pos = x >= 0
        result[mask_pos] = x[mask_pos] + np.log(1 + np.exp(-beta * x[mask_pos])) / beta
        result[~mask_pos] = np.log(1 + np.exp(beta * x[~mask_pos])) / beta
    return result

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 C (real-space) and C_ft (Fourier). Otherwise return only C.

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 return_ft is True.

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
def 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
    ----------
    X : ndarray or torch.Tensor, shape (N_samples, N_theta)
        Sample matrix; rows are samples.
    return_ft : bool, default True
        If True, return both ``C`` (real-space) and ``C_ft`` (Fourier).
        Otherwise return only ``C``.

    Returns
    -------
    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 ``return_ft`` is True.
    """
    if isinstance(X, np.ndarray):
        C_ft = np.mean(np.abs(np.fft.rfft(X, axis=1, norm='forward'))**2, axis=0)
        C = np.fft.irfft(C_ft, norm='forward')
    else:  # torch
        C_ft = torch.mean(torch.abs(torch.fft.rfft(X, dim=1, norm='forward'))**2, dim=0)
        C = torch.fft.irfft(C_ft, norm='forward')
    if return_ft:
        return C, C_ft
    return C

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
def setup_tc_axes(axes):
    """(internal) Standardize tuning-curve panel formatting.

    Sets x-tick positions to [0, pi, 2*pi] with symbolic labels, x-limits
    to [0, 2*pi], y-limits to [0, 10]; suppresses x-labels on non-bottom
    rows and y-tick labels on non-left columns.

    Parameters
    ----------
    axes : ndarray of matplotlib axes
        1-D or 2-D grid of axes.
    """
    if axes.ndim == 1:
        axes = axes.reshape(1, -1)
    for ax in axes.flatten():
        ax.set_xticks([0, np.pi, 2 * np.pi])
        ax.set_xticklabels(["0", "$\\pi$", "$2\\pi$"])
        ax.set_xlabel("$\\theta$")
        ax.set_ylim(0, 10)
        ax.set_xlim(0, 2 * np.pi)
    for ax in axes[:-1].flatten():
        ax.set_xlabel("")
    for ax in axes[:, 1:].flatten():
        ax.set_yticklabels([])

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
def setup_profile_axes(ax, ylabel):
    """(internal) Standardize profile-plot panel formatting.

    Parameters
    ----------
    ax : matplotlib axis
    ylabel : str
    """
    ax.set_xticks([-np.pi, 0, np.pi])
    ax.set_ylim(0, 6)
    ax.set_xlim(-np.pi, np.pi)
    ax.set_xticklabels(['$-\\pi$', '$0$', '$\\pi$'])
    ax.set_ylabel(ylabel)

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
def 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
    ----------
    ax : matplotlib axis
    opt_sigmas : ndarray, shape (N_units, 2)
        Optimal sigmas per CV fold.
    """
    log_sigmas = np.log10(opt_sigmas)
    ax.scatter(log_sigmas[:, 0], log_sigmas[:, 1],
               lw=0, s=2.5, alpha=0.25, clip_on=False)
    ax.set_xlim(-1, 2)
    ax.set_ylim(-1, 2)
    ax.set_aspect(1.0)

    rho, _ = pearsonr(log_sigmas[:, 0], log_sigmas[:, 1])
    ax.text(0.05, 0.95, f'ρ = {rho:.2f}', transform=ax.transAxes, verticalalignment='top')
    return ax

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 plt.subplots(figsize=(4, 3)) is created.

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
def plot_loss_vs_scale(ax, scale_vals, min_losses, opt_scale):
    """Optimization loss vs the wrap-Gaussian scale parameter, with optimum marked.

    Parameters
    ----------
    ax : matplotlib axis or None
        If None, a fresh ``plt.subplots(figsize=(4, 3))`` is created.
    scale_vals : ndarray, shape (N_scale,)
    min_losses : ndarray, shape (N_scale,)
        Minimum loss at each scale (after marginalizing over bias, beta).
    opt_scale : float
        Optimal scale value (where to draw the vertical line).
    """
    if ax is None:
        _, ax = plt.subplots(figsize=(4, 3))
    # A plain solid black line: this is a smooth measured error curve, so markers
    # are unjustified per the plotting convention. clip_on=False so the peak of the
    # curve (which touches the y-limit) is not sliced off by the axes box.
    ax.plot(scale_vals, min_losses, color='black', clip_on=False, label='Loss')
    ax.axvline(x=opt_scale, color='black', linestyle='--', alpha=1,
               label=f'Min Scale={opt_scale:.2f}')
    ax.set_xlabel("$\\sigma$ [Fourier decay scale]")
    ax.set_ylabel('min. error at $\\sigma$')
    ax.set_ylim(0, 0.11)
    return ax

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 plt.subplots(figsize=(4, 3)) is created.

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
def 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
    ----------
    ax : matplotlib axis or None
        If None, a fresh ``plt.subplots(figsize=(4, 3))`` is created.
    loss_slice : ndarray, shape (N_bias, N_beta)
        Loss landscape at the optimal scale.
    bias_vals : ndarray, shape (N_bias,)
    beta_vals : ndarray, shape (N_beta,)
    opt_bias, opt_beta : float
        Optimal (bias, beta).

    Returns
    -------
    ax : matplotlib axis
    cbar : matplotlib colorbar
    """
    if ax is None:
        _, ax = plt.subplots(figsize=(4, 3))
    im = ax.imshow(loss_slice.T, origin='lower', aspect='auto',
                   extent=[bias_vals[0], bias_vals[-1], beta_vals[0], beta_vals[-1]],
                   cmap=style.field_cmap('aurora'),
                   vmin=0, vmax=loss_slice.max(), interpolation="None")
    ax.plot(opt_bias, opt_beta, 'w.', markersize=5,
            label=f'Min (bias={opt_bias:.2f}, beta={opt_beta:.2f})')
    cbar = plt.colorbar(im, ax=ax, label='error', location='top',
                        fraction=style.CBAR_FRACTION, pad=style.CBAR_PAD,
                        aspect=style.CBAR_ASPECT)
    cbar.outline.set_linewidth(0.5)
    ax.set_xlabel('$b$ [soft threshold]')
    ax.set_ylabel("$\\beta$ [sharpness]")
    ax.set_ylim(0, 10)
    ax.set_xlim(0, 5)
    return ax, cbar

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
def 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
    ----------
    axes : ndarray of matplotlib axes, shape (N_mice, N_cols)
    mouse_nums_to_plot : sequence of int
        Mouse ids to render (one per row).
    mouse_nums : ndarray, shape (N_curves,)
        Per-cell mouse-id labels.
    mouse_names : ndarray, shape (N_curves,)
        Per-cell mouse names (strings).
    plain_tcs : ndarray, shape (N_curves, 2, N_theta)
        Plain (per-CV-fold) tuning curves.
    scalings : ndarray, shape (N_curves,)
        Per-cell scaling factors (mean-normalize).
    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.
"""
    if axes.ndim == 1:
        axes = axes.reshape(1, -1)
    N_theta = Phi_m_data.shape[1]
    theta = np.arange(N_theta) * 2 * np.pi / N_theta
    # CV-fold colours. Defaults are the original bright pair; the published
    # figure passes the muted pair.
    c1, c2 = fold_colors if fold_colors is not None else (style.FOLD_A, style.FOLD_B)

    for row_idx, mouse_num in enumerate(mouse_nums_to_plot):
        mouse_mask = mouse_nums == mouse_num
        mouse_name = mouse_names[mouse_mask][0]

        np.random.seed(row_idx)
        cell_idx_to_show = np.random.choice(np.arange(mouse_mask.sum()),
                                            replace=False, size=axes.shape[1])

        for i, ax in zip(cell_idx_to_show, axes[row_idx]):
            plain_tcs_to_show = plain_tcs[mouse_mask][i] * scalings[mouse_mask][i]
            ax.plot(theta, plain_tcs_to_show[0], clip_on=True, color=c1, lw=1, label="partition 1")
            ax.plot(theta, plain_tcs_to_show[1], clip_on=True, color=c2, lw=1,
                    label="partition 2")
            ax.plot(theta, Phi_m_data[mouse_mask][i], color=style.DATA,
                    clip_on=True, label="smoothed")
            if ax == axes[row_idx][0]:
                ax.set_ylabel(f'mouse\n{mouse_name}')

    setup_tc_axes(axes)

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 gp_opt.gen_Phi_m draws from, set here so the panel is reproducible whatever the caller did beforehand.

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
def 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
    ----------
    axes : ndarray of matplotlib axes (1-D or 2-D)
    opt_params : sequence of 3 floats
        (scale, bias, beta).
    seed : int
        Seed for the global RNG that ``gp_opt.gen_Phi_m`` draws from, set here so
        the panel is reproducible whatever the caller did beforehand.
    """
    if axes.ndim == 1:
        axes = axes.reshape(1, -1)
    set_global_seed(seed)
    theta = np.arange(100) * 2 * np.pi / 100
    Phi_m = gp_opt.gen_Phi_m(*opt_params, N_samples=axes.size, N_theta=100)
    Phi_m = Phi_m / Phi_m.mean(1, keepdims=True)

    for i, ax in enumerate(axes.flatten()):
        ax.plot(theta, Phi_m[i], color='black', clip_on=False)

    setup_tc_axes(axes)

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
def 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
    ----------
    ax : matplotlib axis
    theta : ndarray, shape (N_theta,)
    profiles : ndarray, shape (N_curves, N_theta)
    mean_profile : ndarray or None, shape (N_theta,)
    profile_label : str
        Y-axis label.
    mean_label : str
        (Unused; kept for backward compat with signature.)
    color : str
        Color for the individual-profile lines.
    model_profile : ndarray or None, shape (N_theta,)
    """
    ax.plot(theta, profiles.T, alpha=.5, c=color, zorder=0, clip_on=False)
    ax.plot(theta, profiles[0], alpha=.5, c=color, zorder=0, clip_on=False, label='individual mice')
    if mean_profile is not None:
        # Only lighten and widen the data curve when a nearly coincident model
        # curve is present. Data-only panels retain the bold charcoal aggregate.
        mean_color = style.DATA_UNDERLAY if model_profile is not None else style.DATA
        mean_lw = style.OVERLAP_DATA_LW if model_profile is not None else 1.3
        ax.plot(theta, mean_profile, c=mean_color, zorder=2, lw=mean_lw,
                label='mouse average')
    if model_profile is not None:
        # A solid persimmon center stroke over the wider stone data stroke makes
        # both nearly coincident curves continuously visible at print size.
        ax.plot(theta, model_profile, color=style.MODEL, zorder=3,
                lw=style.OVERLAP_MODEL_LW, label='generative process')
    setup_profile_axes(ax, profile_label)
    ax.set_xlabel('Δθ')

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 analysis.compute_mean_and_std_profiles_for_all_mice).

required
all_stds (ndarray, shape(n_mice, N_theta))

Per-mouse mean and std profiles (from analysis.compute_mean_and_std_profiles_for_all_mice).

required
opt_params sequence of 3 floats or None

If given, also draws a model curve from gp_opt.gen_Phi_m(*opt_params, ...).

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
def 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
    ----------
    ax_mu, ax_std : matplotlib axes
    all_mus, all_stds : ndarray, shape (n_mice, N_theta)
        Per-mouse mean and std profiles (from
        ``analysis.compute_mean_and_std_profiles_for_all_mice``).
    opt_params : sequence of 3 floats or None
        If given, also draws a model curve from
        ``gp_opt.gen_Phi_m(*opt_params, ...)``.
    """
    n_angles = all_mus.shape[1]
    mid_idx = n_angles // 2
    theta = np.arange(-mid_idx, n_angles - mid_idx) * 2 * np.pi / n_angles

    model_profiles = None
    if opt_params is not None:
        model_data = gp_opt.gen_Phi_m(*opt_params, N_samples=100000, N_theta=n_angles,
                                      device=None, normalize=True)
        model_mu, model_std = analysis.compute_mean_and_std_profiles(model_data)
        model_profiles = (np.roll(model_mu, -mid_idx), np.roll(model_std, -mid_idx))

    plot_profile(ax_mu, theta, np.roll(all_mus, -mid_idx, axis=1),
                 mean_profile=np.roll(all_mus.mean(0), -mid_idx),
                 profile_label='mean',
                 model_profile=model_profiles[0] if model_profiles else None)

    plot_profile(ax_std, theta, np.roll(all_stds, -mid_idx, axis=1),
                 mean_profile=np.roll(all_stds.mean(0), -mid_idx),
                 profile_label='std. dev.',
                 model_profile=model_profiles[1] if model_profiles else None)

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
def plot_covariance_comparison(ax, Gamma_phi_data, Gamma_phi_opt):
    """Overlay data + generative-process covariance functions.

    Parameters
    ----------
    ax : matplotlib axis
    Gamma_phi_data : ndarray, shape (N_theta,)
    Gamma_phi_opt : ndarray, shape (N_theta,)
    """
    # These curves lie almost exactly on top of each other. A solid persimmon center
    # stroke over a wider stone data stroke leaves both curves continuously visible
    # without offsetting either scientific quantity.
    theta = np.linspace(-np.pi, np.pi, 100)
    ax.plot(theta, np.roll(Gamma_phi_data, -50), lw=style.OVERLAP_DATA_LW,
            label="data",
            color=style.DATA_UNDERLAY, zorder=1)
    ax.plot(theta, np.roll(Gamma_phi_opt, -50), lw=style.OVERLAP_MODEL_LW,
            label="gen.\nprocess", color=style.MODEL, zorder=2)
    ax.legend(loc='upper right', bbox_to_anchor=[1.1, 0.9])
    ax.set_ylim(0, 4)
    ax.set_ylabel("$\\Gamma_{\\phi}(\\Delta\\theta)$")
    ax.set_xlabel("$\\Delta\\theta$")
    ax.set_xlim(-np.pi, np.pi)
    ax.set_xticks([-np.pi, 0, np.pi])
    ax.set_xticklabels(["$-\\pi$", "$0$", "$\\pi$"])

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
def plot_peak_count_comparison(ax, data_counts, model_counts):
    """Side-by-side bar chart of peak-count distributions: data vs model.

    Parameters
    ----------
    ax : matplotlib axis
    data_counts, model_counts : ndarray, shape (N_bins,)
    """
    bar_width = 0.35
    positions = np.arange(1, len(data_counts) + 1)
    ax.bar(positions - bar_width / 2 - 0.01, data_counts, bar_width,
           color=data_color, label="Data", edgecolor='white', zorder=2)
    ax.bar(positions + bar_width / 2 + 0.01, model_counts, bar_width,
           color=gen_process_color, label="Generative\nprocess", edgecolor='white', zorder=2)
    ax.set_xlim(0.5, len(data_counts) + 0.5)
    ax.set_ylim(0, 1)
    ax.set_xticks(positions)
    ax.set_yticks([0, 0.25, 0.5, 0.75, 1])
    ax.set_ylabel("frac. neurons")
    ax.set_xlabel("peak count")

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
def plot_peak_value_histograms(ax, data_peaks, model_peaks):
    """Peak-value distribution: data vs model.

    Parameters
    ----------
    ax : matplotlib axis
    data_peaks, model_peaks : ndarray
        Flat arrays of peak heights.
    """
    ax.hist(data_peaks, bins=80, range=(0, 15), density=True,
            color=data_color, label="data", clip_on=False)
    ax.hist(model_peaks, bins=80, range=(0, 15), density=True,
            color=gen_process_color, histtype='step', label="model", clip_on=False)
    ax.set_ylim(0, 1.)
    ax.set_xlim(0, 15.)
    ax.set_xticks([0, 5, 10, 15])
    ax.set_xlabel("peak height")
    ax.set_ylabel("density")

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
def plot_symmetry_histogram(ax, data_scores, model_scores, ylim=None):
    """Flip-symmetry score distribution: data vs model.

    Parameters
    ----------
    ax : matplotlib axis
    data_scores, model_scores : ndarray
        Per-curve Pearson r in [-1, 1].
    ylim : tuple or None
        Optional y-axis limits.
    """
    ax.hist(data_scores, density=True, range=(-1., 1.), bins=80,
            color=data_color, label="data")
    ax.hist(model_scores, density=True, range=(-1., 1.), bins=80,
            histtype='step', color=gen_process_color, label="model")
    if ylim:
        ax.set_ylim(ylim)
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.set_ylabel('density')
    ax.set_xlabel("$\\rho^{flip}$")

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
def plot_information_histogram(ax, data_info, model_info):
    """Bits-per-spike distribution: data vs model.

    Parameters
    ----------
    ax : matplotlib axis
    data_info, model_info : ndarray
    """
    ax.hist(data_info, density=True, range=(0, 4), bins=80,
            color=data_color, label="data")
    ax.hist(model_info, density=True, range=(0, 4), bins=80,
            histtype='step', color=gen_process_color, label="model")
    ax.set_xticks([0, 1, 2, 3, 4])
    ax.set_xlim(0, 3.5)
    ax.set_ylabel("density")
    ax.set_xlabel("$I_{HD}$")

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 analysis.compute_coms_for_all_mice.

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 null is True, which is the only branch that draws random numbers. Before 2026-08-02 the null draw used whatever global state it inherited, so the panel changed on every run, contradicting the paper's Reproducibility statement.

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
def 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
    ----------
    ax : matplotlib axis
    mouse_coms : list of ndarray
        Length-n_mice; from ``analysis.compute_coms_for_all_mice``.
    null : bool, default False
        If True, replace each mouse's COMs with a uniform-random null draw
        of the same size (for a visual significance baseline).
    color : str
        Scatter color.
    seed : int
        Seed for the global RNG, set only when ``null`` is True, which is the
        only branch that draws random numbers. Before 2026-08-02 the null draw
        used whatever global state it inherited, so the panel changed on every
        run, contradicting the paper's Reproducibility statement.
    """
    n_mice = len(mouse_coms)
    if null:
        set_global_seed(seed)
    for mouse_idx in range(n_mice):
        if null:
            coms = 2 * np.pi * np.random.rand(len(mouse_coms[mouse_idx]))
        else:
            coms = mouse_coms[mouse_idx]
        ax.scatter(coms, np.ones(len(coms)) * (mouse_idx + 1),
                   lw=0, s=2., color=color, alpha=1, clip_on=False)

    ax.set_xlim(0, 2 * np.pi)
    ax.set_ylim(0.5, n_mice + 0.5)
    ax.set_xticks([0, np.pi, 2 * np.pi])
    ax.set_xticklabels(['$0$', '$\\pi$', '$2\\pi$'])
    ax.set_ylabel('mouse index')
    ax.set_xlabel('center of mass')
    ax.set_title('random uniform' if null else 'data')

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
def 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
    ----------
    axes : ndarray of matplotlib axes, shape (N_mice_to_plot, N_subsample_sizes)
    mouse_nums : ndarray
    mouse_nums_to_plot : sequence of int
    mouse_names : ndarray
    Phi_m_data : ndarray, shape (N_curves, N_theta)
    subsample_sizes : sequence of int

    Returns
    -------
    im : matplotlib image handle (last drawn)
    """
    np.random.seed(42)
    vmax = 5

    for i, mouse_num in enumerate(mouse_nums_to_plot):
        mouse_tcs = Phi_m_data[mouse_nums == mouse_num]
        num_tcs = mouse_tcs.shape[0]
        mouse_name = mouse_names[mouse_nums == mouse_num][0]
        if i == 0:
            for j, N_sub in enumerate(subsample_sizes):
                axes[i, j].set_title("$N_{sub} =" + str(N_sub) + "$")
        axes[i, 0].set_ylabel(f'mouse\n{mouse_name}')

        for j, N_sub in enumerate(subsample_sizes):
            sub_tcs = mouse_tcs[np.random.choice(np.arange(num_tcs), replace=False, size=N_sub)]
            cov_sub = (sub_tcs.T @ sub_tcs) / N_sub
            # origin='lower' so row 0 sits at theta' = 0, matching the extent's
            # y axis. Without it imshow's default puts row 0 at the top, the image
            # renders mirrored against its own tick labels, and the true diagonal
            # draws as the anti-diagonal.
            im = axes[i, j].imshow(cov_sub, extent=[0, 2 * np.pi, 0, 2 * np.pi],
                                   origin='lower',
                                   vmin=0, vmax=vmax, cmap=style.COVARIANCE_CMAP,
                                   interpolation="nearest")

            ax = axes[i, j]
            if i == len(mouse_nums_to_plot) - 1:
                ax.set_xticks([0, np.pi, 2 * np.pi])
                ax.set_xticklabels(["$0$", "$\\pi$", "$2\\pi$"])
            else:
                ax.set_xticks([])
            if j == 0:
                ax.set_yticks([0, np.pi, 2 * np.pi])
                ax.set_yticklabels(["$0$", "$\\pi$", "$2\\pi$"])
            else:
                ax.set_yticks([])
            ax.set_aspect(1.)
            ax.text(0.5, 0, "$\\theta$", ha='center', va='bottom',
                    c='white', transform=ax.transAxes, size=6)
            ax.text(0, 0.5, "$\\theta'$", ha='left', va='center',
                    c='white', transform=ax.transAxes, size=6)
    return im

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
def plot_cov_examples(ax):
    """Wrap-Gaussian covariance functions at a few scales.

    Parameters
    ----------
    ax : matplotlib axis
    """
    scales = [0.8, 1.05, 1.25, 1.6, 2.25]
    theta = np.linspace(-np.pi, np.pi, 100)
    # Fig 4's cool palette: the sigma family takes 'ocean'.
    colors = style.sweep_colors(len(scales), 'ocean')
    for scale, color in zip(scales, colors):
        Gamma_x, _ = tc.wrapped_gaussian_cov(1, scale=scale, N_theta=len(theta))
        ax.plot(theta, np.roll(Gamma_x, len(theta) // 2), color=color, alpha=0.8)
    ax.set_xlabel(r"$\Delta \theta$")
    ax.set_ylabel(r"$\Gamma_x(\Delta \theta)$")
    ax.set_xticks([-np.pi, 0, np.pi])
    ax.set_xticklabels([r"$-\pi$", "$0$", r"$\pi$"])
    ax.set_xlim(-np.pi, np.pi)
    ax.set_ylim(0, 1.02)
    ax.set_title("covariance")

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
def plot_pre_examples(ax):
    """Sample pre-nonlinearity tuning curves at a few scales, vertically offset.

    Parameters
    ----------
    ax : matplotlib axis
    """
    scales = [0.8, 1.05, 1.25, 1.6, 2.25]
    theta = np.linspace(-np.pi, np.pi, 100)
    # Same 'ocean' ramp as panel A. The per-curve sigma labels below pick up the
    # same color, so text and curve stay in register; the ramp's capped lightness
    # is what keeps the largest-sigma label legible.
    colors = style.sweep_colors(len(scales), 'ocean')
    for i, (scale, color) in enumerate(zip(scales, colors)):
        _, Gamma_x_ft = tc.wrapped_gaussian_cov(1, scale=scale, N_theta=len(theta))
        X = tc.sample_tcs(N=10, Gamma_ft=Gamma_x_ft).T
        ax.plot(theta + np.pi, 5 * i + X[:5].T, color=color, alpha=0.8)
        # sigma labels sit just LEFT of the left spine, tilted so they fit in the
        # narrow gap without stealing the width the panel now extends into on the
        # right (see Fig. 4 layout).
        ax.text(-0.15, 5 * i + np.mean(X[:5]),
                f'$\\sigma$ = {scale:.2f}', va='center', ha='right',
                rotation=35, rotation_mode='anchor', color=color, size=6)
    ax.set_xlabel(r"$\theta$")
    ax.set_xticks([0, np.pi, 2 * np.pi])
    ax.set_xticklabels(["$0$", r"$\pi$", r"$2\pi$"])
    ax.set_xlim(0, 2 * np.pi)
    ax.set_yticks([])
    ax.set_title("samples")

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
def plot_nonlin_examples(ax):
    """Softplus nonlinearity examples at a few (bias, beta) pairs, plus Gaussian prior overlay.

    Parameters
    ----------
    ax : matplotlib axis
    """
    x_vals = np.linspace(-4, 4, 1000)
    # Beta takes the same warm 'ember' ramp used for beta in the DMFT figure,
    # while panels A and B use the cool 'ocean' ramp for sigma.
    # Each of the three thresholds b redraws the same beta-colored fan, shifted
    # horizontally; the b arrow in the figure marks that shift.
    betas = [1.3, 2, 3.5, 10]
    beta_colors = style.sweep_colors(len(betas), 'ember')
    for bias in [0, 1.5, 2.5]:
        for beta, color in zip(betas, beta_colors):
            y_vals = fn.softplus(x_vals - bias, beta=beta) * 0.07
            ax.plot(x_vals, y_vals, color=color, alpha=0.85)

    pdf = (1. / np.sqrt(2 * np.pi)) * np.exp(-x_vals**2 / 2.)
    ax.plot(x_vals, pdf, zorder=0, color='0.25', alpha=1)
    ax.fill_between(x_vals, 0, pdf, zorder=0, color="0.5", alpha=0.1)

    ax.set_xlim(-4, 4)
    ax.set_xlabel(r"$x(\theta)$")
    ax.set_ylabel(r"$\phi(\theta)$")
    ax.set_title("nonlinearity")

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 2 * soma_r < 2 * sin(pi / n_neurons).

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 style.E_COLOR / style.I_COLOR, the persimmon and petrol anchors that also define the signed-matrix map.

None
i_color str or None

Optional override colours for the E/I labels. When None (default), the labels take style.E_COLOR / style.I_COLOR, the persimmon and petrol anchors that also define the signed-matrix map.

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
def 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
    ----------
    ax : matplotlib axes
    n_neurons : int
        Number of somata on the ring.
    soma_r : float
        Soma radius in ring-radius units. Somata stay visibly separated while
        ``2 * soma_r < 2 * sin(pi / n_neurons)``.
    e_targets, i_targets : sequence of int
        Neuron offsets (both signs are drawn) receiving excitatory and
        inhibitory projections from the source neuron.
    e_color, i_color : str or None
        Optional override colours for the E/I labels. When None (default), the
        labels take ``style.E_COLOR`` / ``style.I_COLOR``, the persimmon and
        petrol anchors that also define the signed-matrix map.
    """
    r_inner = 1.0 - soma_r
    ang = np.pi / 2 - 2 * np.pi * np.arange(n_neurons) / n_neurons
    pos = np.column_stack([np.cos(ang), np.sin(ang)])

    def inner_point(p):
        u = p / np.linalg.norm(p)
        return u * r_inner, u

    src_in, _ = inner_point(pos[0])

    # Edge colours are tints of the two semantic anchors style.E_COLOR /
    # style.I_COLOR, so the whole set reads as one persimmon-to-petrol sweep.
    # Nearest-target excitation starts at full-strength persimmon and fades toward
    # the center; inhibition continues from pale petrol to full-strength petrol.
    # The sweep therefore passes through light in the middle instead of becoming
    # two disconnected fans. The larger inhibitory fan makes the Mexican-hat
    # profile intuitive and echoes the signed-matrix map in panel C.
    def _tint(hex_color, w):
        """Blend a colour toward white by fraction ``w``."""
        return tuple(np.asarray(_mcolors.to_rgb(hex_color)) * (1 - w) + w)

    e_shades = [_tint(style.E_COLOR, w) for w in np.linspace(0.0, 0.45, len(e_targets))]
    i_shades = [_tint(style.I_COLOR, w) for w in np.linspace(0.45, 0.0, len(i_targets))]

    # projections, drawn beneath the somata (thinner lines than before, so the
    # terminal discs/bars read cleanly against them)
    for offsets, shades, kind, pull in ((e_targets, e_shades, 'E', 0.22),
                                        (i_targets, i_shades, 'I', 0.52)):
        for k, col in zip(offsets, shades):
            for sgn in (+1, -1):
                p_term, u_rad = inner_point(pos[(sgn * k) % n_neurons])
                # quadratic Bezier whose control point is pulled toward the ring
                # centre, making the inward bow exact rather than sign-inferred
                ctrl = ((src_in + p_term) / 2) * (1.0 - pull)
                ax.add_patch(PathPatch(
                    Path([src_in, ctrl, p_term],
                         [Path.MOVETO, Path.CURVE3, Path.CURVE3]),
                    fill=False, edgecolor=col, lw=1.52, zorder=3))
                if kind == 'E':
                    ax.add_patch(Circle(p_term, 0.050, facecolor=col,
                                        edgecolor='none', zorder=6))
                else:
                    t = np.array([-u_rad[1], u_rad[0]])
                    ax.plot(*np.column_stack([p_term - t * 0.066,
                                              p_term + t * 0.066]),
                            color=col, lw=1.6, solid_capstyle='butt',
                            zorder=6)

    # labels take the full-strength anchors, which are also the most saturated
    # drawn edges: E the nearest excitatory shade, I the farthest inhibitory one
    e_color = e_color if e_color is not None else style.E_COLOR
    i_color = i_color if i_color is not None else style.I_COLOR

    sprite = _shaded_sphere_rgba()
    for p in pos:
        ax.imshow(sprite, extent=[p[0] - soma_r, p[0] + soma_r,
                                  p[1] - soma_r, p[1] + soma_r],
                  zorder=5, interpolation='bilinear')

    ax.text(-0.20, -0.06, 'E', color=e_color, fontsize=label_fontsize,
            fontweight='bold', ha='center', va='center', zorder=7)
    ax.text(0.20, -0.06, 'I', color=i_color, fontsize=label_fontsize,
            fontweight='bold', ha='center', va='center', zorder=7)

    # theta direction arrow, sweeping counter-clockwise up the right-hand side
    # from about 5 o'clock to about 2:45. Clock face -> degrees: 3 o'clock is 0
    # and each hour is 30 degrees, so 5:00 is -60 and 2:45 is +7.5.
    a_tail, a_head, rr = np.deg2rad(-60.0), np.deg2rad(7.5), 1.30
    arrow = FancyArrowPatch((rr * np.cos(a_tail), rr * np.sin(a_tail)),
                            (rr * np.cos(a_head), rr * np.sin(a_head)),
                            connectionstyle='arc3,rad=0.26', arrowstyle='-|>',
                            mutation_scale=15, color='black', lw=1.6,
                            shrinkA=0, shrinkB=0)
    arrow.set_joinstyle('miter')   # sharp head, not matplotlib's rounded default
    arrow.set_capstyle('butt')
    ax.add_patch(arrow)
    a_mid, r_lab = (a_tail + a_head) / 2, 1.56
    ax.text(r_lab * np.cos(a_mid), r_lab * np.sin(a_mid), r"$\theta$",
            fontsize=theta_fontsize, ha='center', va='center')

    # tight bounds: the ring spans +/-1.14, so only the theta arrow and its label
    # need extra room, and only on the right
    # y-window is exactly the ring's outer diameter, so the ring fills the panel
    # height; that lets the caller match it to the heatmap's height in Fig. 2.
    lim = 1.0 + soma_r
    ax.set_xlim(-lim - 0.02, lim + 0.46)   # extra room on the right for theta
    ax.set_ylim(-lim, lim)
    ax.set_aspect('equal')
    ax.axis('off')

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
def 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
    ----------
    ax : matplotlib axes
    n_theta : int
        Grid resolution along each angular axis.
    width : float
        Gaussian width of the excitatory lobe, in radians.
    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.
    """
    t = np.linspace(0, 2 * np.pi, n_theta)
    dt = np.abs(t[:, None] - t[None, :])
    dt = np.minimum(dt, 2 * np.pi - dt)
    J = np.exp(-(dt / width) ** 2) - offset
    lim = np.abs(J).max()
    # origin='lower' so row 0 sits at theta' = 0, matching the extent's y axis and
    # putting the excitatory band on the true diagonal rather than the anti-diagonal.
    ax.imshow(J, cmap=style.DIVERGING_CMAP, vmin=-lim, vmax=lim,
              extent=[0, 2 * np.pi, 0, 2 * np.pi], aspect=1.0, origin='lower')
    ax.set_xticks([0, np.pi, 2 * np.pi])
    ax.set_xticklabels([r"$0$", r"$\pi$", r"$2\pi$"])
    ax.set_yticks([0, np.pi, 2 * np.pi])
    ax.set_yticklabels([r"$0$", r"$\pi$", r"$2\pi$"])
    ax.set_title(r"$J(\theta-\theta')$", fontsize=title_fontsize)
    ax.set_xlabel(r"$\theta$")
    ax.set_ylabel(r"$\theta'$", rotation=0, va='center')

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 step-th neuron's tuning curve.

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
def 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
    ----------
    ax : matplotlib axes
    n_neurons : int
        Number of neurons spanning the ring.
    step : int
        Plot every ``step``-th neuron's tuning curve.
    width2 : float
        Squared Gaussian width, in neuron-index units.
    """
    idx = np.arange(n_neurons)
    for i in range(0, n_neurons, step):
        ax.plot(idx, np.exp(-(idx - i) ** 2 / width2),
                color=str(0.75 * (1 - i / n_neurons)), clip_on=False, lw=1.5)
    ax.set_xticks([0, n_neurons // 2 - 1, n_neurons - 1])
    ax.set_xticklabels([r"$0$", r"$\pi$", r"$2\pi$"])
    ax.set_yticks([])
    ax.set_ylabel("firing rate")
    ax.set_xlabel(r"head direction $\theta$")
    ax.set_xlim(0, n_neurons - 1)
    ax.set_ylim(0, 1)

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
def 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
    ----------
    ax : matplotlib axes
    box_color, edge_color : str
        Fill and outline of the boxes.
    fontsize : float
        Box label size.
    arrow_label_fontsize : float
        Size of the N -> infinity label on the synth -> dmft arrow.
    box_w, box_h : float
        Box size in axes fractions.
    lw : float
        Outline and arrow width.
    """
    # columns are unevenly spaced so that synth -> dmft, the one arrow carrying
    # a label, gets the longer run and the label is not crowded by either box
    x1, x2, x3 = 0.133, 0.473, 0.867           # column centres
    y1, y2 = 0.790, 0.210                      # row centres

    nodes = {
        'data':      (x1, y1, 'Neural data'),
        'ddrnn':     (x2, y1, 'Data-derived\nRNN'),
        'gen':       (x1, y2, 'Generative\nprocess'),
        'synth':     (x2, y2, 'Synthetic\ndata-derived\nRNN'),
        'dmft':      (x3, y2, 'Dynamical\nmean-field\ntheory'),
    }
    for x, y, label in nodes.values():
        ax.add_patch(FancyBboxPatch((x - box_w / 2, y - box_h / 2), box_w, box_h,
                                    boxstyle='round,pad=0,rounding_size=0.028',
                                    facecolor=box_color, edgecolor=edge_color,
                                    linewidth=lw, zorder=2))
        ax.text(x, y, label, ha='center', va='center', fontsize=fontsize,
                zorder=3, linespacing=1.25)

    def arrow(a, b, label=None):
        (xa, ya, _), (xb, yb, _) = nodes[a], nodes[b]
        if abs(ya - yb) < 1e-9:                       # horizontal
            start, end = (xa + box_w / 2, ya), (xb - box_w / 2, yb)
        else:                                          # vertical
            sgn = -1 if yb < ya else 1
            start, end = (xa, ya + sgn * box_h / 2), (xb, yb - sgn * box_h / 2)
        p = FancyArrowPatch(start, end, arrowstyle='-|>', mutation_scale=8,
                            color=edge_color, lw=lw, shrinkA=0, shrinkB=0,
                            zorder=1)
        p.set_joinstyle('miter')
        ax.add_patch(p)
        if label:
            if abs(ya - yb) < 1e-9:            # horizontal arrow: label above it
                # nudge the label a hair left of the raw gap midpoint: the mathtext
                # advance width centres the N->infinity glyph run slightly right of
                # its ink, so this lands it visually centred between the two boxes.
                ax.text((start[0] + end[0]) / 2 - 0.0015, ya + 0.050, label,
                        ha='center', va='bottom', fontsize=arrow_label_fontsize)
            else:                              # vertical arrow: label beside it
                ax.text(xa + 0.035, (start[1] + end[1]) / 2, label,
                        ha='left', va='center', fontsize=arrow_label_fontsize)

    arrow('data', 'ddrnn')
    arrow('data', 'gen')
    arrow('gen', 'synth')
    arrow('synth', 'dmft', r"$N\!\to\!\infty$")

    ax.set_xlim(0, 1)
    ax.set_ylim(0, 1)
    ax.axis('off')

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
def 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
    ----------
    ax : matplotlib axes
    aspect : float
        Panel width/height, so the drawing fills the panel without distortion.
    ordered, disordered, 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.
    seed : int
        Seeds the disordered example curves (determinism).
    """
    # Orthographic view angles (azimuth A, elevation E) shared by the ring curve
    # and the axis gizmo, so the gizmo honestly labels the ring's orientation.
    A_view, E_view = np.deg2rad(50.0), np.deg2rad(28.0)

    def project(X, Y, Z, A=A_view, E=E_view):
        # Orthographic projection of a 3D point onto screen coords (u, v).
        u = -np.sin(A) * X + np.cos(A) * Y
        v = (-np.cos(A) * np.sin(E) * X - np.sin(A) * np.sin(E) * Y
             + np.cos(E) * Z)
        return u, v

    def ring_xy(n=900):
        # True orthographic projection of the embedded circle
        # (X, Y, Z) = (sin theta, cos theta, cos 2theta): a circle carrying a
        # second harmonic, so the projected loop bobs up and down twice and
        # crosses itself, reading as a warped ring rather than a flat circle.
        t = np.linspace(0, 2 * np.pi, n)
        return project(np.sin(t), np.cos(t), np.cos(2 * t))

    def ordered_curve(shift, x):
        return np.exp(-((((x - shift + 0.5) % 1.0) - 0.5) / 0.14) ** 2)

    def disordered_curve(rng, x):
        y = np.zeros_like(x)
        for k in range(1, 6):
            y += rng.normal() / k * np.sin(2 * np.pi * k * x + rng.uniform(0, 2 * np.pi))
        y = y - y.min()
        return y / (y.max() + 1e-9)

    ax.set_xlim(0, aspect); ax.set_ylim(0, 1); ax.set_aspect("equal"); ax.axis("off")
    cxmid = aspect / 2

    # ---- geometric ring, top (label fully above it) ----
    # The ring is a true orthographic projection of the embedded circle
    # (sin, cos, cos 2theta); it carries a soft offset drop shadow so the warped
    # loop reads as a 3D curve. Centered in the panel; the axis gizmo that names
    # the projection sits off to the lower-left.
    ring_h, cy = 0.235, 0.760
    rx, ry = ring_xy()
    rx = rx - rx.mean(); ry = ry - ry.mean()
    s = ring_h / (ry.max() - ry.min())
    cx_ring = cxmid
    for k, (dx, dy, a) in enumerate([(0.006, -0.010, 0.18), (0.012, -0.020, 0.12)]):
        ax.plot(cx_ring + rx * s + dx, cy + ry * s + dy, color="0.35", lw=2.4,
                solid_capstyle="round", solid_joinstyle="round", zorder=2, alpha=a)
    ax.plot(cx_ring + rx * s, cy + ry * s, color="black", lw=2.0,
            solid_capstyle="round", solid_joinstyle="round", zorder=3)
    ax.text(cxmid, 0.998, "geometric ring\n(circular symmetry)", fontsize=6.6,
            ha="center", va="top", linespacing=1.2)

    # ---- axis gizmo: the same projection's three coordinate axes, drawn small
    #      off to the lower-left so the reader can see how the circle is embedded
    #      (a circle in x-y carrying a second harmonic along z = cos 2theta). ----
    gx, gy = cx_ring + rx.min() * s - 0.082, cy - 0.080
    glen = 0.058
    axis_specs = [
        ((-np.sin(A_view), -np.cos(A_view) * np.sin(E_view)), r"$\sin\theta$"),
        (( np.cos(A_view), -np.sin(A_view) * np.sin(E_view)), r"$\cos\theta$"),
        (( 0.0,             np.cos(E_view)),                  r"$\cos 2\theta$"),
    ]
    y_lab = gy - 0.042          # sin/cos labels share this height, just below the arrows
    for (dxu, dyv), lab in axis_specs:
        tipx, tipy = gx + dxu * glen, gy + dyv * glen
        ax.add_patch(FancyArrowPatch((gx, gy), (tipx, tipy), arrowstyle="-|>",
                     mutation_scale=6, color="0.35", lw=0.9,
                     joinstyle="miter", capstyle="butt",
                     shrinkA=0, shrinkB=0, zorder=4))
        if lab == r"$\cos 2\theta$":
            lx, ly = tipx + dxu * 0.024, tipy + dyv * 0.024   # above the up-arrow
        elif lab == r"$\sin\theta$":
            lx, ly = tipx - 0.011, y_lab                       # left, shared height
        else:                                                  # cos theta
            lx, ly = tipx + 0.009, y_lab                       # right, shared height
        ax.text(lx, ly, lab, fontsize=5.0, ha="center", va="center",
                color="0.25", zorder=4)

    # ---- two tuning columns (fill the panel down to the bottom edge) ----
    box_w, box_h = 0.30, 0.10
    xL, xR = 0.006, aspect - box_w - 0.006
    row_tops = [0.452, 0.300, 0.120]        # top edge of each neuron box
    theta_y = 0.005
    vdots_y = (row_tops[1] - box_h + row_tops[2]) / 2   # between neuron 2 and N

    def column(x0, curves, title, tcolor, inner_x):
        labels = ["neuron 1", "neuron 2", "neuron $N$"]
        lab_x = x0 + 0.035 * box_w          # left-aligned label inside box (both cols)
        inners = []
        for cv, lab, ytop_i in zip(curves, labels, row_tops):
            y0 = ytop_i - box_h
            ax.add_patch(Rectangle((x0, y0), box_w, box_h, facecolor=grey,
                                   edgecolor="none", zorder=1))
            # curve confined to the lower part so it never touches the top-left label
            xx = np.linspace(0, 1, 200)
            ax.plot(x0 + xx * box_w, y0 + 0.10 * box_h + cv(xx) * 0.48 * box_h,
                    color="black", lw=1.05, solid_capstyle="round", zorder=3)
            ax.text(lab_x, y0 + box_h - 0.06 * box_h, lab, fontsize=6.0,
                    ha="left", va="top", zorder=4)
            inners.append((inner_x, y0 + box_h / 2))
        ax.text(x0 + box_w / 2, vdots_y, r"$\vdots$", fontsize=8,
                ha="center", va="center")
        ax.text(x0 + box_w / 2, theta_y, r"$\theta$", fontsize=8,
                ha="center", va="top")
        # Regular weight, matching the "geometric ring" caption. The BOLD labels
        # are reserved for the two embeddings, which name the operation; these
        # name its output and should not compete with it.
        ax.text(x0 + box_w / 2, row_tops[0] + 0.022, title, fontsize=6.6,
                ha="center", va="bottom", color=tcolor)
        return inners

    ordered_fns = [lambda x, sh=sh: ordered_curve(sh, x) for sh in (0.30, 0.46, 0.74)]
    disordered_fns = [lambda x, r=np.random.default_rng(seed + sd): disordered_curve(r, x)
                  for sd in (1, 4, 7)]
    iL = column(xL, ordered_fns, "ordered tuning", ordered, xL + box_w + 0.008)
    iR = column(xR, disordered_fns, "disordered tuning", disordered, xR - 0.008)

    # ---- arrow fans: shafts leave a short base at the ring bottom and bow inward
    #      toward the panel centre, the lower/longer arrows bowing the most ----
    def fan(bx, targets, color, sign, rads):
        oy = cy - ring_h * 0.52
        for j, (tgt, rad) in enumerate(zip(targets, rads)):
            # every shaft in a fan starts at the exact same base point
            # miter join + butt cap: a SHARP arrowhead. matplotlib's default
            # rounded join blunts the tip into a little dome.
            ax.add_patch(FancyArrowPatch((bx, oy), tgt, arrowstyle="-|>",
                         mutation_scale=9, color=color, lw=1.3,
                         joinstyle="miter", capstyle="butt",
                         shrinkA=2, shrinkB=2,
                         connectionstyle="arc3,rad={}".format(rad), zorder=2))
    bows = [0.03, 0.08, 0.15]               # top least, bottom most
    fan(cxmid - 0.034, iL, ordered, -1, [-b for b in bows])
    fan(cxmid + 0.034, iR, disordered, +1, bows)

    ax.text(xL + box_w / 2, 0.560, "Fourier\nembedding", fontsize=6.2, color=ordered,
            ha="center", va="center", fontweight="bold", linespacing=1.05)
    ax.text(xR + box_w / 2, 0.560, "disordered\nembedding", fontsize=6.2, color=disordered,
            ha="center", va="center", fontweight="bold", linespacing=1.05)

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
def sweep_cmap(kind='slate'):
    """The colormap for an ordered-parameter family of curves. See ``_SWEEP_HUES``."""
    return SWEEP_CMAPS[kind]

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
def 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.
    """
    t = np.linspace(1, 0, n) if reverse else np.linspace(0, 1, n)
    return SWEEP_CMAPS[kind](t)

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
def field_cmap(kind='ice'):
    """The colormap for a 2-D scalar field, keyed by quantity. See ``_FIELD_HUES``."""
    return FIELD_CMAPS[kind]

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
def 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.
    """
    orient = 'vertical' if side in ('right', 'left') else 'horizontal'
    cax = _make_axes_locatable(ax).append_axes(side, size=CBAR_SIZE, pad=CBAR_GAP)
    cbar = fig.colorbar(mappable, cax=cax, orientation=orient)
    if ticks is not None:
        cbar.set_ticks(ticks)
    if ticklabels is not None:
        cbar.set_ticklabels(ticklabels)
    if label is not None:
        cbar.set_label(label)
    cbar.outline.set_linewidth(0.5)
    cbar.ax.tick_params(width=0.5)
    return cbar

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
def 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.
    """
    cbar = fig.colorbar(mappable, ax=ax, orientation=orientation,
                        fraction=CBAR_FRACTION, pad=CBAR_PAD,
                        aspect=CBAR_ASPECT, **kw)
    if ticks is not None:
        cbar.set_ticks(ticks)
    if ticklabels is not None:
        cbar.set_ticklabels(ticklabels)
    if label is not None:
        cbar.set_label(label)
    cbar.outline.set_linewidth(0.5)
    return cbar

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
def 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.
    """
    ax.text(x, y, letter, transform=ax.transAxes, fontsize=8,
            fontweight='bold', ha=ha, va=va, **kw)

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 str.format spec. Default "{:.2f}".

'{:.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
def 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
    ----------
    value : float
        Number to format.
    fmt : str
        Python ``str.format`` spec. Default ``"{:.2f}"``.

    Returns
    -------
    s : str
        Formatted string with the leading minus stripped if it represents a
        rounded zero; otherwise the unchanged format output.
    """
    s = fmt.format(value)
    if s.startswith('-'):
        try:
            if float(s) == 0:
                return s[1:]
        except ValueError:
            pass
    return s

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
def set_global_seed(seed):
    """Seed numpy, torch, and torch.cuda (if available) for deterministic reproducibility."""
    np.random.seed(seed)
    try:
        import torch
        torch.manual_seed(seed)
        if torch.cuda.is_available():
            torch.cuda.manual_seed_all(seed)
    except ImportError:
        pass