Skip to content

API Reference

Here you can find detailed documentation for the public Python API of the lqg package.

Core Systems & LQG Specification

lqg.system.System

An agent acting in an environment, both described as linear-Gaussian systems.

The environment (dynamics) evolves as

x[t+1] = A x[t] + B u[t] + V eps[t],    eps[t] ~ N(0, I)
y[t+1] = F x[t+1] + W eta[t],         eta[t] ~ N(0, I)

The agent (actor) has its own internal model of the environment, with its own matrices A, B, F, V, W and a quadratic cost (Q, R). It computes optimal control gains for that cost (LQR) and tracks its belief xhat about the state with a Kalman filter. Its actions u[t] = L[t] xhat[t] + k[t] then drive the true dynamics.

When the agent's model matches the environment, use LQG. Keeping the two separate allows models of agents with subjective or mismatched beliefs about the environment.

Shapes in this class use these names:

  • n: number of trials
  • T: number of time steps, so trajectories have T + 1 states
  • xdim: state dimensionality of the environment
  • bdim: state dimensionality of the agent's internal model
  • ydim: observation dimensionality
  • udim: action dimensionality

Parameters:

Name Type Description Default
actor LQGSpec

the agent's internal model and cost function, e.g. from Actor.

required
dynamics LQGSpec

the true dynamics of the environment, e.g. from Dynamics. Its cost terms are ignored.

required
Source code in lqg/system.py
 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
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
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
406
407
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
459
460
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
521
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
class System:
    """An agent acting in an environment, both described as linear-Gaussian systems.

    The environment (``dynamics``) evolves as

    ```
    x[t+1] = A x[t] + B u[t] + V eps[t],    eps[t] ~ N(0, I)
    y[t+1] = F x[t+1] + W eta[t],         eta[t] ~ N(0, I)
    ```

    The agent (``actor``) has its own internal model of the environment, with
    its own matrices ``A, B, F, V, W`` and a quadratic cost (``Q, R``). It
    computes optimal control gains for that cost (LQR) and tracks its belief
    ``xhat`` about the state with a Kalman filter. Its actions
    ``u[t] = L[t] xhat[t] + k[t]`` then drive the true dynamics.

    When the agent's model matches the environment, use [LQG][lqg.system.LQG].
    Keeping the two separate allows models of agents with subjective or
    mismatched beliefs about the environment.

    Shapes in this class use these names:

    - ``n``: number of trials
    - ``T``: number of time steps, so trajectories have ``T + 1`` states
    - ``xdim``: state dimensionality of the environment
    - ``bdim``: state dimensionality of the agent's internal model
    - ``ydim``: observation dimensionality
    - ``udim``: action dimensionality

    Args:
        actor (LQGSpec): the agent's internal model and cost function, e.g. from
            [Actor][lqg.system.Actor].
        dynamics (LQGSpec): the true dynamics of the environment, e.g. from
            [Dynamics][lqg.system.Dynamics]. Its cost terms are ignored.
    """

    def __init__(self, actor: LQGSpec, dynamics: LQGSpec):
        self.actor = actor
        self.dynamics = dynamics

    @property
    def T(self):
        """Length of trajectory

        Returns:
            int: number of time steps
        """
        return self.dynamics.A.shape[0]

    @property
    def xdim(self):
        """State dimensionality

        Returns:
            int: dimensionality of state
        """
        return self.dynamics.A.shape[1]

    @property
    def ydim(self):
        """Observation dimensionality

        Returns:
            int: dimensionality of observation
        """
        return self.dynamics.F.shape[1]

    @property
    def bdim(self):
        """Belief dimensionality

        Returns:
            int: dimensionality of belief
        """
        return self.actor.A.shape[1]

    @property
    def udim(self):
        """Action dimensionality

        Returns:
            int: dimensionality of action
        """
        return self.dynamics.B.shape[2]

    def simulate(
        self, rng_key, n=1, x0=None, xhat0=None, Sigma0=None, return_all=False
    ):
        """Simulate n trials

        Args:
            rng_key (jax.random.PRNGKey): random number generator key
            n (int): number of trials
            x0 (jnp.array, optional): initial state of shape (xdim,). Defaults
                to zeros.
            xhat0 (jnp.array, optional): initial belief of shape (bdim,).
                Defaults to zeros.
            Sigma0 (jnp.array, optional): initial belief covariance of shape
                (bdim, bdim), used to compute the Kalman gains. Defaults to
                ``V[0] @ V[0].T`` of the actor.
            return_all (bool): return beliefs, observations and actions as well

        Returns:
            jnp.array or tuple: If ``return_all`` is False, the simulated states
                ``x`` of shape (n, T+1, xdim), including the initial state.
                Otherwise, a tuple ``(x, xhat, y, u)`` with the states, the
                beliefs of shape (n, T+1, bdim), the observations ``y[1:]`` of
                shape (n, T, ydim) and the actions of shape (n, T, udim).
        """

        Sigma0 = self.actor.V[0] @ self.actor.V[0].T if Sigma0 is None else Sigma0

        gains = lqr.backward(self.actor)
        K = kf.forward(self.actor, Sigma0=Sigma0)

        def simulate_trial(rng_key, x0=None, xhat0=None):
            """Simulate a single trial

            Args:
                rng_key (jax.random.PRNGKey): random number generator key
                T (int): number of time steps
                x0 (jnp.array): initial state
                xhat0 (jnp.array): initial belief

            Returns:
                jnp.array, jnp.array, jnp.array, jnp.array: x (states), x_hat (estimates), y, u
            """

            x0 = jnp.zeros(self.xdim) if x0 is None else x0
            xhat0 = jnp.zeros(self.bdim) if xhat0 is None else xhat0

            # generate standard normal noise terms
            rng_key, subkey = random.split(rng_key)
            epsilon = random.normal(subkey, shape=(self.T, self.xdim))
            rng_key, subkey = random.split(rng_key)
            eta = random.normal(subkey, shape=(self.T, self.ydim))

            def loop(carry, t):
                x, x_hat = carry

                # compute control based on agent's current belief
                u = gains.L[t] @ x_hat + gains.k[t]

                # apply dynamics
                x = (
                    self.dynamics.A[t] @ x
                    + self.dynamics.B[t] @ u
                    + self.dynamics.V[t] @ epsilon[t]
                )

                # generate observation
                y = self.dynamics.F[t] @ x + self.dynamics.W[t] @ eta[t]

                # update agent's belief
                x_pred = self.actor.A[t] @ x_hat + self.actor.B[t] @ u
                x_hat = x_pred + K[t] @ (y - self.actor.F[t] @ x_pred)

                return (x, x_hat), (x, x_hat, y, u)

            _, (x, x_hat, y, u) = scan(loop, (x0, xhat0), jnp.arange(self.T))

            return (jnp.vstack([x0, x]), jnp.vstack([xhat0, x_hat]), y, u)

        # simulate n trials
        x, x_hat, y, u = vmap(lambda key: simulate_trial(key, x0=x0, xhat0=xhat0))(
            random.split(rng_key, num=n)
        )

        if return_all:
            return x, x_hat, y, u
        else:
            return x

    def simulate_actions(
        self, x, action_dim_mask, rng_key, xhat0=None, Sigma0=None, return_all=False
    ):
        """Simulate cursor actions given pre-existing experimental target trajectories.

        Args:
        The target dimensions of the state are taken from the data at each time
        step, while the dimensions selected by ``action_dim_mask`` are simulated
        from the agent's actions.

        Args:
            x (jnp.array): Experimental state data of shape (n, T+1, xdim)
            action_dim_mask (jnp.array): Boolean mask of shape (xdim,) that
                selects the state dimensions to simulate (e.g. cursor position)
            rng_key (jax.random.PRNGKey): Random number generator key
            xhat0 (jnp.array, optional): Initial belief of shape (bdim,).
                Defaults to zeros.
            Sigma0 (jnp.array, optional): initial belief covariance of shape
                (bdim, bdim). Defaults to ``V[0] @ V[0].T`` of the actor.
            return_all (bool): Whether to return beliefs, observations and
                actions as well

        Returns:
            jnp.array or tuple: If ``return_all`` is False, the states of shape
                (n, T+1, xdim). Otherwise, a tuple ``(x, xhat, y, u)`` with the
                same shapes as in [simulate][lqg.system.System.simulate].
        """
        Sigma0 = self.actor.V[0] @ self.actor.V[0].T if Sigma0 is None else Sigma0

        gains = lqr.backward(self.actor)
        K = kf.forward(self.actor, Sigma0=Sigma0)

        def simulate_trial_actions(x_single, action_dim_mask, rng_key, xhat0=None):
            # 1. Initial state at t=0 comes directly from experimental data x_single[0]
            x0 = x_single[0]
            xhat0 = jnp.zeros(self.bdim) if xhat0 is None else xhat0

            # Generate standard normal noise terms
            rng_key, subkey = random.split(rng_key)
            epsilon = random.normal(subkey, shape=(self.T, self.xdim))
            rng_key, subkey = random.split(rng_key)
            eta = random.normal(subkey, shape=(self.T, self.ydim))

            def loop(carry, t):
                x_curr, x_hat = carry  # x_curr is a 1D state vector of shape (xdim,)

                # Compute control based on agent's current belief
                u = gains.L[t] @ x_hat + gains.k[t]

                # Apply full dynamics transition: A[t] @ x_curr carries state & physics forward
                x_next_sim = (
                    self.dynamics.A[t] @ x_curr
                    + self.dynamics.B[t] @ u
                    + self.dynamics.V[t] @ epsilon[t]
                )

                # Splicing: Take fixed experimental target state for t+1,
                # but inject newly simulated cursor/action states
                x_next = (
                    x_single[t + 1].at[action_dim_mask].set(x_next_sim[action_dim_mask])
                )

                # Generate observation based on updated state x_next
                y = self.dynamics.F[t] @ x_next + self.dynamics.W[t] @ eta[t]

                # Update agent's belief
                x_pred = self.actor.A[t] @ x_hat + self.actor.B[t] @ u
                x_hat = x_pred + K[t] @ (y - self.actor.F[t] @ x_pred)

                return (x_next, x_hat), (x_next, x_hat, y, u)

            # Run scan across T time steps
            _, (x_steps, x_hat, y, u) = scan(loop, (x0, xhat0), jnp.arange(self.T))

            # Combine initial state x0 with simulated sequence -> shape (T+1, xdim)
            x_full = jnp.vstack([x0, x_steps])

            return x_full, jnp.vstack([xhat0, x_hat]), y, u

        # Map across trials and random keys
        keys = random.split(rng_key, num=x.shape[0])
        x_sim, x_hat, y, u = vmap(
            lambda x_i, key: simulate_trial_actions(
                x_i, action_dim_mask, key, xhat0=xhat0
            )
        )(x, keys)

        if return_all:
            return x_sim, x_hat, y, u
        else:
            return x_sim

    def conditional_moments(self, x, x0=None, xhat0=None, Sigma0=None):
        """Moments of the joint state and belief, given past observed states.

        For each time step ``t``, computes the mean and covariance of the
        Gaussian ``p(x[t+1], xhat[t+1] | x[0:t+1])`` for a single trial, where
        the agent's belief ``xhat`` is marginalized out over the past.

        Args:
            x (jnp.array): one trial of observed states, of shape (T+1, d). If
                ``d < xdim``, the first ``d`` state dimensions are observed.
            x0 (jnp.array, optional): initial state. Defaults to ``x[0]``.
            xhat0 (jnp.array, optional): initial belief. Defaults to ``x0``.
            Sigma0 (jnp.array, optional): initial belief covariance of shape
                (bdim, bdim), used to compute the Kalman gains. Defaults to
                ``V[0] @ V[0].T`` of the actor.

        Returns:
            tuple: ``(mu, Sigma)``, the means of shape (T, xdim + bdim) and the
                covariances of shape (T, xdim + bdim, xdim + bdim). The first
                ``xdim`` entries are the state, the rest the belief.
        """
        T, obs_dim = x.shape
        xdim = self.dynamics.A.shape[1]
        bdim = self.actor.A.shape[1]

        # compute control and estimator gains
        gains = lqr.backward(self.actor)
        K = kf.forward(
            self.actor,
            Sigma0=self.actor.V[0] @ self.actor.V[0].T if Sigma0 is None else Sigma0,
        )

        # set up joint dynamical system for state and belief
        # p(x_t, xhat_t | x_{t-1}, xhat_{t-1})

        # joint dynamics
        F = jnp.concatenate(
            [
                jnp.concatenate([self.dynamics.A, self.dynamics.B @ gains.L], axis=-1),
                jnp.concatenate(
                    [
                        K @ self.dynamics.F @ self.dynamics.A,
                        self.actor.A
                        + self.actor.B @ gains.L
                        - K @ self.actor.F @ self.actor.A
                        + K
                        @ (
                            self.dynamics.F @ self.dynamics.B
                            - self.actor.F @ self.actor.B
                        )
                        @ gains.L,
                    ],
                    axis=-1,
                ),
            ],
            axis=-2,
        )

        # joint noise covariance Cholesky factor
        G = jnp.concatenate(
            [
                jnp.concatenate(
                    [
                        self.dynamics.V,
                        jnp.zeros(
                            (self.T, self.dynamics.A.shape[1], self.dynamics.W.shape[2])
                        ),
                    ],
                    axis=-1,
                ),
                jnp.concatenate(
                    [K @ self.dynamics.F @ self.dynamics.V, K @ self.dynamics.W],
                    axis=-1,
                ),
            ],
            axis=-2,
        )

        # initialize p(x_t, xhat_t | x_{1:t-1})
        if x0 is None:
            x0 = x[0]
        if xhat0 is None:
            xhat0 = x0
        mu0 = jnp.hstack(
            [x0, jnp.zeros(xdim - x0.shape[0]), xhat0, jnp.zeros(bdim - xhat0.shape[0])]
        )
        Sigma0 = G[0] @ G[0].T

        def scan_fn(carry, step):
            mu, Sigma = carry
            F, G, x = step

            # conditioning and marginalizing
            mu = F @ mu + (F @ Sigma)[:, :obs_dim] @ jnp.linalg.solve(
                Sigma[:obs_dim, :obs_dim], x - mu[:obs_dim]
            )

            Sigma = (
                F @ Sigma @ F.T
                + G @ G.T
                - (F @ Sigma)[:, :obs_dim]
                @ jnp.linalg.solve(
                    Sigma[:obs_dim, :obs_dim], (Sigma @ F.T)[:obs_dim, :]
                )
            )
            return (mu, Sigma), (mu, Sigma)

        _, (mu, Sigma) = scan(scan_fn, (mu0, Sigma0), (F, G, x[:-1]))
        # return jnp.vstack((mu0, mu)), jnp.vstack((Sigma0[jnp.newaxis], Sigma))
        return mu, Sigma

    def conditional_distribution(self, x, x0=None, xhat0=None, Sigma0=None):
        """Distribution of each state given all previous states.

        This is ``p(x[t+1] | x[0:t+1])`` for every trial and time step, with the
        agent's beliefs marginalized out. See
        [conditional_moments][lqg.system.System.conditional_moments].

        Args:
            x (jnp.array): observed states of shape (n, T+1, d)
            x0 (jnp.array, optional): initial states of shape (n, d). Defaults
                to ``x[:, 0]``.
            xhat0 (jnp.array, optional): initial beliefs of shape (n, bdim).
                Defaults to ``x0``.
            Sigma0 (jnp.array, optional): initial belief covariance of shape
                (bdim, bdim)

        Returns:
            numpyro.distributions.Distribution: a multivariate normal with batch
                shape (n,) and event shape (T, d), to be evaluated on
                ``x[:, 1:]``.
        """
        n, T, d = x.shape

        # compute p(x_{t+1}, xhat_{t+1} | x_{1:t})
        mu, Sigma = vmap(self.conditional_moments, in_axes=(0, 0, 0, None))(
            x, x0, xhat0, Sigma0
        )

        # marginalize out xhat by using only those entries of mu and Sigma that correspond to x
        return dist.MultivariateNormal(mu[:, :, :d], Sigma[:, :, :d, :d]).to_event(1)

    def log_likelihood(self, x, x0=None, xhat0=None, Sigma0=None):
        """Log likelihood of observed trajectories.

        Evaluates ``log p(x[1:] | x[0])``, factorized over time steps as in
        [conditional_distribution][lqg.system.System.conditional_distribution].

        Args:
            x (jnp.array): observed states of shape (n, T+1, d)
            x0 (jnp.array, optional): initial states of shape (n, d)
            xhat0 (jnp.array, optional): initial beliefs of shape (n, bdim)
            Sigma0 (jnp.array, optional): initial belief covariance of shape
                (bdim, bdim)

        Returns:
            jnp.array: log likelihood of each trial, of shape (n,)
        """
        return self.conditional_distribution(
            x, x0=x0, xhat0=xhat0, Sigma0=Sigma0
        ).log_prob(x[:, 1:])

    def belief_tracking_distribution(self, x, Sigma0=None):
        """Distribution of the agent's beliefs given the observed states.

        This is ``p(xhat[t+1] | x[0:t+1])`` for every trial and time step.

        Args:
            x (jnp.array): observed states of shape (n, T+1, xdim)
            Sigma0 (jnp.array, optional): initial belief covariance of shape
                (bdim, bdim)

        Returns:
            numpyro.distributions.MultivariateNormal: a distribution with batch
                shape (n, T) and event shape (bdim,)
        """
        d = self.xdim

        # compute p(x_{t+1}, xhat_{t+1} | x_{1:t})
        mu, Sigma = vmap(
            lambda xi: self.conditional_moments(xi, Sigma0=Sigma0), in_axes=0
        )(x)

        # return those elements of mu and Sigma that correspond to xhat
        return dist.MultivariateNormal(mu[:, :, d:], Sigma[:, :, d:, d:])

    def to_numpyro(self, Sigma0=None, xdim=None):
        """Wrap the system as a numpyro distribution over trajectories.

        The distribution can be used with ``numpyro.sample`` in a model, e.g.
        ``numpyro.sample("x", system.to_numpyro(), obs=x)``.

        Args:
            Sigma0 (jnp.array, optional): initial belief covariance of shape
                (bdim, bdim)
            xdim (int, optional): number of observed state dimensions. Defaults
                to all of them.

        Returns:
            numpyro.distributions.Distribution: a distribution with event shape
                (T+1, xdim)
        """
        return NumpyroLQG(self, Sigma0=Sigma0, xdim=xdim)

    def _repr_latex_(self) -> str:
        """
        Produces a Latex representation of the system.
        Can be used in jupyter notebooks via `display(system)`.

        Returns:
            str: Latex representation.
        """

        def bmatrix(arr: Array) -> str:
            """
            Produces a Latex bmatrix string representation of a given array.
            Adapted from https://stackoverflow.com/a/17131750.

            Args:
                arr (Array): Array to represent as bmatrix.

            Returns:
                str: Latex bmatrix representation.
            """
            assert jnp.ndim(arr) == 2

            lines = (
                jnp.array_str(arr, max_line_width=jnp.inf, precision=4)
                .replace("[", "")
                .replace("]", "")
                .splitlines()
            )

            rows = ["\\begin{bmatrix}"]
            rows += [" " + " & ".join(line.split()) + "\\\\" for line in lines]
            rows += ["\\end{bmatrix}"]
            bmatrix = "".join(rows)
            return bmatrix

        mats_dynamics = [
            self.dynamics.A,
            self.dynamics.B,
            self.dynamics.F,
            self.dynamics.V,
            self.dynamics.W,
            # self.dynamics.Q,
            # self.dynamics.R
        ]
        mats_actor = [
            self.actor.A,
            self.actor.B,
            self.actor.F,
            self.actor.V,
            self.actor.W,
            self.actor.Q,
            self.actor.R,
        ]
        mat_names = ["A", "B", "F", "V", "W", "Q", "R"]

        latex_str = "\\begin{align*} \\text{Dynamics:}"
        for mat, mat_name in zip(mats_dynamics, mat_names):
            latex_str += f" &&{mat_name} = {bmatrix(mat[0])}"

        latex_str += "\\\\"

        latex_str += "\\text{Actor:}"
        for mat, mat_name in zip(mats_actor, mat_names):
            latex_str += f" &&{mat_name} = {bmatrix(mat[0])}"

        latex_str += "\\end{align*}"
        return latex_str

simulate(rng_key, n=1, x0=None, xhat0=None, Sigma0=None, return_all=False)

Simulate n trials

Parameters:

Name Type Description Default
rng_key PRNGKey

random number generator key

required
n int

number of trials

1
x0 array

initial state of shape (xdim,). Defaults to zeros.

None
xhat0 array

initial belief of shape (bdim,). Defaults to zeros.

None
Sigma0 array

initial belief covariance of shape (bdim, bdim), used to compute the Kalman gains. Defaults to V[0] @ V[0].T of the actor.

None
return_all bool

return beliefs, observations and actions as well

False

Returns:

Type Description
array or tuple

If return_all is False, the simulated states x of shape (n, T+1, xdim), including the initial state. Otherwise, a tuple (x, xhat, y, u) with the states, the beliefs of shape (n, T+1, bdim), the observations y[1:] of shape (n, T, ydim) and the actions of shape (n, T, udim).

Source code in lqg/system.py
 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
def simulate(
    self, rng_key, n=1, x0=None, xhat0=None, Sigma0=None, return_all=False
):
    """Simulate n trials

    Args:
        rng_key (jax.random.PRNGKey): random number generator key
        n (int): number of trials
        x0 (jnp.array, optional): initial state of shape (xdim,). Defaults
            to zeros.
        xhat0 (jnp.array, optional): initial belief of shape (bdim,).
            Defaults to zeros.
        Sigma0 (jnp.array, optional): initial belief covariance of shape
            (bdim, bdim), used to compute the Kalman gains. Defaults to
            ``V[0] @ V[0].T`` of the actor.
        return_all (bool): return beliefs, observations and actions as well

    Returns:
        jnp.array or tuple: If ``return_all`` is False, the simulated states
            ``x`` of shape (n, T+1, xdim), including the initial state.
            Otherwise, a tuple ``(x, xhat, y, u)`` with the states, the
            beliefs of shape (n, T+1, bdim), the observations ``y[1:]`` of
            shape (n, T, ydim) and the actions of shape (n, T, udim).
    """

    Sigma0 = self.actor.V[0] @ self.actor.V[0].T if Sigma0 is None else Sigma0

    gains = lqr.backward(self.actor)
    K = kf.forward(self.actor, Sigma0=Sigma0)

    def simulate_trial(rng_key, x0=None, xhat0=None):
        """Simulate a single trial

        Args:
            rng_key (jax.random.PRNGKey): random number generator key
            T (int): number of time steps
            x0 (jnp.array): initial state
            xhat0 (jnp.array): initial belief

        Returns:
            jnp.array, jnp.array, jnp.array, jnp.array: x (states), x_hat (estimates), y, u
        """

        x0 = jnp.zeros(self.xdim) if x0 is None else x0
        xhat0 = jnp.zeros(self.bdim) if xhat0 is None else xhat0

        # generate standard normal noise terms
        rng_key, subkey = random.split(rng_key)
        epsilon = random.normal(subkey, shape=(self.T, self.xdim))
        rng_key, subkey = random.split(rng_key)
        eta = random.normal(subkey, shape=(self.T, self.ydim))

        def loop(carry, t):
            x, x_hat = carry

            # compute control based on agent's current belief
            u = gains.L[t] @ x_hat + gains.k[t]

            # apply dynamics
            x = (
                self.dynamics.A[t] @ x
                + self.dynamics.B[t] @ u
                + self.dynamics.V[t] @ epsilon[t]
            )

            # generate observation
            y = self.dynamics.F[t] @ x + self.dynamics.W[t] @ eta[t]

            # update agent's belief
            x_pred = self.actor.A[t] @ x_hat + self.actor.B[t] @ u
            x_hat = x_pred + K[t] @ (y - self.actor.F[t] @ x_pred)

            return (x, x_hat), (x, x_hat, y, u)

        _, (x, x_hat, y, u) = scan(loop, (x0, xhat0), jnp.arange(self.T))

        return (jnp.vstack([x0, x]), jnp.vstack([xhat0, x_hat]), y, u)

    # simulate n trials
    x, x_hat, y, u = vmap(lambda key: simulate_trial(key, x0=x0, xhat0=xhat0))(
        random.split(rng_key, num=n)
    )

    if return_all:
        return x, x_hat, y, u
    else:
        return x

simulate_actions(x, action_dim_mask, rng_key, xhat0=None, Sigma0=None, return_all=False)

Simulate cursor actions given pre-existing experimental target trajectories.

Args: The target dimensions of the state are taken from the data at each time step, while the dimensions selected by action_dim_mask are simulated from the agent's actions.

Parameters:

Name Type Description Default
x array

Experimental state data of shape (n, T+1, xdim)

required
action_dim_mask array

Boolean mask of shape (xdim,) that selects the state dimensions to simulate (e.g. cursor position)

required
rng_key PRNGKey

Random number generator key

required
xhat0 array

Initial belief of shape (bdim,). Defaults to zeros.

None
Sigma0 array

initial belief covariance of shape (bdim, bdim). Defaults to V[0] @ V[0].T of the actor.

None
return_all bool

Whether to return beliefs, observations and actions as well

False

Returns:

Type Description
array or tuple

If return_all is False, the states of shape (n, T+1, xdim). Otherwise, a tuple (x, xhat, y, u) with the same shapes as in simulate.

Source code in lqg/system.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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
def simulate_actions(
    self, x, action_dim_mask, rng_key, xhat0=None, Sigma0=None, return_all=False
):
    """Simulate cursor actions given pre-existing experimental target trajectories.

    Args:
    The target dimensions of the state are taken from the data at each time
    step, while the dimensions selected by ``action_dim_mask`` are simulated
    from the agent's actions.

    Args:
        x (jnp.array): Experimental state data of shape (n, T+1, xdim)
        action_dim_mask (jnp.array): Boolean mask of shape (xdim,) that
            selects the state dimensions to simulate (e.g. cursor position)
        rng_key (jax.random.PRNGKey): Random number generator key
        xhat0 (jnp.array, optional): Initial belief of shape (bdim,).
            Defaults to zeros.
        Sigma0 (jnp.array, optional): initial belief covariance of shape
            (bdim, bdim). Defaults to ``V[0] @ V[0].T`` of the actor.
        return_all (bool): Whether to return beliefs, observations and
            actions as well

    Returns:
        jnp.array or tuple: If ``return_all`` is False, the states of shape
            (n, T+1, xdim). Otherwise, a tuple ``(x, xhat, y, u)`` with the
            same shapes as in [simulate][lqg.system.System.simulate].
    """
    Sigma0 = self.actor.V[0] @ self.actor.V[0].T if Sigma0 is None else Sigma0

    gains = lqr.backward(self.actor)
    K = kf.forward(self.actor, Sigma0=Sigma0)

    def simulate_trial_actions(x_single, action_dim_mask, rng_key, xhat0=None):
        # 1. Initial state at t=0 comes directly from experimental data x_single[0]
        x0 = x_single[0]
        xhat0 = jnp.zeros(self.bdim) if xhat0 is None else xhat0

        # Generate standard normal noise terms
        rng_key, subkey = random.split(rng_key)
        epsilon = random.normal(subkey, shape=(self.T, self.xdim))
        rng_key, subkey = random.split(rng_key)
        eta = random.normal(subkey, shape=(self.T, self.ydim))

        def loop(carry, t):
            x_curr, x_hat = carry  # x_curr is a 1D state vector of shape (xdim,)

            # Compute control based on agent's current belief
            u = gains.L[t] @ x_hat + gains.k[t]

            # Apply full dynamics transition: A[t] @ x_curr carries state & physics forward
            x_next_sim = (
                self.dynamics.A[t] @ x_curr
                + self.dynamics.B[t] @ u
                + self.dynamics.V[t] @ epsilon[t]
            )

            # Splicing: Take fixed experimental target state for t+1,
            # but inject newly simulated cursor/action states
            x_next = (
                x_single[t + 1].at[action_dim_mask].set(x_next_sim[action_dim_mask])
            )

            # Generate observation based on updated state x_next
            y = self.dynamics.F[t] @ x_next + self.dynamics.W[t] @ eta[t]

            # Update agent's belief
            x_pred = self.actor.A[t] @ x_hat + self.actor.B[t] @ u
            x_hat = x_pred + K[t] @ (y - self.actor.F[t] @ x_pred)

            return (x_next, x_hat), (x_next, x_hat, y, u)

        # Run scan across T time steps
        _, (x_steps, x_hat, y, u) = scan(loop, (x0, xhat0), jnp.arange(self.T))

        # Combine initial state x0 with simulated sequence -> shape (T+1, xdim)
        x_full = jnp.vstack([x0, x_steps])

        return x_full, jnp.vstack([xhat0, x_hat]), y, u

    # Map across trials and random keys
    keys = random.split(rng_key, num=x.shape[0])
    x_sim, x_hat, y, u = vmap(
        lambda x_i, key: simulate_trial_actions(
            x_i, action_dim_mask, key, xhat0=xhat0
        )
    )(x, keys)

    if return_all:
        return x_sim, x_hat, y, u
    else:
        return x_sim

conditional_moments(x, x0=None, xhat0=None, Sigma0=None)

Moments of the joint state and belief, given past observed states.

For each time step t, computes the mean and covariance of the Gaussian p(x[t+1], xhat[t+1] | x[0:t+1]) for a single trial, where the agent's belief xhat is marginalized out over the past.

Parameters:

Name Type Description Default
x array

one trial of observed states, of shape (T+1, d). If d < xdim, the first d state dimensions are observed.

required
x0 array

initial state. Defaults to x[0].

None
xhat0 array

initial belief. Defaults to x0.

None
Sigma0 array

initial belief covariance of shape (bdim, bdim), used to compute the Kalman gains. Defaults to V[0] @ V[0].T of the actor.

None

Returns:

Type Description
tuple

(mu, Sigma), the means of shape (T, xdim + bdim) and the covariances of shape (T, xdim + bdim, xdim + bdim). The first xdim entries are the state, the rest the belief.

Source code in lqg/system.py
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
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
def conditional_moments(self, x, x0=None, xhat0=None, Sigma0=None):
    """Moments of the joint state and belief, given past observed states.

    For each time step ``t``, computes the mean and covariance of the
    Gaussian ``p(x[t+1], xhat[t+1] | x[0:t+1])`` for a single trial, where
    the agent's belief ``xhat`` is marginalized out over the past.

    Args:
        x (jnp.array): one trial of observed states, of shape (T+1, d). If
            ``d < xdim``, the first ``d`` state dimensions are observed.
        x0 (jnp.array, optional): initial state. Defaults to ``x[0]``.
        xhat0 (jnp.array, optional): initial belief. Defaults to ``x0``.
        Sigma0 (jnp.array, optional): initial belief covariance of shape
            (bdim, bdim), used to compute the Kalman gains. Defaults to
            ``V[0] @ V[0].T`` of the actor.

    Returns:
        tuple: ``(mu, Sigma)``, the means of shape (T, xdim + bdim) and the
            covariances of shape (T, xdim + bdim, xdim + bdim). The first
            ``xdim`` entries are the state, the rest the belief.
    """
    T, obs_dim = x.shape
    xdim = self.dynamics.A.shape[1]
    bdim = self.actor.A.shape[1]

    # compute control and estimator gains
    gains = lqr.backward(self.actor)
    K = kf.forward(
        self.actor,
        Sigma0=self.actor.V[0] @ self.actor.V[0].T if Sigma0 is None else Sigma0,
    )

    # set up joint dynamical system for state and belief
    # p(x_t, xhat_t | x_{t-1}, xhat_{t-1})

    # joint dynamics
    F = jnp.concatenate(
        [
            jnp.concatenate([self.dynamics.A, self.dynamics.B @ gains.L], axis=-1),
            jnp.concatenate(
                [
                    K @ self.dynamics.F @ self.dynamics.A,
                    self.actor.A
                    + self.actor.B @ gains.L
                    - K @ self.actor.F @ self.actor.A
                    + K
                    @ (
                        self.dynamics.F @ self.dynamics.B
                        - self.actor.F @ self.actor.B
                    )
                    @ gains.L,
                ],
                axis=-1,
            ),
        ],
        axis=-2,
    )

    # joint noise covariance Cholesky factor
    G = jnp.concatenate(
        [
            jnp.concatenate(
                [
                    self.dynamics.V,
                    jnp.zeros(
                        (self.T, self.dynamics.A.shape[1], self.dynamics.W.shape[2])
                    ),
                ],
                axis=-1,
            ),
            jnp.concatenate(
                [K @ self.dynamics.F @ self.dynamics.V, K @ self.dynamics.W],
                axis=-1,
            ),
        ],
        axis=-2,
    )

    # initialize p(x_t, xhat_t | x_{1:t-1})
    if x0 is None:
        x0 = x[0]
    if xhat0 is None:
        xhat0 = x0
    mu0 = jnp.hstack(
        [x0, jnp.zeros(xdim - x0.shape[0]), xhat0, jnp.zeros(bdim - xhat0.shape[0])]
    )
    Sigma0 = G[0] @ G[0].T

    def scan_fn(carry, step):
        mu, Sigma = carry
        F, G, x = step

        # conditioning and marginalizing
        mu = F @ mu + (F @ Sigma)[:, :obs_dim] @ jnp.linalg.solve(
            Sigma[:obs_dim, :obs_dim], x - mu[:obs_dim]
        )

        Sigma = (
            F @ Sigma @ F.T
            + G @ G.T
            - (F @ Sigma)[:, :obs_dim]
            @ jnp.linalg.solve(
                Sigma[:obs_dim, :obs_dim], (Sigma @ F.T)[:obs_dim, :]
            )
        )
        return (mu, Sigma), (mu, Sigma)

    _, (mu, Sigma) = scan(scan_fn, (mu0, Sigma0), (F, G, x[:-1]))
    # return jnp.vstack((mu0, mu)), jnp.vstack((Sigma0[jnp.newaxis], Sigma))
    return mu, Sigma

conditional_distribution(x, x0=None, xhat0=None, Sigma0=None)

Distribution of each state given all previous states.

This is p(x[t+1] | x[0:t+1]) for every trial and time step, with the agent's beliefs marginalized out. See conditional_moments.

Parameters:

Name Type Description Default
x array

observed states of shape (n, T+1, d)

required
x0 array

initial states of shape (n, d). Defaults to x[:, 0].

None
xhat0 array

initial beliefs of shape (n, bdim). Defaults to x0.

None
Sigma0 array

initial belief covariance of shape (bdim, bdim)

None

Returns:

Type Description
Distribution

a multivariate normal with batch shape (n,) and event shape (T, d), to be evaluated on x[:, 1:].

Source code in lqg/system.py
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
def conditional_distribution(self, x, x0=None, xhat0=None, Sigma0=None):
    """Distribution of each state given all previous states.

    This is ``p(x[t+1] | x[0:t+1])`` for every trial and time step, with the
    agent's beliefs marginalized out. See
    [conditional_moments][lqg.system.System.conditional_moments].

    Args:
        x (jnp.array): observed states of shape (n, T+1, d)
        x0 (jnp.array, optional): initial states of shape (n, d). Defaults
            to ``x[:, 0]``.
        xhat0 (jnp.array, optional): initial beliefs of shape (n, bdim).
            Defaults to ``x0``.
        Sigma0 (jnp.array, optional): initial belief covariance of shape
            (bdim, bdim)

    Returns:
        numpyro.distributions.Distribution: a multivariate normal with batch
            shape (n,) and event shape (T, d), to be evaluated on
            ``x[:, 1:]``.
    """
    n, T, d = x.shape

    # compute p(x_{t+1}, xhat_{t+1} | x_{1:t})
    mu, Sigma = vmap(self.conditional_moments, in_axes=(0, 0, 0, None))(
        x, x0, xhat0, Sigma0
    )

    # marginalize out xhat by using only those entries of mu and Sigma that correspond to x
    return dist.MultivariateNormal(mu[:, :, :d], Sigma[:, :, :d, :d]).to_event(1)

log_likelihood(x, x0=None, xhat0=None, Sigma0=None)

Log likelihood of observed trajectories.

Evaluates log p(x[1:] | x[0]), factorized over time steps as in conditional_distribution.

Parameters:

Name Type Description Default
x array

observed states of shape (n, T+1, d)

required
x0 array

initial states of shape (n, d)

None
xhat0 array

initial beliefs of shape (n, bdim)

None
Sigma0 array

initial belief covariance of shape (bdim, bdim)

None

Returns:

Type Description
array

log likelihood of each trial, of shape (n,)

Source code in lqg/system.py
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
def log_likelihood(self, x, x0=None, xhat0=None, Sigma0=None):
    """Log likelihood of observed trajectories.

    Evaluates ``log p(x[1:] | x[0])``, factorized over time steps as in
    [conditional_distribution][lqg.system.System.conditional_distribution].

    Args:
        x (jnp.array): observed states of shape (n, T+1, d)
        x0 (jnp.array, optional): initial states of shape (n, d)
        xhat0 (jnp.array, optional): initial beliefs of shape (n, bdim)
        Sigma0 (jnp.array, optional): initial belief covariance of shape
            (bdim, bdim)

    Returns:
        jnp.array: log likelihood of each trial, of shape (n,)
    """
    return self.conditional_distribution(
        x, x0=x0, xhat0=xhat0, Sigma0=Sigma0
    ).log_prob(x[:, 1:])

belief_tracking_distribution(x, Sigma0=None)

Distribution of the agent's beliefs given the observed states.

This is p(xhat[t+1] | x[0:t+1]) for every trial and time step.

Parameters:

Name Type Description Default
x array

observed states of shape (n, T+1, xdim)

required
Sigma0 array

initial belief covariance of shape (bdim, bdim)

None

Returns:

Type Description
MultivariateNormal

a distribution with batch shape (n, T) and event shape (bdim,)

Source code in lqg/system.py
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
def belief_tracking_distribution(self, x, Sigma0=None):
    """Distribution of the agent's beliefs given the observed states.

    This is ``p(xhat[t+1] | x[0:t+1])`` for every trial and time step.

    Args:
        x (jnp.array): observed states of shape (n, T+1, xdim)
        Sigma0 (jnp.array, optional): initial belief covariance of shape
            (bdim, bdim)

    Returns:
        numpyro.distributions.MultivariateNormal: a distribution with batch
            shape (n, T) and event shape (bdim,)
    """
    d = self.xdim

    # compute p(x_{t+1}, xhat_{t+1} | x_{1:t})
    mu, Sigma = vmap(
        lambda xi: self.conditional_moments(xi, Sigma0=Sigma0), in_axes=0
    )(x)

    # return those elements of mu and Sigma that correspond to xhat
    return dist.MultivariateNormal(mu[:, :, d:], Sigma[:, :, d:, d:])

to_numpyro(Sigma0=None, xdim=None)

Wrap the system as a numpyro distribution over trajectories.

The distribution can be used with numpyro.sample in a model, e.g. numpyro.sample("x", system.to_numpyro(), obs=x).

Parameters:

Name Type Description Default
Sigma0 array

initial belief covariance of shape (bdim, bdim)

None
xdim int

number of observed state dimensions. Defaults to all of them.

None

Returns:

Type Description
Distribution

a distribution with event shape (T+1, xdim)

Source code in lqg/system.py
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def to_numpyro(self, Sigma0=None, xdim=None):
    """Wrap the system as a numpyro distribution over trajectories.

    The distribution can be used with ``numpyro.sample`` in a model, e.g.
    ``numpyro.sample("x", system.to_numpyro(), obs=x)``.

    Args:
        Sigma0 (jnp.array, optional): initial belief covariance of shape
            (bdim, bdim)
        xdim (int, optional): number of observed state dimensions. Defaults
            to all of them.

    Returns:
        numpyro.distributions.Distribution: a distribution with event shape
            (T+1, xdim)
    """
    return NumpyroLQG(self, Sigma0=Sigma0, xdim=xdim)

lqg.system.LQG

Bases: System

A system in which the agent's internal model matches the environment.

The same matrices are used for the actor and the dynamics. See Actor for their meaning and shapes.

Source code in lqg/system.py
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
class LQG(System):
    """A system in which the agent's internal model matches the environment.

    The same matrices are used for the actor and the dynamics. See
    [Actor][lqg.system.Actor] for their meaning and shapes.
    """

    def __init__(self, A, B, F, V, W, Q, R, T=1000):
        """Create an LQG system from time-invariant matrices.

        Args:
            A (jnp.array): state transition matrix of shape (xdim, xdim)
            B (jnp.array): control matrix of shape (xdim, udim)
            F (jnp.array): observation matrix of shape (ydim, xdim)
            V (jnp.array): process noise Cholesky factor of shape (xdim, xdim)
            W (jnp.array): observation noise Cholesky factor of shape
                (ydim, ydim)
            Q (jnp.array): state cost matrix of shape (xdim, xdim)
            R (jnp.array): action cost matrix of shape (udim, udim)
            T (int): number of time steps
        """
        spec = time_stack_spec(A=A, B=B, F=F, V=V, W=W, Q=Q, R=R, T=T)

        super().__init__(actor=spec, dynamics=spec)

__init__(A, B, F, V, W, Q, R, T=1000)

Create an LQG system from time-invariant matrices.

Parameters:

Name Type Description Default
A array

state transition matrix of shape (xdim, xdim)

required
B array

control matrix of shape (xdim, udim)

required
F array

observation matrix of shape (ydim, xdim)

required
V array

process noise Cholesky factor of shape (xdim, xdim)

required
W array

observation noise Cholesky factor of shape (ydim, ydim)

required
Q array

state cost matrix of shape (xdim, xdim)

required
R array

action cost matrix of shape (udim, udim)

required
T int

number of time steps

1000
Source code in lqg/system.py
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
def __init__(self, A, B, F, V, W, Q, R, T=1000):
    """Create an LQG system from time-invariant matrices.

    Args:
        A (jnp.array): state transition matrix of shape (xdim, xdim)
        B (jnp.array): control matrix of shape (xdim, udim)
        F (jnp.array): observation matrix of shape (ydim, xdim)
        V (jnp.array): process noise Cholesky factor of shape (xdim, xdim)
        W (jnp.array): observation noise Cholesky factor of shape
            (ydim, ydim)
        Q (jnp.array): state cost matrix of shape (xdim, xdim)
        R (jnp.array): action cost matrix of shape (udim, udim)
        T (int): number of time steps
    """
    spec = time_stack_spec(A=A, B=B, F=F, V=V, W=W, Q=Q, R=R, T=T)

    super().__init__(actor=spec, dynamics=spec)

lqg.system.Dynamics(A, B, F, V, W, T=1000)

Specification of an environment with time-invariant dynamics.

x[t+1] = A x[t] + B u[t] + V eps[t],    eps[t] ~ N(0, I)
y[t+1] = F x[t+1] + W eta[t],         eta[t] ~ N(0, I)

Parameters:

Name Type Description Default
A array

state transition matrix of shape (xdim, xdim)

required
B array

control matrix of shape (xdim, udim)

required
F array

observation matrix of shape (ydim, xdim)

required
V array

process noise Cholesky factor of shape (xdim, xdim)

required
W array

observation noise Cholesky factor of shape (ydim, ydim)

required
T int

number of time steps

1000

Returns:

Type Description
LQGSpec

the matrices repeated over T time steps, with zero costs

Source code in lqg/system.py
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
def Dynamics(A, B, F, V, W, T=1000):
    """Specification of an environment with time-invariant dynamics.

    ```
    x[t+1] = A x[t] + B u[t] + V eps[t],    eps[t] ~ N(0, I)
    y[t+1] = F x[t+1] + W eta[t],         eta[t] ~ N(0, I)
    ```

    Args:
        A (jnp.array): state transition matrix of shape (xdim, xdim)
        B (jnp.array): control matrix of shape (xdim, udim)
        F (jnp.array): observation matrix of shape (ydim, xdim)
        V (jnp.array): process noise Cholesky factor of shape (xdim, xdim)
        W (jnp.array): observation noise Cholesky factor of shape (ydim, ydim)
        T (int): number of time steps

    Returns:
        LQGSpec: the matrices repeated over ``T`` time steps, with zero costs
    """
    xdim = A.shape[0]
    udim = B.shape[1]

    return time_stack_spec(
        A=A,
        B=B,
        F=F,
        V=V,
        W=W,
        Q=jnp.zeros((xdim, xdim)),
        R=jnp.zeros((udim, udim)),
        T=T,
    )

lqg.system.Actor(A, B, F, V, W, Q, R, T=1000)

Specification of an agent's internal model and cost function.

The agent assumes the same linear-Gaussian dynamics as in Dynamics and minimizes the cost sum_t x[t]^T Q x[t] + u[t]^T R u[t] (with constant factors dropped).

Parameters:

Name Type Description Default
A array

state transition matrix of shape (bdim, bdim)

required
B array

control matrix of shape (bdim, udim)

required
F array

observation matrix of shape (ydim, bdim)

required
V array

process noise Cholesky factor of shape (bdim, bdim)

required
W array

observation noise Cholesky factor of shape (ydim, ydim)

required
Q array

state cost matrix of shape (bdim, bdim)

required
R array

action cost matrix of shape (udim, udim)

required
T int

number of time steps

1000

Returns:

Type Description
LQGSpec

the matrices repeated over T time steps. The final state cost is Q, and all linear and cross terms are zero.

Source code in lqg/system.py
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
def Actor(A, B, F, V, W, Q, R, T=1000):
    """Specification of an agent's internal model and cost function.

    The agent assumes the same linear-Gaussian dynamics as in
    [Dynamics][lqg.system.Dynamics] and minimizes the cost
    ``sum_t x[t]^T Q x[t] + u[t]^T R u[t]`` (with constant factors dropped).

    Args:
        A (jnp.array): state transition matrix of shape (bdim, bdim)
        B (jnp.array): control matrix of shape (bdim, udim)
        F (jnp.array): observation matrix of shape (ydim, bdim)
        V (jnp.array): process noise Cholesky factor of shape (bdim, bdim)
        W (jnp.array): observation noise Cholesky factor of shape (ydim, ydim)
        Q (jnp.array): state cost matrix of shape (bdim, bdim)
        R (jnp.array): action cost matrix of shape (udim, udim)
        T (int): number of time steps

    Returns:
        LQGSpec: the matrices repeated over ``T`` time steps. The final state
            cost is ``Q``, and all linear and cross terms are zero.
    """
    return time_stack_spec(A=A, B=B, F=F, V=V, W=W, Q=Q, R=R, T=T)

lqg.spec.LQGSpec

Bases: NamedTuple

Time-varying specification of a (generalized) LQG problem.

Dynamics and observations:

x[t+1] = A[t] x[t] + B[t] u[t] + V[t] eps[t],    eps[t] ~ N(0, I)
y[t+1] = F[t] x[t+1] + W[t] eta[t],       eta[t] ~ N(0, I)

Cost, up to a constant:

sum_t ( 1/2 x[t]^T Q[t] x[t] + q[t]^T x[t]
      + u[t]^T P[t] x[t]
      + 1/2 u[t]^T R[t] u[t] + r[t]^T u[t] )
+ 1/2 x[T]^T Qf x[T] + qf^T x[T]

All time-varying fields have a leading time axis of length T. Use Actor or Dynamics to build a specification from time-invariant matrices.

Attributes:

Name Type Description
Q ndarray

quadratic state cost, shape (T, xdim, xdim)

q ndarray

linear state cost, shape (T, xdim)

Qf ndarray

quadratic final state cost, shape (xdim, xdim)

qf ndarray

linear final state cost, shape (xdim,)

P ndarray

action-state cross cost, shape (T, udim, xdim)

R ndarray

quadratic action cost, shape (T, udim, udim)

r ndarray

linear action cost, shape (T, udim)

A ndarray

state transition matrices, shape (T, xdim, xdim)

B ndarray

control matrices, shape (T, xdim, udim)

V ndarray

process noise Cholesky factors, shape (T, xdim, xdim)

F ndarray

observation matrices, shape (T, ydim, xdim)

W ndarray

observation noise Cholesky factors, shape (T, ydim, ydim)

Source code in lqg/spec.py
 5
 6
 7
 8
 9
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
class LQGSpec(NamedTuple):
    """Time-varying specification of a (generalized) LQG problem.

    Dynamics and observations:

    ```
    x[t+1] = A[t] x[t] + B[t] u[t] + V[t] eps[t],    eps[t] ~ N(0, I)
    y[t+1] = F[t] x[t+1] + W[t] eta[t],       eta[t] ~ N(0, I)
    ```

    Cost, up to a constant:

    ```
    sum_t ( 1/2 x[t]^T Q[t] x[t] + q[t]^T x[t]
          + u[t]^T P[t] x[t]
          + 1/2 u[t]^T R[t] u[t] + r[t]^T u[t] )
    + 1/2 x[T]^T Qf x[T] + qf^T x[T]
    ```

    All time-varying fields have a leading time axis of length ``T``. Use
    [Actor][lqg.system.Actor] or [Dynamics][lqg.system.Dynamics] to build a
    specification from time-invariant matrices.

    Attributes:
        Q (jnp.ndarray): quadratic state cost, shape (T, xdim, xdim)
        q (jnp.ndarray): linear state cost, shape (T, xdim)
        Qf (jnp.ndarray): quadratic final state cost, shape (xdim, xdim)
        qf (jnp.ndarray): linear final state cost, shape (xdim,)
        P (jnp.ndarray): action-state cross cost, shape (T, udim, xdim)
        R (jnp.ndarray): quadratic action cost, shape (T, udim, udim)
        r (jnp.ndarray): linear action cost, shape (T, udim)
        A (jnp.ndarray): state transition matrices, shape (T, xdim, xdim)
        B (jnp.ndarray): control matrices, shape (T, xdim, udim)
        V (jnp.ndarray): process noise Cholesky factors, shape (T, xdim, xdim)
        F (jnp.ndarray): observation matrices, shape (T, ydim, xdim)
        W (jnp.ndarray): observation noise Cholesky factors, shape
            (T, ydim, ydim)
    """

    Q: jnp.ndarray
    q: jnp.ndarray
    Qf: jnp.array
    qf: jnp.array
    P: jnp.ndarray
    R: jnp.ndarray
    r: jnp.ndarray
    A: jnp.ndarray
    B: jnp.ndarray
    V: jnp.ndarray
    F: jnp.ndarray
    W: jnp.ndarray

Tracking Models

lqg.tracking.basic.TrackingTask

Bases: System

Continuous tracking of a target with a cursor whose velocity is controlled.

For each spatial dimension, the state is [target, cursor]. The target follows a Gaussian random walk, the action sets the cursor's velocity, and both positions are observed with independent Gaussian noise. The cost is the squared distance between target and cursor plus action_cost * u^2. The agent's internal model matches the dynamics.

Parameters:

Name Type Description Default
dim int

number of spatial dimensions (e.g. 2 for tracking in x and y)

1
process_noise float

standard deviation of the target's random walk

1.0
action_variability float

standard deviation of the noise on the cursor's movement

0.5
sigma_target float

standard deviation of the target observation noise

6.0
sigma_cursor float

standard deviation of the cursor observation noise

6.0
action_cost float

weight of the action cost relative to the distance cost

1.0
dt float

duration of a time step in seconds

1.0 / 60.0
T int

number of time steps

1000
Source code in lqg/tracking/basic.py
 7
 8
 9
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
class TrackingTask(System):
    """Continuous tracking of a target with a cursor whose velocity is controlled.

    For each spatial dimension, the state is ``[target, cursor]``. The target
    follows a Gaussian random walk, the action sets the cursor's velocity, and
    both positions are observed with independent Gaussian noise. The cost is
    the squared distance between target and cursor plus
    ``action_cost * u^2``. The agent's internal model matches the dynamics.

    Args:
        dim (int): number of spatial dimensions (e.g. 2 for tracking in x and y)
        process_noise (float): standard deviation of the target's random walk
        action_variability (float): standard deviation of the noise on the
            cursor's movement
        sigma_target (float): standard deviation of the target observation noise
        sigma_cursor (float): standard deviation of the cursor observation noise
        action_cost (float): weight of the action cost relative to the distance
            cost
        dt (float): duration of a time step in seconds
        T (int): number of time steps
    """

    def __init__(
        self,
        dim=1,
        process_noise=1.0,
        action_variability=0.5,
        sigma_target=6.0,
        sigma_cursor=6.0,
        action_cost=1.0,
        dt=1.0 / 60.0,
        T=1000,
    ):
        self.dim = dim
        self.process_noise = process_noise
        # dimensionality
        d = 2 * dim
        # dynamics model
        A = jnp.eye(d)
        B = dt * linalg.block_diag(*[jnp.array([[0.0], [1.0]])] * dim)

        # observation model
        F = jnp.eye(d)

        # noise model
        V = jnp.diag(jnp.array([process_noise, action_variability] * dim))
        W = jnp.diag(jnp.array([sigma_target, sigma_cursor] * dim))

        # cost function
        Q = linalg.block_diag(*[jnp.array([[1.0, -1.0], [-1.0, 1.0]])] * dim)
        R = jnp.eye(B.shape[1]) * action_cost

        spec = Actor(A=A, B=B, F=F, V=V, W=W, Q=Q, R=R, T=T)

        super().__init__(actor=spec, dynamics=spec)

lqg.tracking.basic.BoundedActor

Bases: TrackingTask

Boundedly rational actor in a tracking task, with an action cost.

The same model as TrackingTask; the name emphasizes that the action cost makes the actor deviate from optimal tracking. See there for the arguments.

Source code in lqg/tracking/basic.py
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
class BoundedActor(TrackingTask):
    """Boundedly rational actor in a tracking task, with an action cost.

    The same model as [TrackingTask][lqg.tracking.basic.TrackingTask]; the
    name emphasizes that the action cost makes the actor deviate from
    optimal tracking. See there for the arguments.
    """

    def __init__(
        self,
        dim=1,
        process_noise=1.0,
        action_variability=0.5,
        sigma_target=6.0,
        sigma_cursor=6.0,
        action_cost=1.0,
        dt=1.0 / 60,
        T=1000,
    ):
        super().__init__(
            dim=dim,
            process_noise=process_noise,
            action_variability=action_variability,
            sigma_target=sigma_target,
            sigma_cursor=sigma_cursor,
            action_cost=action_cost,
            dt=dt,
            T=T,
        )

lqg.tracking.basic.OptimalActor

Bases: TrackingTask

Actor in a tracking task with a negligible action cost.

The same model as BoundedActor, but with action_cost fixed to 1e-3.

Parameters:

Name Type Description Default
dim int

number of spatial dimensions (e.g. 2 for tracking in x and y)

1
process_noise float

standard deviation of the target's random walk

1.0
action_variability float

standard deviation of the noise on the cursor's movement

0.5
sigma_target float

standard deviation of the target observation noise

6.0
sigma_cursor float

standard deviation of the cursor observation noise

6.0
dt float

duration of a time step in seconds

1.0 / 60
T int

number of time steps

1000
Source code in lqg/tracking/basic.py
 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
class OptimalActor(TrackingTask):
    """Actor in a tracking task with a negligible action cost.

    The same model as [BoundedActor][lqg.tracking.basic.BoundedActor], but
    with ``action_cost`` fixed to ``1e-3``.

    Args:
        dim (int): number of spatial dimensions (e.g. 2 for tracking in x and y)
        process_noise (float): standard deviation of the target's random walk
        action_variability (float): standard deviation of the noise on the
            cursor's movement
        sigma_target (float): standard deviation of the target observation noise
        sigma_cursor (float): standard deviation of the cursor observation noise
        dt (float): duration of a time step in seconds
        T (int): number of time steps
    """

    def __init__(
        self,
        dim=1,
        process_noise=1.0,
        action_variability=0.5,
        sigma_target=6.0,
        sigma_cursor=6.0,
        dt=1.0 / 60,
        T=1000,
    ):
        super().__init__(
            dim=dim,
            process_noise=process_noise,
            action_variability=action_variability,
            sigma_target=sigma_target,
            sigma_cursor=sigma_cursor,
            action_cost=1e-3,
            dt=dt,
            T=T,
        )

lqg.tracking.basic.RelativeObservationBoundedActor

Bases: System

Bounded actor that only observes the target position relative to the cursor.

The same model as BoundedActor, except that the observation is target - cursor (one per spatial dimension) instead of both positions separately.

Parameters:

Name Type Description Default
dim int

number of spatial dimensions (e.g. 2 for tracking in x and y)

1
process_noise float

standard deviation of the target's random walk

1.0
action_variability float

standard deviation of the noise on the cursor's movement

0.5
sigma float

standard deviation of the observation noise

6.0
action_cost float

weight of the action cost relative to the distance cost

1.0
dt float

duration of a time step in seconds

1.0 / 60.0
T int

number of time steps

1000
Source code in lqg/tracking/basic.py
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
class RelativeObservationBoundedActor(System):
    """Bounded actor that only observes the target position relative to the cursor.

    The same model as [BoundedActor][lqg.tracking.basic.BoundedActor], except
    that the observation is ``target - cursor`` (one per spatial dimension)
    instead of both positions separately.

    Args:
        dim (int): number of spatial dimensions (e.g. 2 for tracking in x and y)
        process_noise (float): standard deviation of the target's random walk
        action_variability (float): standard deviation of the noise on the
            cursor's movement
        sigma (float): standard deviation of the observation noise
        action_cost (float): weight of the action cost relative to the distance
            cost
        dt (float): duration of a time step in seconds
        T (int): number of time steps
    """

    def __init__(
        self,
        dim=1,
        process_noise=1.0,
        action_variability=0.5,
        sigma=6.0,
        action_cost=1.0,
        dt=1.0 / 60.0,
        T=1000,
    ):
        self.dim = dim
        self.process_noise = process_noise

        # dimensionality
        d = 2 * dim

        # dynamics model
        A = jnp.eye(d)
        B = dt * linalg.block_diag(*[jnp.array([[0.0], [1.0]])] * dim)

        # observation model
        F = linalg.block_diag(*[jnp.array([[1.0, -1.0]])] * dim)

        # noise model
        V = jnp.diag(jnp.array([process_noise, action_variability] * dim))
        W = jnp.diag(jnp.array([sigma] * dim))

        # cost function
        Q = linalg.block_diag(*[jnp.array([[1.0, -1.0], [-1.0, 1.0]])] * dim)
        R = jnp.eye(B.shape[1]) * action_cost

        spec = Actor(A=A, B=B, F=F, V=V, W=W, Q=Q, R=R, T=T)

        super().__init__(actor=spec, dynamics=spec)

lqg.tracking.subjective.SubjectiveActor

Bases: System

Bounded actor with a subjective model of the target dynamics.

The true dynamics are the same as in BoundedActor. The actor, however, assumes that the target has an additional latent velocity, i.e. it believes in the model

target[t+1]     = target[t] + dt * target_vel[t] + subj_noise * eps
target_vel[t+1] = target_vel[t] + subj_vel_noise * eps

The actor's state is [target, cursor] for each spatial dimension, followed by target_vel for each spatial dimension.

Parameters:

Name Type Description Default
dim int

number of spatial dimensions (e.g. 2 for tracking in x and y)

1
process_noise float

standard deviation of the target's random walk

1.0
action_variability float

standard deviation of the noise on the cursor's movement

0.5
action_cost float

weight of the action cost relative to the distance cost

1.0
subj_noise float

standard deviation of the target noise that the actor assumes

1.0
subj_vel_noise float

standard deviation of the target velocity noise that the actor assumes

0.5
sigma_target float

standard deviation of the target observation noise

6.0
sigma_cursor float

standard deviation of the cursor observation noise

6.0
dt float

duration of a time step in seconds

1.0 / 60
T int

number of time steps

1000
Source code in lqg/tracking/subjective.py
 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
class SubjectiveActor(System):
    """Bounded actor with a subjective model of the target dynamics.

    The true dynamics are the same as in
    [BoundedActor][lqg.tracking.basic.BoundedActor]. The actor, however,
    assumes that the target has an additional latent velocity, i.e. it
    believes in the model

    ```
    target[t+1]     = target[t] + dt * target_vel[t] + subj_noise * eps
    target_vel[t+1] = target_vel[t] + subj_vel_noise * eps
    ```

    The actor's state is ``[target, cursor]`` for each spatial dimension,
    followed by ``target_vel`` for each spatial dimension.

    Args:
        dim (int): number of spatial dimensions (e.g. 2 for tracking in x and y)
        process_noise (float): standard deviation of the target's random walk
        action_variability (float): standard deviation of the noise on the
            cursor's movement
        action_cost (float): weight of the action cost relative to the distance
            cost
        subj_noise (float): standard deviation of the target noise that the
            actor assumes
        subj_vel_noise (float): standard deviation of the target velocity noise
            that the actor assumes
        sigma_target (float): standard deviation of the target observation noise
        sigma_cursor (float): standard deviation of the cursor observation noise
        dt (float): duration of a time step in seconds
        T (int): number of time steps
    """

    def __init__(
        self,
        dim=1,
        process_noise=1.0,
        action_cost=1.0,
        action_variability=0.5,
        subj_noise=1.0,
        subj_vel_noise=0.5,
        sigma_target=6.0,
        sigma_cursor=6.0,
        dt=1.0 / 60,
        T=1000,
    ):
        A = jnp.eye(2 * dim)
        B = linalg.block_diag(*[jnp.array([[0.0], [1.0 * dt]])] * dim)
        F = jnp.eye(2 * dim)

        V = linalg.block_diag(
            *[jnp.diag(jnp.array([process_noise, action_variability]))] * dim
        )
        W = linalg.block_diag(
            *[jnp.diag(jnp.array([sigma_target, sigma_cursor]))] * dim
        )

        dyn = Dynamics(A=A, B=B, F=F, V=V, W=W, T=T)

        A = linalg.block_diag(
            *[jnp.array([[1.0, 0.0, dt], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]])] * dim
        )
        B = linalg.block_diag(*[jnp.array([[0.0], [1.0 * dt], [0.0]])] * dim)
        F = linalg.block_diag(*[jnp.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])] * dim)

        V = linalg.block_diag(
            *[jnp.diag(jnp.array([subj_noise, action_variability, subj_vel_noise]))]
            * dim
        )

        Q = linalg.block_diag(
            *[jnp.array([[1.0, -1.0, 0.0], [-1.0, 1.0, 0.0], [0.0, 0.0, 0.0]])] * dim
        )
        R = jnp.eye(B.shape[1]) * action_cost

        dims = swap_dims(A.shape[0], dim)

        A = A[dims, :][:, dims]
        B = B[dims, :]
        V = V[dims, :]
        F = F[:, dims]
        Q = Q[dims, :][:, dims]

        act = Actor(A=A, B=B, F=F, V=V, W=W, Q=Q, R=R, T=T)

        super().__init__(actor=act, dynamics=dyn)

lqg.tracking.point_mass.PointMassBoundedActor

Bases: System

Bounded actor in a tracking task with point-mass hand dynamics.

Unlike in BoundedActor, the action does not set the cursor velocity directly. It drives a first-order muscle activation with time constant tau, whose force accelerates the cursor as a point mass. The state is [target, cursor_pos, cursor_vel, force], and target and cursor position are observed with Gaussian noise. Only one spatial dimension is supported.

The cost is the squared distance between target and cursor, plus velocity_cost * cursor_vel^2, force_cost * force^2 and action_cost * u^2. The agent's internal model matches the dynamics.

Parameters:

Name Type Description Default
process_noise float

standard deviation of the target's random walk

1.0
action_variability float

standard deviation of the noise on the muscle activation

0.001
sigma_target float

standard deviation of the target observation noise

6.0
sigma_cursor float

standard deviation of the cursor observation noise

12.5
action_cost float

weight of the action cost

0.01
velocity_cost float

weight of the cost on cursor velocity

0.01
force_cost float

weight of the cost on muscle force

0.01
dt float

duration of a time step in seconds

1.0 / 60.0
T int

number of time steps

1000
tau float

time constant of the muscle activation in seconds

0.066
Source code in lqg/tracking/point_mass.py
 7
 8
 9
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
class PointMassBoundedActor(System):
    """Bounded actor in a tracking task with point-mass hand dynamics.

    Unlike in [BoundedActor][lqg.tracking.basic.BoundedActor], the action does
    not set the cursor velocity directly. It drives a first-order muscle
    activation with time constant ``tau``, whose force accelerates the cursor
    as a point mass. The state is ``[target, cursor_pos, cursor_vel, force]``,
    and target and cursor position are observed with Gaussian noise. Only one
    spatial dimension is supported.

    The cost is the squared distance between target and cursor, plus
    ``velocity_cost * cursor_vel^2``, ``force_cost * force^2`` and
    ``action_cost * u^2``. The agent's internal model matches the dynamics.

    Args:
        process_noise (float): standard deviation of the target's random walk
        action_variability (float): standard deviation of the noise on the
            muscle activation
        sigma_target (float): standard deviation of the target observation noise
        sigma_cursor (float): standard deviation of the cursor observation noise
        action_cost (float): weight of the action cost
        velocity_cost (float): weight of the cost on cursor velocity
        force_cost (float): weight of the cost on muscle force
        dt (float): duration of a time step in seconds
        T (int): number of time steps
        tau (float): time constant of the muscle activation in seconds
    """

    def __init__(
        self,
        process_noise=1.0,
        action_variability=1e-3,
        sigma_target=6.0,
        sigma_cursor=12.5,
        action_cost=0.01,
        velocity_cost=0.01,
        force_cost=0.01,
        dt=1.0 / 60.0,
        T=1000,
        tau=0.066,
    ):
        A, B, V = point_mass_dynamics_matrices(
            tau=tau, action_variability=action_variability, dt=dt
        )
        A = linalg.block_diag(jnp.eye(1), A)  # add target position as a constant state
        B = jnp.vstack([jnp.zeros((1, 1)), B])
        V = linalg.block_diag(jnp.diag(jnp.array([process_noise])), V)

        # observation of target position
        F = jnp.eye(2, 4)
        W = jnp.diag(jnp.array([sigma_target, sigma_cursor]))

        # cost on distance between cursor and target, no cost on velocity or muscle activation
        Q = linalg.block_diag(
            *[
                jnp.array(
                    [
                        [1.0, -1.0, 0.0, 0.0],
                        [-1.0, 1.0, 0.0, 0.0],
                        [0.0, 0.0, velocity_cost, 0.0],
                        [0.0, 0.0, 0.0, force_cost],
                    ]
                )
            ]
        )
        R = jnp.eye(B.shape[1]) * action_cost

        spec = Actor(A=A, B=B, F=F, V=V, W=W, Q=Q, R=R, T=T)

        super().__init__(actor=spec, dynamics=spec)

lqg.tracking.point_mass.PointMassSubjectiveActor

Bases: System

Point-mass hand dynamics with a subjective model of the target dynamics.

The true dynamics are the same as in PointMassBoundedActor (random-walk target, point-mass cursor with first-order muscle activation). The actor, however, assumes that the target has an additional latent velocity, i.e. it believes in the model

target_{t+1} = target_t + dt * target_vel_t + subj_noise * eps
target_vel_{t+1} = target_vel_t + subj_vel_noise * eps

Actor state: [target, cursor_pos, cursor_vel, force, target_vel]. The first four dimensions coincide with the state of the true dynamics.

With subj_noise == process_noise and subj_vel_noise == 0, the model reduces to PointMassBoundedActor.

Parameters:

Name Type Description Default
process_noise float

standard deviation of the target's random walk

1.0
action_variability float

standard deviation of the noise on the muscle activation

0.001
subj_noise float

standard deviation of the target noise that the actor assumes

1.0
subj_vel_noise float

standard deviation of the target velocity noise that the actor assumes

0.5
sigma_target float

standard deviation of the target observation noise

6.0
sigma_cursor float

standard deviation of the cursor observation noise

12.5
action_cost float

weight of the action cost

0.01
velocity_cost float

weight of the cost on cursor velocity

0.01
force_cost float

weight of the cost on muscle force

0.01
dt float

duration of a time step in seconds

1.0 / 60.0
T int

number of time steps

1000
tau float

time constant of the muscle activation in seconds

0.066
Source code in lqg/tracking/point_mass.py
 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
class PointMassSubjectiveActor(System):
    """Point-mass hand dynamics with a subjective model of the target dynamics.

    The true dynamics are the same as in PointMassBoundedActor (random-walk target,
    point-mass cursor with first-order muscle activation). The actor, however,
    assumes that the target has an additional latent velocity, i.e. it believes in
    the model

        target_{t+1} = target_t + dt * target_vel_t + subj_noise * eps
        target_vel_{t+1} = target_vel_t + subj_vel_noise * eps

    Actor state: [target, cursor_pos, cursor_vel, force, target_vel]. The first four
    dimensions coincide with the state of the true dynamics.

    With subj_noise == process_noise and subj_vel_noise == 0, the model reduces to
    PointMassBoundedActor.

    Args:
        process_noise (float): standard deviation of the target's random walk
        action_variability (float): standard deviation of the noise on the
            muscle activation
        subj_noise (float): standard deviation of the target noise that the
            actor assumes
        subj_vel_noise (float): standard deviation of the target velocity noise
            that the actor assumes
        sigma_target (float): standard deviation of the target observation noise
        sigma_cursor (float): standard deviation of the cursor observation noise
        action_cost (float): weight of the action cost
        velocity_cost (float): weight of the cost on cursor velocity
        force_cost (float): weight of the cost on muscle force
        dt (float): duration of a time step in seconds
        T (int): number of time steps
        tau (float): time constant of the muscle activation in seconds
    """

    def __init__(
        self,
        process_noise=1.0,
        action_variability=1e-3,
        subj_noise=1.0,
        subj_vel_noise=0.5,
        sigma_target=6.0,
        sigma_cursor=12.5,
        action_cost=0.01,
        velocity_cost=0.01,
        force_cost=0.01,
        dt=1.0 / 60.0,
        T=1000,
        tau=0.066,
    ):
        A_pm, B_pm, V_pm = point_mass_dynamics_matrices(
            tau=tau, action_variability=action_variability, dt=dt
        )

        # observation of target and cursor position
        W = jnp.diag(jnp.array([sigma_target, sigma_cursor]))

        # true dynamics: [target, cursor_pos, cursor_vel, force]
        A = linalg.block_diag(jnp.eye(1), A_pm)
        B = jnp.vstack([jnp.zeros((1, 1)), B_pm])
        V = linalg.block_diag(jnp.diag(jnp.array([process_noise])), V_pm)
        F = jnp.eye(2, 4)

        dyn = Dynamics(A=A, B=B, F=F, V=V, W=W, T=T)

        # subjective model: [target, cursor_pos, cursor_vel, force, target_vel]
        A = linalg.block_diag(jnp.eye(1), A_pm, jnp.eye(1))
        A = A.at[0, 4].set(dt)  # target position driven by latent target velocity
        B = jnp.vstack([jnp.zeros((1, 1)), B_pm, jnp.zeros((1, 1))])
        V = linalg.block_diag(
            jnp.diag(jnp.array([subj_noise])),
            V_pm,
            jnp.diag(jnp.array([subj_vel_noise])),
        )
        F = jnp.eye(2, 5)

        # cost on distance between cursor and target, velocity and force
        Q = linalg.block_diag(
            jnp.array(
                [
                    [1.0, -1.0, 0.0, 0.0],
                    [-1.0, 1.0, 0.0, 0.0],
                    [0.0, 0.0, velocity_cost, 0.0],
                    [0.0, 0.0, 0.0, force_cost],
                ]
            ),
            jnp.zeros((1, 1)),  # no cost on target velocity
        )
        R = jnp.eye(B.shape[1]) * action_cost

        act = Actor(A=A, B=B, F=F, V=V, W=W, Q=Q, R=R, T=T)

        super().__init__(actor=act, dynamics=dyn)

Control & Estimation

lqg.control.lqr

Gains

Bases: NamedTuple

LQR control gains, giving the optimal action u[t] = L[t] x[t] + k[t].

Attributes:

Name Type Description
L ndarray

feedback gains of shape (T, udim, xdim)

k ndarray

feedforward terms of shape (T, udim)

H ndarray

regularized Hessians of the cost-to-go with respect to the action, of shape (T, udim, udim)

Source code in lqg/control/lqr.py
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Gains(NamedTuple):
    """LQR control gains, giving the optimal action ``u[t] = L[t] x[t] + k[t]``.

    Attributes:
        L (jnp.ndarray): feedback gains of shape (T, udim, xdim)
        k (jnp.ndarray): feedforward terms of shape (T, udim)
        H (jnp.ndarray): regularized Hessians of the cost-to-go with respect to
            the action, of shape (T, udim, udim)
    """

    L: jnp.ndarray
    k: jnp.ndarray
    H: jnp.ndarray = None

backward(spec, eps=1e-08)

Compute optimal control gains with a backward pass (Riccati recursion).

Solves the linear-quadratic regulator for the dynamics and cost in spec, ignoring noise. By the separation principle, these gains are also optimal for the noisy, partially observed problem when applied to the Kalman filter estimate of the state.

Parameters:

Name Type Description Default
spec LQGSpec

problem specification

required
eps float

minimum eigenvalue of H. H is shifted by a multiple of the identity to reach it if needed, which keeps the problem well-posed when R is not positive definite (see section 5.4.1 of Li's PhD thesis).

1e-08

Returns:

Type Description
Gains

the control gains for each time step

Source code in lqg/control/lqr.py
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
def backward(spec: LQGSpec, eps: float = 1e-8) -> Gains:
    """Compute optimal control gains with a backward pass (Riccati recursion).

    Solves the linear-quadratic regulator for the dynamics and cost in
    ``spec``, ignoring noise. By the separation principle, these gains are
    also optimal for the noisy, partially observed problem when applied to
    the Kalman filter estimate of the state.

    Args:
        spec (LQGSpec): problem specification
        eps (float): minimum eigenvalue of ``H``. ``H`` is shifted by a multiple
            of the identity to reach it if needed, which keeps the problem
            well-posed when ``R`` is not positive definite (see section 5.4.1 of
            Li's PhD thesis).

    Returns:
        Gains: the control gains for each time step
    """

    def loop(carry, step):
        S, s = carry

        Q, q, P, R, r, A, B = step

        H = R + B.T @ S @ B
        G = P + B.T @ S @ A
        g = r + B.T @ s

        # Deal with negative eigenvals of H, see section 5.4.1 of Li's PhD thesis
        evals, _ = jnp.linalg.eigh(H)
        Ht = H + jnp.maximum(0.0, eps - evals[0]) * jnp.eye(H.shape[0])

        L = -jnp.linalg.solve(Ht, G)
        k = -jnp.linalg.solve(Ht, g)

        S = Q + A.T @ S @ A + L.T @ H @ L + L.T @ G + G.T @ L
        s = q + A.T @ s + G.T @ k + L.T @ H @ k + L.T @ g

        return (S, s), (L, k, Ht)

    _, (L, k, H) = lax.scan(
        loop,
        (spec.Qf, spec.qf),
        (spec.Q, spec.q, spec.P, spec.R, spec.r, spec.A, spec.B),
        reverse=True,
    )

    return Gains(L=L, k=k, H=H)

lqg.belief.kf

forward(spec, Sigma0)

Compute Kalman gains with a forward pass.

The belief is then updated as

x_pred    = A[t] xhat[t] + B[t] u[t]
xhat[t+1] = x_pred + K[t] (y[t+1] - F[t] x_pred)

Parameters:

Name Type Description Default
spec LQGSpec

problem specification, of which A, F, V and W are used

required
Sigma0 ndarray

initial covariance of the state estimate, of shape (xdim, xdim)

required

Returns:

Type Description
ndarray

Kalman gains of shape (T, xdim, ydim)

Source code in lqg/belief/kf.py
 6
 7
 8
 9
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
def forward(spec: LQGSpec, Sigma0: jnp.ndarray) -> jnp.ndarray:
    """Compute Kalman gains with a forward pass.

    The belief is then updated as

    ```
    x_pred    = A[t] xhat[t] + B[t] u[t]
    xhat[t+1] = x_pred + K[t] (y[t+1] - F[t] x_pred)
    ```

    Args:
        spec (LQGSpec): problem specification, of which ``A``, ``F``, ``V``
            and ``W`` are used
        Sigma0 (jnp.ndarray): initial covariance of the state estimate, of
            shape (xdim, xdim)

    Returns:
        jnp.ndarray: Kalman gains of shape (T, xdim, ydim)
    """

    def loop(P, step):
        A, F, V, W = step

        P = A @ P @ A.T + V @ V.T
        G = F @ P @ F.T + W @ W.T
        K = P @ F.T @ jnp.linalg.inv(G)

        P = (jnp.eye(P.shape[0]) - K @ F) @ P

        return P, K

    _, K = lax.scan(loop, Sigma0, (spec.A, spec.F, spec.V, spec.W))

    return K

Inference & Models

lqg.infer.utils.infer(x, num_samples, num_warmup, model=BoundedActor, numpyro_fn=lqg_model, process_noise=1.0, dt=1.0 / 60, method='nuts', progress_bar=True, num_chains=1, seed=0, **fixed)

Bayesian inference of model parameters with MCMC.

Samples from the posterior over the parameters of model given observed trajectories, using NUTS. With method="neutra", a normalizing flow is first fit to the posterior with SVI (10,000 steps) and used to reparametrize the model, which can help with difficult posterior geometry.

Parameters:

Name Type Description Default
x array

observed trajectories of shape (n, T+1, d)

required
num_samples int

number of posterior samples per chain

required
num_warmup int

number of warmup steps per chain

required
model type

model class, e.g. BoundedActor

BoundedActor
numpyro_fn callable

numpyro model function defining the priors and the likelihood. Defaults to the model in lqg.infer.models with the default priors.

lifted_model
process_noise float

target random walk standard deviation, which is not estimated

1.0
dt float

duration of a time step in seconds

1.0 / 60
method str

"nuts" or "neutra"

'nuts'
progress_bar bool

whether to show a progress bar

True
num_chains int

number of MCMC chains

1
seed int

random seed

0
**fixed

parameters that are fixed to the given values (not estimated)

{}

Returns:

Type Description
MCMC

the MCMC object after running, e.g. use mcmc.get_samples() to get the posterior samples

Source code in lqg/infer/utils.py
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
def infer(
    x,
    num_samples,
    num_warmup,
    model=BoundedActor,
    numpyro_fn=lqg_model,
    process_noise=1.0,
    dt=1.0 / 60,
    method="nuts",
    progress_bar=True,
    num_chains=1,
    seed=0,
    **fixed,
):
    """Bayesian inference of model parameters with MCMC.

    Samples from the posterior over the parameters of ``model`` given observed
    trajectories, using NUTS. With ``method="neutra"``, a normalizing flow is
    first fit to the posterior with SVI (10,000 steps) and used to
    reparametrize the model, which can help with difficult posterior geometry.

    Args:
        x (jnp.array): observed trajectories of shape (n, T+1, d)
        num_samples (int): number of posterior samples per chain
        num_warmup (int): number of warmup steps per chain
        model (type): model class, e.g.
            [BoundedActor][lqg.tracking.basic.BoundedActor]
        numpyro_fn (callable): numpyro model function defining the priors and
            the likelihood. Defaults to the model in ``lqg.infer.models`` with
            the default priors.
        process_noise (float): target random walk standard deviation, which is
            not estimated
        dt (float): duration of a time step in seconds
        method (str): ``"nuts"`` or ``"neutra"``
        progress_bar (bool): whether to show a progress bar
        num_chains (int): number of MCMC chains
        seed (int): random seed
        **fixed: parameters that are fixed to the given values (not estimated)

    Returns:
        numpyro.infer.MCMC: the MCMC object after running, e.g. use
            ``mcmc.get_samples()`` to get the posterior samples
    """
    if method == "nuts":
        # setup kernel
        nuts_kernel = NUTS(numpyro_fn, init_strategy=init_to_median)

    elif method == "neutra":
        # learn normalizing flow
        guide = AutoBNAFNormal(numpyro_fn)
        svi = SVI(numpyro_fn, guide, optim.Adam(0.003), Trace_ELBO())
        svi_state = svi.init(random.PRNGKey(seed), x, model, process_noise, dt, **fixed)

        last_state, losses = lax.scan(
            lambda state, i: svi.update(state, x, model, process_noise, dt, **fixed),
            svi_state,
            jnp.zeros(10_000),
        )

        # reparametrize model
        neutra = NeuTraReparam(guide, svi.get_params(last_state))
        nuts_kernel = NUTS(neutra.reparam(numpyro_fn))

    else:
        raise ValueError("Please specify a valid inference method (nuts, neutra).")

    # run NUTS
    mcmc = MCMC(
        nuts_kernel,
        num_samples=num_samples,
        num_warmup=num_warmup,
        progress_bar=progress_bar,
        num_chains=num_chains,
    )
    mcmc.run(random.PRNGKey(seed), x, model, process_noise, dt, **fixed)

    return mcmc

lqg.infer.mle

max_likelihood(key, x, model=BoundedActor, numpyro_fn=lqg_model, max_steps=2000, constraints=None, num_restarts=5, **fixed)

Maximum likelihood estimation of the parameters of an LQG model.

The optimization is performed in an unconstrained space and mapped to the parameter space via the bijectors in constraints. It is repeated from num_restarts random initializations, and the solution with the lowest negative log likelihood is returned.

Parameters:

Name Type Description Default
key

jax.random.PRNGKey for sampling initial parameters

required
x

observed data of shape (n_trials, T, d)

required
model

model class (e.g. BoundedActor)

BoundedActor
numpyro_fn

numpyro model function defining the likelihood

lqg_model
max_steps

maximum number of optimization steps per restart

2000
constraints

dict mapping parameter names to bijectors (e.g. Box, LogBox). Parameters not in this dict use the bounds in default_constraints.

None
num_restarts

number of random restarts of the optimization

5
**fixed

parameters that are fixed to the given values (not estimated)

{}

Returns:

Type Description
dict

estimated parameters

Source code in lqg/infer/mle.py
 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
def max_likelihood(
    key,
    x,
    model=BoundedActor,
    numpyro_fn=lqg_model,
    max_steps=2_000,
    constraints=None,
    num_restarts=5,
    **fixed,
):
    """Maximum likelihood estimation of the parameters of an LQG model.

    The optimization is performed in an unconstrained space and mapped to the
    parameter space via the bijectors in ``constraints``. It is repeated from
    ``num_restarts`` random initializations, and the solution with the lowest
    negative log likelihood is returned.

    Args:
        key: jax.random.PRNGKey for sampling initial parameters
        x: observed data of shape (n_trials, T, d)
        model: model class (e.g. BoundedActor)
        numpyro_fn: numpyro model function defining the likelihood
        max_steps: maximum number of optimization steps per restart
        constraints: dict mapping parameter names to bijectors (e.g. Box, LogBox).
            Parameters not in this dict use the bounds in ``default_constraints``.
        num_restarts: number of random restarts of the optimization
        **fixed: parameters that are fixed to the given values (not estimated)

    Returns:
        dict: estimated parameters
    """
    constraints = {**default_constraints, **(constraints or {})}

    # bijectors are pytrees, so we close over them instead of passing them as args
    def loss(log_params, args):
        return _log_likelihood(log_params, args, constraints)

    def _fit(key):
        # sample initial parameters (in unconstrained space)
        initial_params = {
            name: random.normal(
                subkey,
                (),
            )
            for name, subkey in zip(
                get_model_params(model), random.split(key, len(get_model_params(model)))
            )
            if name not in fixed
        }
        solver = optx.LBFGS(rtol=1e-4, atol=1e-4)
        solution = optx.minimise(
            loss,
            solver,
            initial_params,
            args=(numpyro_fn, x, model, fixed),
            max_steps=max_steps,
            throw=False,
        )
        params = {
            name: constraints[name].forward(value)
            for name, value in solution.value.items()
        }
        return params, solution.state.f_info.f

    params, nll = jax.vmap(_fit)(random.split(key, num_restarts))
    params = {k: v[jnp.argmin(nll)] for k, v in params.items()}

    return params  # , losses

parameter_recovery(key, model, num_datasets=100, T=500, num_trials=20, obs_dim=2, constraints=None, max_steps=1000, num_restarts=10, progress=True, **fixed)

Parameter recovery analysis for a model class.

For each of num_datasets repetitions, true parameters are sampled within the bounds of constraints (see sample_within_bounds), data are simulated from the model, and the parameters are estimated with max_likelihood.

Parameters:

Name Type Description Default
key

jax.random.PRNGKey

required
model

model class (e.g. BoundedActor)

required
num_datasets

number of simulated data sets

100
T

number of time steps per trial

500
num_trials

number of trials per data set

20
obs_dim

number of state dimensions used for fitting (as in experimental data, where only target and cursor position are observed)

2
constraints

dict mapping parameter names to bijectors (e.g. Box, LogBox). Parameters not in this dict use the bounds in default_constraints.

None
max_steps

maximum number of optimization steps per restart

1000
num_restarts

number of random restarts of the optimization

10
progress

show a progress bar

True
**fixed

parameters that are fixed to the given values (not estimated)

{}

Returns:

Type Description

dict with entries "true" and "estimate": dicts mapping parameter names to arrays of shape (num_datasets,), "ll_true" and "ll_estimate": log likelihood of the data at the true and estimated parameters. An estimate that is far from the true value but has a higher likelihood points to a non-identifiable parameter, a lower likelihood to a failed optimization.

Source code in lqg/infer/mle.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
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
def parameter_recovery(
    key,
    model,
    num_datasets=100,
    T=500,
    num_trials=20,
    obs_dim=2,
    constraints=None,
    max_steps=1_000,
    num_restarts=10,
    progress=True,
    **fixed,
):
    """Parameter recovery analysis for a model class.

    For each of ``num_datasets`` repetitions, true parameters are sampled within the
    bounds of ``constraints`` (see ``sample_within_bounds``), data are simulated from
    the model, and the parameters are estimated with ``max_likelihood``.

    Args:
        key: jax.random.PRNGKey
        model: model class (e.g. BoundedActor)
        num_datasets: number of simulated data sets
        T: number of time steps per trial
        num_trials: number of trials per data set
        obs_dim: number of state dimensions used for fitting (as in experimental data,
            where only target and cursor position are observed)
        constraints: dict mapping parameter names to bijectors (e.g. Box, LogBox).
            Parameters not in this dict use the bounds in ``default_constraints``.
        max_steps: maximum number of optimization steps per restart
        num_restarts: number of random restarts of the optimization
        progress: show a progress bar
        **fixed: parameters that are fixed to the given values (not estimated)

    Returns:
        dict with entries
            "true" and "estimate": dicts mapping parameter names to arrays of shape (num_datasets,),
            "ll_true" and "ll_estimate": log likelihood of the data at the true and estimated
                parameters. An estimate that is far from the true value but has a higher
                likelihood points to a non-identifiable parameter, a lower likelihood
                to a failed optimization.
    """
    constraints = {**default_constraints, **(constraints or {})}
    free = [name for name in get_model_params(model) if name not in fixed]
    missing = [name for name in free if name not in constraints]
    if missing:
        raise ValueError(
            f"No constraints for {missing}: pass them in `constraints` or fix them."
        )

    results = {
        "true": {name: [] for name in free},
        "estimate": {name: [] for name in free},
    }
    results["ll_true"], results["ll_estimate"] = [], []

    keys = random.split(key, num_datasets)
    if progress:
        from tqdm import tqdm

        keys = tqdm(keys)

    for dataset_key in keys:
        key_params, key_sim, key_fit = random.split(dataset_key, 3)

        true_params = {
            name: sample_within_bounds(subkey, name, constraints)
            for name, subkey in zip(free, random.split(key_params, len(free)))
        }
        x = model(**true_params, **fixed, T=T).simulate(rng_key=key_sim, n=num_trials)
        x = x[..., :obs_dim]

        estimates = max_likelihood(
            key=key_fit,
            x=x,
            model=model,
            constraints=constraints,
            max_steps=max_steps,
            num_restarts=num_restarts,
            **fixed,
        )

        for name in free:
            results["true"][name].append(true_params[name])
            results["estimate"][name].append(estimates[name])
        results["ll_true"].append(
            model(**true_params, **fixed, T=T).log_likelihood(x).sum()
        )
        results["ll_estimate"].append(
            model(**estimates, **fixed, T=T).log_likelihood(x).sum()
        )

    return {
        "true": {name: jnp.array(v) for name, v in results["true"].items()},
        "estimate": {name: jnp.array(v) for name, v in results["estimate"].items()},
        "ll_true": jnp.array(results["ll_true"]),
        "ll_estimate": jnp.array(results["ll_estimate"]),
    }

plot_parameter_recovery(results, constraints=None)

Scatter plots of true vs. estimated parameters from parameter_recovery.

Parameters with a LogBox constraint are shown on a log scale.

Source code in lqg/infer/mle.py
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
def plot_parameter_recovery(results, constraints=None):
    """Scatter plots of true vs. estimated parameters from ``parameter_recovery``.

    Parameters with a LogBox constraint are shown on a log scale.
    """
    import matplotlib.pyplot as plt

    constraints = {**default_constraints, **(constraints or {})}
    names = list(results["true"])

    figure, axes = plt.subplots(
        1, len(names), figsize=(3 * len(names), 3), squeeze=False
    )
    for axis, name in zip(axes.flat, names):
        true, estimate = results["true"][name], results["estimate"][name]
        lims = [min(true.min(), estimate.min()), max(true.max(), estimate.max())]
        axis.scatter(true, estimate, alpha=0.7)
        axis.plot(lims, lims, "k--", alpha=0.5)
        axis.set_title(name)
        axis.set_xlabel("simulated value")
        if isinstance(constraints.get(name), LogBox):
            axis.set_xscale("log")
            axis.set_yscale("log")
    axes.flat[0].set_ylabel("estimated value")
    figure.tight_layout()
    return figure

lqg.infer.models

shared_params_lqg_model(x, model_type, process_noise=1.0, dt=1.0 / 60.0, priors=None, shared_params=None, dim=1, **fixed_params)

numpyro model for LQG models with shared parameter

Parameters:

Name Type Description Default
x

data

required
process_noise

target random walk standard deviation

1.0
dt

time step duration

1.0 / 60.0
priors

dict of prio distributions

None
shared_params

list of parameter names that are shared across conditions

None
dim

dimensionality of the state

1
**fixed_params

any parameter that should be fixed (i.e. not estimated from the data)

{}
Source code in lqg/infer/models.py
 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 shared_params_lqg_model(
    x,
    model_type,
    process_noise=1.0,
    dt=1.0 / 60.0,
    priors=None,
    shared_params=None,
    dim=1,
    **fixed_params,
):
    """numpyro model for LQG models with shared parameter

    Args:
        x: data
        process_noise: target random walk standard deviation
        dt: time step duration
        priors: dict of prio distributions
        shared_params: list of parameter names that are shared across conditions
        dim: dimensionality of the state
        **fixed_params: any parameter that should be fixed (i.e. not estimated from the data)

    """
    # data shape is conditions, trials, time steps, state dimensionality
    Nc, N, T, d = x.shape

    # if not specifying extra priors, use the default ones from above
    if priors is None:
        priors = default_prior

    # which parameters will be shared across conditions?
    if shared_params is None:
        shared_params = []
    shared_params = set(shared_params)

    # get the parameter names of the current model type
    model_params = set(get_model_params(model_type).keys())

    # set up empty dict of parameters
    params = {}

    # these parameters will be shared across conditions
    for name in shared_params.intersection(model_params):
        # if a parameter is given in the fixed_params dict, we assume a fixed (user-specified) value
        if name in fixed_params:
            params[name] = fixed_params[name]
        # if not, we use one prior distribution across conditions
        else:
            params[name] = numpyro.sample(name, priors[name])

    # iterate over conditions
    for n in range(Nc):
        # get the data array for the current condition
        xn = x[n]

        # for those parameters that are not shared across conditions
        for name in model_params - shared_params:
            # define a prior distribution for that parameter in the current condition
            params[name] = numpyro.sample(f"{name}_{n}", priors[name])

        # set up the model, passing both shared and condition-specific parameters via the params dict
        lqg = model_type(process_noise=process_noise, dt=dt, T=T, dim=dim, **params)

        # likelihood
        numpyro.sample(f"x_{n}", lqg.conditional_distribution(xn), obs=xn[:, 1:])

lqg.infer.prior

Utilities & I/O

lqg.io

load_tracking_data(delay=12, clip=120, subtract_mean=True, data_path='data/')

Load tracking data from Bonnen et al. (2015)

Parameters:

Name Type Description Default
delay

temporal delay between target and response

12
clip

clip the first n time steps

120
subtract_mean

subtract the mean of both trajectories?

True

Returns:

Type Description
array

data from tracking task

Source code in lqg/io.py
 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
def load_tracking_data(delay=12, clip=120, subtract_mean=True, data_path="data/"):
    """Load tracking data from Bonnen et al. (2015)

    Args:
        delay: temporal delay between target and response
        clip: clip the first n time steps
        subtract_mean: subtract the mean of both trajectories?

    Returns:
        np.array: data from tracking task
    """

    # factor to convert between pixels and acrmin
    arcscale = 1.32

    # load matlab file
    mat = loadmat(os.path.join(data_path, "data.mat"))

    # get target blob widths
    sigma = (mat["sigma"] * arcscale).round()
    sigmas = np.unique(sigma)

    # convert to numpy.float32
    target = mat["target"].astype(np.float32)
    mouse = mat["response"].astype(np.float32)

    # apply delay and clip the first couple of time steps
    if delay:
        target = target[:, clip:-delay]
        mouse = mouse[:, clip + delay :]
    else:
        target = target[:, clip:]
        mouse = mouse[:, clip:]

    # subtract the mean from both trajectories (in accordance with the analysis by Bonnen et al., 2015)
    # see https://github.com/kbonnen/BonnenEtAl2015_KalmanFilterCode/blob/master/tracking2graphs.m
    if subtract_mean:
        target = target - np.mean(target, axis=1, keepdims=True)
        mouse = mouse - np.mean(mouse, axis=1, keepdims=True)

    # stack data from all trials
    data = np.stack(
        [
            np.array(
                [
                    target[np.where(sigma == blob_width)[0], :],
                    mouse[np.where(sigma == blob_width)[0], :],
                ]
            )
            for blob_width in sigmas
        ]
    )

    # bring in right shape for our analysis methods
    data = data.transpose(0, 2, 3, 1)

    # subtract first time step in x dimension
    data = data - data[:, :, 0, 0][:, :, np.newaxis, np.newaxis]

    return data, sigmas

loadmat(filename)

this function should be called instead of direct spio.loadmat as it cures the problem of not properly recovering python dictionaries from mat files. It calls the function check keys to cure all entries which are still mat-objects

Source code in lqg/io.py
10
11
12
13
14
15
16
17
18
def loadmat(filename):
    """
    this function should be called instead of direct spio.loadmat
    as it cures the problem of not properly recovering python dictionaries
    from mat files. It calls the function check keys to cure all entries
    which are still mat-objects
    """
    data = spio.loadmat(filename, struct_as_record=False, squeeze_me=True)
    return _check_keys(data)

lqg.optim

A collection of helper functions for optimization with JAX.

minimize(fun, x0, method=None, args=(), bounds=None, constraints=(), tol=None, callback=None, options=None)

A simple wrapper for scipy.optimize.minimize using JAX.

The objective is differentiated automatically with JAX, and parameters can be arbitrary PyTrees. The remaining keyword arguments are passed through to scipy.optimize.minimize; see its documentation for details.

Parameters:

Name Type Description Default
fun callable

The objective function to be minimized, written in JAX code so that it is automatically differentiable. Its signature is fun(x, *args) -> float, where x is a PyTree and args is a tuple of the fixed parameters needed to completely specify the function.

required
x0

Initial guess represented as a JAX PyTree.

required
method str or callable

Type of solver, e.g. "BFGS", "L-BFGS-B" or "SLSQP". If not given, chosen to be one of BFGS, L-BFGS-B, SLSQP, depending on whether the problem has constraints or bounds.

None
args tuple

Extra arguments passed to the objective function and its derivative. Must consist of valid JAX types; e.g. the leaves of the PyTree must be floats.

()
bounds sequence or Bounds

Bounds on variables for L-BFGS-B, TNC, SLSQP, Powell, and trust-constr methods. Bounds must be flattened manually in the same order as the inputs x0.

None
constraints Constraint, dict or list thereof

Constraints definition (only for COBYLA, SLSQP and trust-constr). Constraints must be flattened manually in the same order as the inputs x0.

()
tol float

Tolerance for termination.

None
callback callable

Called after each iteration as callback(xk), where xk is the current parameter vector represented as a PyTree.

None
options dict

A dictionary of solver options, e.g. maxiter or disp.

None

Returns:

Type Description
OptimizeResult

The optimization result. Its x attribute holds the solution, represented as a JAX PyTree.

Source code in lqg/optim.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
def minimize(
    fun,
    x0,
    method=None,
    args=(),
    bounds=None,
    constraints=(),
    tol=None,
    callback=None,
    options=None,
):
    """A simple wrapper for `scipy.optimize.minimize` using JAX.

    The objective is differentiated automatically with JAX, and parameters can
    be arbitrary PyTrees. The remaining keyword arguments are passed through to
    [`scipy.optimize.minimize`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html);
    see its documentation for details.

    Args:
        fun (callable): The objective function to be minimized, written in JAX
            code so that it is automatically differentiable. Its signature is
            `fun(x, *args) -> float`, where `x` is a PyTree and `args` is a
            tuple of the fixed parameters needed to completely specify the
            function.
        x0: Initial guess represented as a JAX PyTree.
        method (str or callable, optional): Type of solver, e.g. `"BFGS"`,
            `"L-BFGS-B"` or `"SLSQP"`. If not given, chosen to be one of
            `BFGS`, `L-BFGS-B`, `SLSQP`, depending on whether the problem has
            constraints or bounds.
        args (tuple, optional): Extra arguments passed to the objective function
            and its derivative. Must consist of valid JAX types; e.g. the leaves
            of the PyTree must be floats.
        bounds (sequence or Bounds, optional): Bounds on variables for
            L-BFGS-B, TNC, SLSQP, Powell, and trust-constr methods. Bounds must
            be flattened manually in the same order as the inputs `x0`.
        constraints (Constraint, dict or list thereof, optional): Constraints
            definition (only for COBYLA, SLSQP and trust-constr). Constraints
            must be flattened manually in the same order as the inputs `x0`.
        tol (float, optional): Tolerance for termination.
        callback (callable, optional): Called after each iteration as
            `callback(xk)`, where `xk` is the current parameter vector
            represented as a PyTree.
        options (dict, optional): A dictionary of solver options, e.g.
            `maxiter` or `disp`.

    Returns:
        scipy.optimize.OptimizeResult: The optimization result. Its `x`
            attribute holds the solution, represented as a JAX PyTree.
    """
    # Use tree flatten and unflatten to convert params x0 from PyTrees to flat arrays
    x0_flat, unravel = ravel_pytree(x0)

    # Wrap the objective function to consume flat _original_
    # numpy arrays and produce scalar outputs.
    def fun_wrapper(x_flat, *args):
        x = unravel(x_flat)
        return float(fun(x, *args))

    # Wrap the gradient in a similar manner
    jac = jit(grad(fun))

    def jac_wrapper(x_flat, *args):
        x = unravel(x_flat)
        g_flat, _ = ravel_pytree(jac(x, *args))
        return onp.array(g_flat)

    # Wrap the callback to consume a pytree
    def callback_wrapper(x_flat, *args):
        if callback is not None:
            x = unravel(x_flat)
            return callback(x, *args)

    # Minimize with scipy
    results = scipy.optimize.minimize(
        fun_wrapper,
        x0_flat,
        args=args,
        method=method,
        jac=jac_wrapper,
        callback=callback_wrapper,
        bounds=bounds,
        constraints=constraints,
        tol=tol,
        options=options,
    )

    # pack the output back into a PyTree
    results["x"] = unravel(results["x"])
    return results

lqg.utils