galrax 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
galrax/__init__.py ADDED
@@ -0,0 +1,10 @@
1
+ """Galrax: exact p-adic dynamics, diffusion on the p-adic integers, and differential
2
+ equations on finite groups, in JAX.
3
+
4
+ - `galrax.padic`: flows `dx/dt = f(x)` on `Z_p^d`, exact modulo `p^K`, maps, orbits,
5
+ normal forms and formal groups.
6
+ - `galrax.ultrametric`: diffusion on `Z_p` and Kozyrev wavelets.
7
+ - `galrax.groups`: differential equations on finite groups, solved with Diffrax.
8
+ """
9
+
10
+ __version__ = "0.2.0"
galrax/_types.py ADDED
@@ -0,0 +1,19 @@
1
+ """The Diffrax type aliases used by `galrax.groups` (private in Diffrax)."""
2
+
3
+ from typing import Any, TYPE_CHECKING
4
+
5
+ import numpy as np
6
+ from jaxtyping import Array, ArrayLike, Bool, PyTree, Real, Shaped
7
+
8
+
9
+ if TYPE_CHECKING:
10
+ BoolScalarLike = bool | Array | np.ndarray
11
+ RealScalarLike = int | float | Array | np.ndarray
12
+ else:
13
+ BoolScalarLike = Bool[ArrayLike, ""]
14
+ RealScalarLike = Real[ArrayLike, ""]
15
+
16
+ Y = PyTree[Shaped[ArrayLike, "?*y"], "Y"]
17
+ VF = PyTree[Shaped[ArrayLike, "?*vf"], "VF"]
18
+ Args = PyTree[Any]
19
+ DenseInfo = dict[str, PyTree[Array]]
@@ -0,0 +1,32 @@
1
+ """Differential equations on finite groups.
2
+
3
+ Functions on a finite group `G`, convolution equations
4
+ `dp/dt = lambda * p + p * mu + N(t, p)`, Fourier transforms on `G` (direct and fast),
5
+ and solvers that integrate the convolution part exactly.
6
+ """
7
+
8
+ from .fourier import (
9
+ AbstractFourierTransform as AbstractFourierTransform,
10
+ AbstractSpectralTransform as AbstractSpectralTransform,
11
+ convolution as convolution,
12
+ FastFourierTransform as FastFourierTransform,
13
+ FourierTransform as FourierTransform,
14
+ subgroup_chain as subgroup_chain,
15
+ subgroup_closure as subgroup_closure,
16
+ )
17
+ from .group import Group as Group
18
+ from .problem import GroupODE as GroupODE
19
+ from .solver import (
20
+ exact_linear_solution as exact_linear_solution,
21
+ fourier_term as fourier_term,
22
+ fourier_terms as fourier_terms,
23
+ GroupSolution as GroupSolution,
24
+ Lawson as Lawson,
25
+ physical_term as physical_term,
26
+ solve_group_ode as solve_group_ode,
27
+ )
28
+ from .terms import (
29
+ AbstractExponentialTerm as AbstractExponentialTerm,
30
+ DiagonalLinearTerm as DiagonalLinearTerm,
31
+ FourierLinearTerm as FourierLinearTerm,
32
+ )
@@ -0,0 +1,508 @@
1
+ from collections import deque
2
+
3
+ import jax
4
+ import jax.numpy as jnp
5
+ import numpy as np
6
+
7
+ from .group import Group
8
+ from .terms import AbstractExponentialTerm, FourierLinearTerm
9
+
10
+
11
+ def subgroup_closure(group: Group, generators) -> np.ndarray:
12
+ """The subgroup generated by `generators`, as a sorted array of element numbers."""
13
+ generators = np.unique(np.asarray(generators, dtype=np.int64))
14
+ inside = np.zeros(group.n, dtype=bool)
15
+ inside[group.ed] = True
16
+ frontier = np.array([group.ed])
17
+ while len(frontier) > 0 and len(generators) > 0:
18
+ products = np.unique(group.kaili[np.ix_(frontier, generators)])
19
+ frontier = products[~inside[products]]
20
+ inside[frontier] = True
21
+ return np.flatnonzero(inside)
22
+
23
+
24
+ def subgroup_chain(group: Group) -> list[np.ndarray]:
25
+ """A chain of subgroups `{e} = G_0 < G_1 < ... < G_m = G`, built greedily: each
26
+ `G_i` is generated by `G_{i-1}` and one more element, chosen so that the index
27
+ `[G_i : G_{i-1}]` is as small as possible.
28
+ """
29
+ chain = [np.array([group.ed])]
30
+ generators = []
31
+ while len(chain[-1]) < group.n:
32
+ inside = np.zeros(group.n, dtype=bool)
33
+ inside[chain[-1]] = True
34
+ best = None
35
+ for g in np.flatnonzero(~inside):
36
+ candidate = subgroup_closure(group, generators + [g])
37
+ if best is None or len(candidate) < len(best[1]):
38
+ best = (int(g), candidate)
39
+ if len(candidate) == 2 * len(chain[-1]):
40
+ break
41
+ generators.append(best[0])
42
+ chain.append(best[1])
43
+ return chain
44
+
45
+
46
+ def convolution(group: Group, f, h):
47
+ """The convolution `(f * h)(x) = sum_y f(y) h(y^{-1} x)`, computed directly in
48
+ `O(n^2)` operations. Both arguments have shape `(..., n)`.
49
+ """
50
+ f = jnp.asarray(f)
51
+ h = jnp.asarray(h)
52
+ dtype = np.result_type(f.dtype, h.dtype)
53
+ f = f.astype(dtype)
54
+ h = h.astype(dtype)
55
+ return jnp.einsum("...y,...yx->...x", f, h[..., group.kaili[group.inv]])
56
+
57
+
58
+ def _complex_dtype():
59
+ return jnp.asarray(1j).dtype
60
+
61
+
62
+ class AbstractSpectralTransform:
63
+ """A linear change of coordinates for functions on a finite group in which the
64
+ linear part of a `GroupODE` can be exponentiated exactly.
65
+
66
+ Coordinates are real: a tuple of arrays of shape `(2, ...)` holding the real and
67
+ imaginary parts of complex blocks. Solvers work in these coordinates, so they
68
+ should be an isometry (up to a constant) of the values on the group, for error
69
+ control to mean the same thing in both spaces.
70
+ """
71
+
72
+ group: Group
73
+
74
+ def to_coordinates(self, f) -> tuple:
75
+ """The real coordinates of a function `f` of shape `(..., n)`."""
76
+ raise NotImplementedError
77
+
78
+ def from_coordinates(self, y):
79
+ """The function on the group with real coordinates `y`."""
80
+ raise NotImplementedError
81
+
82
+ def linear_term(self, problem) -> AbstractExponentialTerm:
83
+ """The linear part of a `GroupODE` in these coordinates."""
84
+ raise NotImplementedError
85
+
86
+
87
+ class AbstractFourierTransform(AbstractSpectralTransform):
88
+ """Fourier transform on a finite group `G` with respect to a complete set of
89
+ unitary irreducible representations `rho_1, ..., rho_h`:
90
+
91
+ `fhat(rho) = sum_g f(g) rho(g)`,
92
+
93
+ `f(g) = (1/n) sum_rho d_rho tr(rho(g)^H fhat(rho))`.
94
+
95
+ Functions on `G` are arrays of shape `(..., n)`; transforms are lists with one
96
+ array of shape `(..., d_r, d_r)` per representation. The representations are
97
+ computed once with NumPy; `forward` and `inverse` are JAX functions, so they can be
98
+ used under `jax.jit`, `jax.vmap` and `jax.grad`.
99
+
100
+ `to_coordinates` and `from_coordinates` convert to the real coordinates used to
101
+ solve differential equations: the blocks `sqrt(d_rho / n) fhat(rho)`, split into
102
+ real and imaginary parts. In these coordinates the transform is an isometry.
103
+ """
104
+
105
+ group: Group
106
+ representations: list[np.ndarray]
107
+
108
+ @property
109
+ def degrees(self) -> np.ndarray:
110
+ return np.array([rep.shape[1] for rep in self.representations])
111
+
112
+ def forward(self, f) -> list:
113
+ raise NotImplementedError
114
+
115
+ def inverse(self, fhat):
116
+ raise NotImplementedError
117
+
118
+ def convolve(self, f, h):
119
+ """The convolution `f * h`, through `(f * h)^(rho) = fhat(rho) hhat(rho)`."""
120
+ fhat = self.forward(f)
121
+ hhat = self.forward(h)
122
+ return self.inverse([a @ b for a, b in zip(fhat, hhat)])
123
+
124
+ def to_coordinates(self, f) -> tuple:
125
+ """Real coordinates of `f`: for each representation, an array of shape
126
+ `(2, ..., d, d)` holding the real and imaginary parts of
127
+ `sqrt(d / n) fhat(rho)`.
128
+ """
129
+ n = self.group.n
130
+ return tuple(
131
+ jnp.stack([a.real, a.imag]) * float(np.sqrt(d / n))
132
+ for a, d in zip(self.forward(f), self.degrees)
133
+ )
134
+
135
+ def from_coordinates(self, y):
136
+ n = self.group.n
137
+ return self.inverse(
138
+ [
139
+ jax.lax.complex(b[0], b[1]) * float(np.sqrt(n / d))
140
+ for b, d in zip(y, self.degrees)
141
+ ]
142
+ )
143
+
144
+ def linear_term(self, problem) -> FourierLinearTerm:
145
+ return FourierLinearTerm.from_problem(problem, self)
146
+
147
+ def _check_function(self, f):
148
+ f = jnp.asarray(f)
149
+ if f.ndim == 0 or f.shape[-1] != self.group.n:
150
+ raise ValueError(
151
+ f"Functions on the group must have shape (..., {self.group.n})."
152
+ )
153
+ return f.astype(_complex_dtype())
154
+
155
+ def _check_transform(self, fhat) -> list:
156
+ fhat = [jnp.asarray(a).astype(_complex_dtype()) for a in fhat]
157
+ if len(fhat) != len(self.representations):
158
+ raise ValueError(
159
+ f"Expected {len(self.representations)} Fourier coefficients."
160
+ )
161
+ batch = fhat[0].shape[:-2]
162
+ for a, d in zip(fhat, self.degrees):
163
+ if a.shape != batch + (d, d):
164
+ raise ValueError("Fourier coefficients have inconsistent shapes.")
165
+ return fhat
166
+
167
+
168
+ class FourierTransform(AbstractFourierTransform):
169
+ """The Fourier transform computed directly from its definition, in `O(n^2)`
170
+ operations.
171
+
172
+ **Arguments:**
173
+
174
+ - `group`: the group.
175
+ - `representations`: unitary irreducible representations, each of shape
176
+ `(n, d, d)`. Defaults to `group.irreducible_representations()`.
177
+ - `seed`: seed for computing the representations.
178
+ """
179
+
180
+ def __init__(self, group: Group, representations=None, seed: int = 0):
181
+ if representations is None:
182
+ representations = group.irreducible_representations(seed)
183
+ representations = [np.asarray(r, dtype=np.complex128) for r in representations]
184
+ for rep in representations:
185
+ if rep.ndim != 3 or rep.shape[0] != group.n or rep.shape[1] != rep.shape[2]:
186
+ raise ValueError("Representations must have shape (n, d, d).")
187
+ if sum(rep.shape[1] ** 2 for rep in representations) != group.n:
188
+ raise ValueError("Representations are not a complete set: sum d^2 != n.")
189
+ self.group = group
190
+ self.representations = representations
191
+
192
+ def forward(self, f) -> list:
193
+ f = self._check_function(f)
194
+ return [
195
+ jnp.einsum("...g,gij->...ij", f, rep.astype(f.dtype))
196
+ for rep in self.representations
197
+ ]
198
+
199
+ def inverse(self, fhat):
200
+ fhat = self._check_transform(fhat)
201
+ n = self.group.n
202
+ return sum(
203
+ (rep.shape[1] / n)
204
+ * jnp.einsum("...ij,gij->...g", a, rep.conj().astype(a.dtype))
205
+ for a, rep in zip(fhat, self.representations)
206
+ )
207
+
208
+
209
+ class _SparseMatrix:
210
+ def __init__(self, matrix: np.ndarray, atol: float):
211
+ matrix = np.asarray(matrix, dtype=np.complex128)
212
+ rows, cols = np.nonzero(np.abs(matrix) > atol)
213
+ self.shape = matrix.shape
214
+ self.nnz = len(rows)
215
+ self.dense = matrix if self.nnz > matrix.size // 4 else None
216
+ self.rows = rows
217
+ self.cols = cols
218
+ self.vals = matrix[rows, cols]
219
+
220
+ def __matmul__(self, x):
221
+ if self.dense is not None:
222
+ return self.dense.astype(x.dtype) @ x
223
+ products = self.vals.astype(x.dtype)[:, None] * x[..., self.cols, :]
224
+ out = jnp.zeros(x.shape[:-2] + (self.shape[0], x.shape[-1]), dtype=x.dtype)
225
+ return out.at[..., self.rows, :].add(products)
226
+
227
+
228
+ class _Level:
229
+ def __init__(self, elements, index, transversal, parents, factors, cosets):
230
+ self.elements = elements
231
+ self.index = index
232
+ self.transversal = transversal
233
+ self.parents = parents
234
+ self.factors = factors
235
+ self.cosets = cosets
236
+ self.representations = []
237
+ self.blocks = []
238
+ self.matrices = []
239
+ self.adjoints = []
240
+
241
+
242
+ def _check_chain(group: Group, chain) -> list[np.ndarray]:
243
+ chain = [np.unique(np.asarray(c, dtype=np.int64)) for c in chain]
244
+ if len(chain) == 0 or not np.array_equal(chain[0], [group.ed]):
245
+ raise ValueError("A subgroup chain must start with the trivial subgroup {e}.")
246
+ if len(chain[-1]) != group.n:
247
+ raise ValueError("A subgroup chain must end with the whole group.")
248
+ for small, large in zip(chain[:-1], chain[1:]):
249
+ if len(small) >= len(large) or not np.isin(small, large).all():
250
+ raise ValueError("A subgroup chain must be strictly increasing.")
251
+ for c in chain:
252
+ if not np.isin(group.kaili[np.ix_(c, c)], c).all():
253
+ raise ValueError("Every member of a subgroup chain must be a subgroup.")
254
+ return chain
255
+
256
+
257
+ def _generators(group: Group, chain) -> list[list[int]]:
258
+ generators = [[]]
259
+ for subgroup in chain[1:]:
260
+ current = list(generators[-1])
261
+ closure = subgroup_closure(group, current)
262
+ while len(closure) < len(subgroup):
263
+ current.append(int(np.setdiff1d(subgroup, closure)[0]))
264
+ closure = subgroup_closure(group, current)
265
+ generators.append(current)
266
+ return generators
267
+
268
+
269
+ def _transversal_tree(group: Group, elements, subgroup, generators) -> _Level:
270
+ index = len(elements) // len(subgroup)
271
+ label = np.full(group.n, -1, dtype=np.int64)
272
+ label[elements] = group.kaili[np.ix_(elements, subgroup)].min(axis=1)
273
+ parent = {group.ed: None}
274
+ order = [group.ed]
275
+ representative = {label[group.ed]: group.ed}
276
+ queue = deque([group.ed])
277
+ while queue and len(representative) < index:
278
+ t = queue.popleft()
279
+ for u in generators:
280
+ s = int(group.kaili[t, u])
281
+ if s in parent:
282
+ continue
283
+ parent[s] = (t, u)
284
+ order.append(s)
285
+ queue.append(s)
286
+ representative.setdefault(label[s], s)
287
+ if len(representative) < index:
288
+ raise ValueError("Generators do not reach every coset.")
289
+
290
+ keep = set()
291
+ for s in representative.values():
292
+ while s is not None and s not in keep:
293
+ keep.add(s)
294
+ s = None if parent[s] is None else parent[s][0]
295
+ nodes = [s for s in order if s in keep]
296
+ node_index = {s: i for i, s in enumerate(nodes)}
297
+ is_representative = set(representative.values())
298
+ transversal = [s for s in nodes if s in is_representative]
299
+ coset_index = {s: j for j, s in enumerate(transversal)}
300
+
301
+ parents = np.array([-1] + [node_index[parent[s][0]] for s in nodes[1:]])
302
+ factors = np.array([-1] + [parent[s][1] for s in nodes[1:]])
303
+ cosets = np.array([coset_index.get(s, -1) for s in nodes])
304
+ return _Level(elements, index, np.array(transversal), parents, factors, cosets)
305
+
306
+
307
+ def _adapt(rep, restriction, sub_representations, atol):
308
+ restricted = rep[restriction]
309
+ order = len(restriction)
310
+ d = rep.shape[1]
311
+ columns, blocks, offset = [], [], 0
312
+ for index, sub in enumerate(sub_representations):
313
+ e = sub.shape[1]
314
+ overlap = np.einsum("hii,hjj->", restricted, sub.conj()) / order
315
+ multiplicity = round(overlap.real)
316
+ if abs(overlap - multiplicity) > 1e-6:
317
+ raise RuntimeError("Restriction multiplicity is not an integer.")
318
+ if multiplicity == 0:
319
+ continue
320
+ units = (e / order) * np.einsum("ha,hij->aij", sub[:, :, 0].conj(), restricted)
321
+ eigvals, eigvecs = np.linalg.eigh((units[0] + units[0].conj().T) / 2)
322
+ vectors = eigvecs[:, eigvals > 0.5]
323
+ if vectors.shape[1] != multiplicity:
324
+ raise RuntimeError(
325
+ "Could not isolate the copies of a subgroup representation."
326
+ )
327
+ for c in range(multiplicity):
328
+ columns.extend(units @ vectors[:, c])
329
+ blocks.append((index, offset, e))
330
+ offset += e
331
+ basis = np.stack(columns, axis=1)
332
+ if basis.shape != (d, d) or not np.allclose(
333
+ basis.conj().T @ basis, np.eye(d), atol=atol
334
+ ):
335
+ raise RuntimeError("Adapted basis is not unitary.")
336
+ adapted = basis.conj().T @ rep @ basis
337
+ expected = np.zeros_like(restricted)
338
+ for index, offset, e in blocks:
339
+ expected[:, offset : offset + e, offset : offset + e] = sub_representations[
340
+ index
341
+ ]
342
+ if not np.allclose(adapted[restriction], expected, atol=atol):
343
+ raise RuntimeError("Adapted representation is not block diagonal.")
344
+ return adapted, blocks
345
+
346
+
347
+ class FastFourierTransform(AbstractFourierTransform):
348
+ """The fast Fourier transform along a chain of subgroups
349
+ `{e} = G_0 < G_1 < ... < G_m = G` (separation of variables: Beth, Clausen,
350
+ Maslen, Rockmore).
351
+
352
+ The representations of every `G_i` are put in a basis adapted to the chain: for
353
+ `h` in `G_{i-1}`, `rho(h)` is literally block diagonal, with blocks the adapted
354
+ representations of `G_{i-1}`. With `G_i = t_1 G_{i-1} + ... + t_k G_{i-1}`,
355
+
356
+ `fhat(rho) = sum_j rho(t_j) (+)_sigma fhat_j(sigma)`,
357
+
358
+ where `fhat_j` is the transform over `G_{i-1}` of `f` restricted to the coset
359
+ `t_j G_{i-1}`. Each transversal element is a word in generators of `G_i`, and the
360
+ words form a tree, so the sum is evaluated by Horner's rule along the tree. The
361
+ matrices of generators lying in `G_{i-1}` are block diagonal, and are applied as
362
+ sparse matrices; for `S_n` with adjacent transpositions this is Clausen's
363
+ algorithm.
364
+
365
+ **Arguments:**
366
+
367
+ - `group`: the group.
368
+ - `chain`: a list of arrays of element numbers, strictly increasing subgroups from
369
+ `{e}` to `G`. Defaults to `subgroup_chain(group)`.
370
+ - `seed`: seed for computing irreducible representations.
371
+ - `atol`: tolerance for the checks of the adapted bases, and below which matrix
372
+ entries are treated as zero.
373
+ """
374
+
375
+ def __init__(self, group: Group, chain=None, seed: int = 0, atol: float = 1e-8):
376
+ chain = subgroup_chain(group) if chain is None else _check_chain(group, chain)
377
+ generators = _generators(group, chain)
378
+ self.group = group
379
+ self.chain = chain
380
+ self.levels = []
381
+
382
+ previous = [np.ones((1, 1, 1), dtype=np.complex128)]
383
+ for i in range(1, len(chain)):
384
+ elements, subgroup = chain[i], chain[i - 1]
385
+ level = _transversal_tree(group, elements, subgroup, generators[i])
386
+ local = np.full(group.n, -1, dtype=np.int64)
387
+ local[elements] = np.arange(len(elements))
388
+ if len(elements) == group.n:
389
+ reps = group.irreducible_representations(seed)
390
+ else:
391
+ table = local[group.kaili[np.ix_(elements, elements)]]
392
+ reps = Group(table, check=False).irreducible_representations(seed)
393
+ factors = set(level.factors[1:].tolist())
394
+ for rep in reps:
395
+ adapted, blocks = _adapt(rep, local[subgroup], previous, atol)
396
+ level.representations.append(adapted)
397
+ level.blocks.append(blocks)
398
+ level.matrices.append(
399
+ {u: _SparseMatrix(adapted[local[u]], atol) for u in factors}
400
+ )
401
+ level.adjoints.append(
402
+ {
403
+ u: _SparseMatrix(adapted[local[u]].conj().T, atol)
404
+ for u in factors
405
+ }
406
+ )
407
+ self.levels.append(level)
408
+ previous = level.representations
409
+ self.representations = previous
410
+
411
+ order = np.array([group.ed])
412
+ for level in reversed(self.levels):
413
+ order = group.kaili[np.ix_(order, level.transversal)].reshape(-1)
414
+ if not np.array_equal(np.sort(order), np.arange(group.n)):
415
+ raise RuntimeError("Transversals do not factorise the group.")
416
+ self.order = order
417
+ self.unorder = np.argsort(order)
418
+
419
+ def operation_count(self) -> int:
420
+ """Number of complex multiplications in one forward transform."""
421
+ count = 0
422
+ cosets = self.group.n
423
+ for level in self.levels:
424
+ cosets //= level.index
425
+ for matrices, rep in zip(level.matrices, level.representations):
426
+ d = rep.shape[1]
427
+ for u in level.factors[1:].tolist():
428
+ count += cosets * matrices[u].nnz * d
429
+ return count
430
+
431
+ def forward(self, f) -> list:
432
+ f = self._check_function(f)
433
+ batch = f.shape[:-1]
434
+ n = self.group.n
435
+ x = f.reshape(-1, n)[:, self.order]
436
+ data = [x.reshape(x.shape[0], n, 1, 1)]
437
+ for level in self.levels:
438
+ pieces = [
439
+ p.reshape(p.shape[0], -1, level.index, *p.shape[2:]) for p in data
440
+ ]
441
+ data = []
442
+ for rep, blocks, matrices in zip(
443
+ level.representations, level.blocks, level.matrices
444
+ ):
445
+ d = rep.shape[1]
446
+ stacked = jnp.zeros(pieces[0].shape[:3] + (d, d), dtype=f.dtype)
447
+ for index, offset, e in blocks:
448
+ stacked = stacked.at[
449
+ ..., offset : offset + e, offset : offset + e
450
+ ].set(pieces[index])
451
+ sums = [None] * len(level.parents)
452
+ for node in reversed(range(len(level.parents))):
453
+ total = sums[node]
454
+ coset = level.cosets[node]
455
+ if coset >= 0:
456
+ term = stacked[:, :, coset]
457
+ total = term if total is None else total + term
458
+ if node == 0:
459
+ data.append(total)
460
+ else:
461
+ term = matrices[int(level.factors[node])] @ total
462
+ parent = level.parents[node]
463
+ sums[parent] = (
464
+ term if sums[parent] is None else sums[parent] + term
465
+ )
466
+ return [a.reshape(batch + a.shape[-2:]) for a in data]
467
+
468
+ def inverse(self, fhat):
469
+ fhat = self._check_transform(fhat)
470
+ batch = fhat[0].shape[:-2]
471
+ n = self.group.n
472
+ dtype = fhat[0].dtype
473
+ data = [(a.shape[-1] / n) * a.reshape(-1, 1, *a.shape[-2:]) for a in fhat]
474
+ for i in reversed(range(len(self.levels))):
475
+ level = self.levels[i]
476
+ below = (
477
+ self.levels[i - 1].representations if i > 0 else [np.ones((1, 1, 1))]
478
+ )
479
+ size = data[0].shape[:2]
480
+ pieces = [
481
+ jnp.zeros(size + (level.index, r.shape[1], r.shape[1]), dtype=dtype)
482
+ for r in below
483
+ ]
484
+ for a, blocks, adjoints in zip(data, level.blocks, level.adjoints):
485
+ values = [None] * len(level.parents)
486
+ for node in range(len(level.parents)):
487
+ if node == 0:
488
+ values[node] = a
489
+ else:
490
+ values[node] = (
491
+ adjoints[int(level.factors[node])]
492
+ @ values[level.parents[node]]
493
+ )
494
+ coset = level.cosets[node]
495
+ if coset >= 0:
496
+ for index, offset, e in blocks:
497
+ pieces[index] = (
498
+ pieces[index]
499
+ .at[:, :, coset]
500
+ .add(
501
+ values[node][
502
+ ..., offset : offset + e, offset : offset + e
503
+ ]
504
+ )
505
+ )
506
+ data = [p.reshape(p.shape[0], -1, *p.shape[3:]) for p in pieces]
507
+ x = data[0].reshape(-1, n)
508
+ return x[:, self.unorder].reshape(batch + (n,))