Source code for nifty.re.multi_grid.grid

#!/usr/bin/env python3

# SPDX-License-Identifier: GPL-2.0+ OR BSD-2-Clause
# Authors: Gordian Edenhofer, Philipp Frank

import operator
from dataclasses import field
from functools import reduce
from typing import Callable, Iterable, Optional

import jax.numpy as jnp
import numpy as np
import numpy.typing as npt
from jax import ShapeDtypeStruct, eval_shape
from jax.lax import select
from ..model import ModelMeta

[docs] class GridAtLevel(metaclass=ModelMeta): shape: npt.NDArray[np.int_] splits: Optional[npt.NDArray[np.int_]] parent_splits: Optional[npt.NDArray[np.int_]]
[docs] def __init__(self, shape, splits=None, parent_splits=None): self.shape = np.atleast_1d(shape) if splits is not None: splits = np.broadcast_to(splits, (self.ndim,)) if parent_splits is not None: parent_splits = np.broadcast_to(parent_splits, (self.ndim,)) self.splits = splits self.parent_splits = parent_splits
def _parse_index(self, index): index = jnp.asarray(index) if index.shape[0] != self.shape.size: ve = f"index {index} is of invalid length {index.shape[0]} for shape {self.shape}" raise IndexError(ve) # Follow jax-array style out of bounds handling shp_bc = self.shape[(slice(None),) + (np.newaxis,) * (index.ndim - 1)] index = select( jnp.abs(index) < shp_bc, index, (jnp.sign(index) * (shp_bc - 1)).astype(index.dtype), ) return index % shp_bc @property def size(self): return reduce(operator.mul, self.shape, 1) @property def ndim(self): return len(self.shape) @property def raw_grids(self): return (self,)
[docs] def refined_indices(self): if self.splits is None: raise IndexError("this level has no children") # TODO non-dense grid return np.mgrid[tuple(slice(0, sh) for sh in self.shape)]
def _is_index_refined(self, index): if self.splits is None: return jnp.zeros(index.shape[1:], dtype=bool) if index.ndim > 1 else False return jnp.ones(index.shape[1:], dtype=bool) if index.ndim > 1 else True
[docs] def resort(self, batched_ar, /): if batched_ar.ndim != 2 * self.ndim: raise ValueError if batched_ar.shape[1::2] != tuple(self.parent_splits): raise ValueError shp = batched_ar.shape return batched_ar.reshape(tuple(a * b for a, b in zip(shp[::2], shp[1::2])))
[docs] def children(self, index): if self.splits is None: raise IndexError("this level has no children") index = self._parse_index(index) f = self.splits[(slice(None),) + (np.newaxis,) * (index.ndim - 1)] c = np.mgrid[tuple(slice(sz) for sz in self.splits)].astype(index.dtype) c_bc = ( (slice(None),) + (np.newaxis,) * (index.ndim - 1) + (slice(None),) * self.ndim ) ids = index * f return ids[(slice(None),) * ids.ndim + (np.newaxis,) * self.ndim] + c[c_bc]
[docs] def neighborhood(self, index, window_size: Iterable[int]): index = self._parse_index(index) window_size = np.asarray(window_size) assert window_size.size == self.ndim c = np.mgrid[tuple(slice(sz) for sz in window_size)] c -= (window_size // 2)[(slice(None),) + (np.newaxis,) * self.ndim] c_bc = ( (slice(None),) + (np.newaxis,) * (index.ndim - 1) + (slice(None),) * self.ndim ) m_bc = (slice(None),) + (np.newaxis,) * (index.ndim - 1 + self.ndim) id_bc = (slice(None),) * index.ndim + (np.newaxis,) * self.ndim res = (index[id_bc] + c[c_bc]) % self.shape[m_bc] return res.astype(index.dtype)
[docs] def parent(self, index): if self.parent_splits is None: raise IndexError("you are alone in this world") index = self._parse_index(index) bc = (slice(None),) + (np.newaxis,) * (index.ndim - 1) return index // self.parent_splits[bc]
[docs] def index2coord(self, index): slc = (slice(None),) + (np.newaxis,) * (index.ndim - 1) return (index + 0.5) / self.shape[slc]
[docs] def coord2index(self, coord, dtype=np.int64, **kwargs): slc = (slice(None),) + (np.newaxis,) * (coord.ndim - 1) index = coord * self.shape[slc] - 0.5 if np.issubdtype(dtype, np.integer): index = np.rint(index).astype(dtype) return index else: raise ValueError(f"non-integer index dtype: {dtype}")
[docs] def index2volume(self, index): return np.array(1.0 / self.size)[(np.newaxis,) * index.ndim]
[docs] class Grid(metaclass=ModelMeta): """Dense grid with periodic boundary conditions.""" shape0: npt.NDArray[np.int_] = field(metadata=dict(static=True)) splits: tuple[npt.NDArray[np.int_]] = field(metadata=dict(static=True)) atLevel: Callable = field(metadata=dict(static=True))
[docs] def __init__(self, *, shape0, splits, atLevel=GridAtLevel): self.shape0 = np.atleast_1d(shape0) splits = (splits,) if isinstance(splits, int) else splits self.splits = tuple(np.broadcast_to(s, self.shape0.shape) for s in splits) self.atLevel = atLevel
@property def depth(self): return len(self.splits) def _parse_level(self, level): if np.abs(level) > self.depth: raise IndexError(f"{self.__class__.__name__} does not have level {level}") return level % (self.depth + 1)
[docs] def amend(self, splits): splits = (splits,) if isinstance(splits, int) else splits splits = tuple(np.broadcast_to(s, self.shape0.shape) for s in splits) return self.__class__( shape0=self.shape0, splits=self.splits + splits, atLevel=self.atLevel )
[docs] def at(self, level: int): level = self._parse_level(level) fct = 1 if level > 0: fct = np.array( [reduce(operator.mul, si) for si in zip(*self.splits[:level])] ) return self.atLevel( shape=self.shape0 * fct, splits=self.splits[level] if level < self.depth else None, parent_splits=self.splits[level - 1] if level >= 1 else None, )
[docs] class OpenGridAtLevel(GridAtLevel): padding: Optional[npt.NDArray[np.int_]] parent_padding: Optional[npt.NDArray[np.int_]] shifts: Optional[npt.NDArray[np.int_]]
[docs] def __init__( self, shape, splits=None, parent_splits=None, *, padding=None, parent_padding=None, shifts=None, level=None, all_splits=None, ): super().__init__(shape=shape, splits=splits, parent_splits=parent_splits) if padding is not None: padding = np.broadcast_to(padding, (self.ndim,)) if parent_padding is not None: parent_padding = np.broadcast_to(parent_padding, (self.ndim,)) if shifts is not None: shifts = np.broadcast_to(shifts, (self.ndim,)) self.padding = padding self.parent_padding = parent_padding self.shifts = shifts del level, all_splits # not used here but used by child classes
[docs] def refined_indices(self): if self.splits is None: raise IndexError("ths level has no children") # TODO non-dense grid return np.mgrid[ tuple(slice(pp, sh - pp) for sh, pp in zip(self.shape, self.padding)) ]
def _is_index_refined(self, index): if self.splits is None: return jnp.zeros(index.shape[1:], dtype=bool) if index.ndim > 1 else False isin = ( (ii >= pp) * (ii < sh - pp) for ii, pp, sh in zip(index, self.padding, self.shape) ) return reduce(operator.mul, isin, 1)
[docs] def children(self, index): if (self.splits is None) or (self.padding is None): raise IndexError("this level has no children") lo = self.padding[(slice(None),) + (np.newaxis,) * (index.ndim - 1)] hi = self.shape[(slice(None),) + (np.newaxis,) * (index.ndim - 1)] - lo # TODO add option for fully jax transformable error handling # Follow jax-array inspired out of bounds handling return super().children(index.clip(lo, hi - 1) - lo)
[docs] def neighborhood(self, index, window_size: Iterable[int]): # TODO add option for fully jax transformable error handling # Follow jax-array inspired out of bounds handling shp_bc = self.shape[ (slice(None),) + (np.newaxis,) * (index.ndim - 1 + self.ndim) ] return super().neighborhood(index, window_size).clip(0, (shp_bc - 1))
[docs] def parent(self, index): if self.parent_splits is None: raise IndexError("you are alone in this world") index = self._parse_index(index) bc = (slice(None),) + (np.newaxis,) * (index.ndim - 1) return (index // self.parent_splits[bc]) + self.parent_padding[bc]
[docs] def index2coord(self, index): slc = (slice(None),) + (np.newaxis,) * (index.ndim - 1) shp = self.shape + 2 * self.shifts index = index + self.shifts[slc] return (index + 0.5) / shp[slc]
[docs] def coord2index(self, coord, dtype=np.int64, **kwargs): slc = (slice(None),) + (np.newaxis,) * (coord.ndim - 1) shp = self.shape + 2 * self.shifts index = coord * shp[slc] - self.shifts[slc] - 0.5 if np.issubdtype(dtype, np.integer): index = jnp.rint(index).astype(dtype) return index else: raise ValueError(f"non-integer index dtype: {dtype}")
[docs] def index2volume(self, index): sz = np.prod(self.shape + 2 * self.shifts) return np.array(1.0 / sz)[(np.newaxis,) * index.ndim]
[docs] class OpenGrid(Grid): """Dense grid with open boundary conditions. At each level the grid has all required indices for a full refinement/convolution even for those that are not split. However, indices used for padding don't have children. The coordinates for the refinement/convolution span the full space including any padding on all previous layers. """ padding: tuple[npt.NDArray[np.int_]] = field(metadata=dict(static=True))
[docs] def __init__(self, *, shape0, splits, padding, atLevel=OpenGridAtLevel): super().__init__(shape0=shape0, splits=splits, atLevel=atLevel) padding = (padding,) if isinstance(padding, int) else padding self.padding = tuple(np.broadcast_to(p, self.shape0.shape) for p in padding) if len(self.padding) != len(self.splits): msg = f"padding ({padding!r}) and splits ({splits!r}) not of equal length" raise ValueError(msg) # Validate that the shape is always valid (greater than zero) shp = self.shape0 for si, pd in zip(self.splits, self.padding): shp = si * (shp - 2 * pd) assert np.all(shp > 0)
[docs] def amend(self, splits, padding): splits = (splits,) if isinstance(splits, int) else splits splits = tuple(np.broadcast_to(s, self.shape0.shape) for s in splits) padding = (padding,) if isinstance(padding, int) else padding padding = tuple(np.broadcast_to(p, self.shape0.shape) for p in padding) return self.__class__( shape0=self.shape0, splits=self.splits + splits, padding=self.padding + padding, atLevel=self.atLevel, )
[docs] def at(self, level: int): level = self._parse_level(level) shp = self.shape0 shifts = np.zeros_like(shp) for si, pd in zip(self.splits[:level], self.padding[:level]): shp = si * (shp - 2 * pd) shifts = si * (shifts + pd) return self.atLevel( shape=shp, splits=self.splits[level] if level < self.depth else None, parent_splits=self.splits[level - 1] if level >= 1 else None, padding=self.padding[level] if level < self.depth else None, parent_padding=self.padding[level - 1] if level >= 1 else None, shifts=shifts, level=level, all_splits=self.splits[: level + 1], )
[docs] class MGridAtLevel(GridAtLevel): """Multi-dimensional meshgrid product of multiple grids.""" grids: tuple[GridAtLevel] = field(metadata=dict(static=False))
[docs] def __init__(self, *grids): self.grids = tuple(grids)
@property def shape(self): return np.concatenate(tuple(g.shape for g in self.grids)) @property def splits(self): if self.grids[0].splits is None: if any(gg.splits is not None for gg in self.grids[1:]): raise ValueError(f"inconsistent `None` splits in grids {self.grids}") return None return np.concatenate(tuple(g.splits for g in self.grids)) @property def parent_splits(self): if self.grids[0].parent_splits is None: if any(gg.parent_splits is not None for gg in self.grids[1:]): msg = f"inconsistent `None` parent_splits in grids {self.grids}" raise ValueError(msg) return None return np.concatenate(tuple(g.parent_splits for g in self.grids)) @property def ngrids(self): return len(self.grids) @property def raw_grids(self): return reduce(operator.add, (g.raw_grids for g in self.grids))
[docs] def refined_indices(self): mgrids = tuple(gg.refined_indices() for gg in self.grids) res = mgrids[0] for mg in mgrids[1:]: slf = (slice(None),) * res.ndim + (jnp.newaxis,) * (mg.ndim - 1) slb = ( (slice(None),) + (jnp.newaxis,) * (res.ndim - 1) + (slice(None),) * (mg.ndim - 1) ) shb = res.shape[1:] + mg.shape[1:] res = jnp.broadcast_to(res[slf], (res.shape[0],) + shb) mg = jnp.broadcast_to(mg[slb], (mg.shape[0],) + shb) res = jnp.concatenate((res, mg), axis=0) return res
def _is_index_refined(self, index): if self.splits is None: return jnp.zeros(index.shape[1:], dtype=bool) if index.ndim > 1 else False ndims_off = tuple(np.cumsum(tuple(g.ndim for g in self.grids))) islice = tuple(slice(l, r) for l, r in zip((0,) + ndims_off[:-1], ndims_off)) isin = tuple(g._is_index_refined(index[i]) for i, g in zip(islice, self.grids)) return reduce(operator.mul, isin, 1)
[docs] def resort(self, batched_ar, /): if any(isinstance(g, FlatGrid) and g.ordering == "serial" for g in self.grids): msg = "serial ordering MGrid resort not implemented" raise NotImplementedError(msg) # TODO generalize using grids resort return super().resort(batched_ar)
[docs] def children(self, index) -> npt.NDArray: ndims_off = tuple(np.cumsum(tuple(g.ndim for g in self.grids))) ndims_sum = ndims_off[-1] islice = tuple(slice(l, r) for l, r in zip((0,) + ndims_off[:-1], ndims_off)) children = tuple(g.children(index[i]) for i, g in zip(islice, self.grids)) # Make initial entry broadcast-able to the full final shape out = children[0][ (slice(None),) * children[0].ndim + (np.newaxis,) * (ndims_sum - self.grids[0].ndim) ] # Successively concatenate all broadcasted children for c, i in zip(children[1:], islice[1:]): c = c[ (slice(None),) * index.ndim + (np.newaxis,) * i.start + (slice(None),) * (i.stop - i.start) + (np.newaxis,) * (ndims_sum - i.stop) ] assert c.shape[0] == (i.stop - i.start) bshp = np.broadcast_shapes(out.shape[1:], c.shape[1:]) c = jnp.broadcast_to(c, c.shape[:1] + bshp) out = jnp.broadcast_to(out, out.shape[:1] + bshp) out = jnp.concatenate((out, c), axis=0) return out
[docs] def neighborhood(self, index, window_size: tuple[int]): ndims_off = tuple(np.cumsum(tuple(g.ndim for g in self.grids))) ndims_sum = ndims_off[-1] islice = tuple(slice(l, r) for l, r in zip((0,) + ndims_off[:-1], ndims_off)) window_size = ( (window_size,) * self.ndim if isinstance(window_size, int) else window_size ) assert len(window_size) == self.ndim neighborhood = [] for i, g in zip(islice, self.grids): n = g.neighborhood(index[i], window_size[i]) neighborhood.append(n) # Make initial entry broadcast-able to the full final shape out = neighborhood[0][ (slice(None),) * neighborhood[0].ndim + (np.newaxis,) * (ndims_sum - self.grids[0].ndim) ] # Successively concatenate all broadcasted neighbors for n, i in zip(neighborhood[1:], islice[1:]): n = n[ (slice(None),) * index.ndim + (np.newaxis,) * i.start + (slice(None),) * (i.stop - i.start) + (np.newaxis,) * (ndims_sum - i.stop) ] assert n.shape[0] == (i.stop - i.start) bshp = np.broadcast_shapes(out.shape[1:], n.shape[1:]) n = jnp.broadcast_to(n, n.shape[:1] + bshp) out = jnp.broadcast_to(out, out.shape[:1] + bshp) out = jnp.concatenate((out, n), axis=0) return out
[docs] def parent(self, index): ndims_off = tuple(np.cumsum(tuple(g.ndim for g in self.grids))) islice = tuple(slice(l, r) for l, r in zip((0,) + ndims_off[:-1], ndims_off)) parent = tuple(g.parent(index[i]) for i, g in zip(islice, self.grids)) return jnp.concatenate(parent, axis=0)
[docs] def index2coord(self, index, **kwargs): ndims_off = tuple(np.cumsum(tuple(g.ndim for g in self.grids))) islice = tuple(slice(l, r) for l, r in zip((0,) + ndims_off[:-1], ndims_off)) coord = tuple( g.index2coord(index[i], **kwargs) for i, g in zip(islice, self.grids) ) return jnp.concatenate(coord, axis=0)
[docs] def coord2index(self, coord, return_valid=False, **kwargs): cdims = tuple( eval_shape(gg.index2coord, ShapeDtypeStruct((gg.ndim,), jnp.int_)).shape[0] for gg in self.grids ) ndims_off = tuple(np.cumsum(cdims)) islice = tuple(slice(l, r) for l, r in zip((0,) + ndims_off[:-1], ndims_off)) index = tuple( g.coord2index(coord[i], return_valid=return_valid, **kwargs) for i, g in zip(islice, self.grids) ) if return_valid: inds = tuple(i[0] if isinstance(i, tuple) else i for i in index) valid = list(i[1] for i in index if isinstance(i, tuple)) if len(valid) > 0: valid = jnp.all(jnp.stack(valid, axis=0), axis=0) else: valid = jnp.ones(inds[0].shape[1:], dtype=bool) return jnp.concatenate(inds, axis=0), valid return jnp.concatenate(index, axis=0)
[docs] def index2volume(self, index, **kwargs): ndims_off = tuple(np.cumsum(tuple(g.ndim for g in self.grids))) islice = tuple(slice(l, r) for l, r in zip((0,) + ndims_off[:-1], ndims_off)) volume = tuple( g.index2volume(index[i], **kwargs) for i, g in zip(islice, self.grids) ) return reduce(operator.mul, volume)
[docs] class MGrid(Grid): """Multi-dimensional meshgrid product of multiple grids.""" grids: tuple[Grid] = field(metadata=dict(static=False))
[docs] def __init__(self, *grids, atLevel=MGridAtLevel): self.grids = tuple(grids) for i, g in enumerate(grids): if not isinstance(g, Grid): raise TypeError( f"Grid {g.__class__.__name__} at index {i} of invalid type" ) if g.depth != grids[0].depth: raise ValueError( f"Grid {g.__class__.__name__} at index {i} not of same depth" ) shape0 = np.concatenate(tuple(g.shape0 for g in self.grids)) splits = tuple( np.concatenate(tuple(g.splits[lvl] for g in self.grids)) for lvl in range(self.grids[0].depth) ) super().__init__(shape0=shape0, splits=splits, atLevel=atLevel)
@property def depth(self): return self.grids[0].depth @property def ngrids(self): return len(self.grids)
[docs] def amend(self, splits): splits = (splits,) if isinstance(splits, int) else splits splits = tuple(np.broadcast_to(s, self.shape0.shape) for s in splits) # Create slices for indexing individal grid regions in split ndims_off = tuple(np.cumsum(tuple(g.ndim for g in self.grids))) islice = tuple(slice(l, r) for l, r in zip((0,) + ndims_off[:-1], ndims_off)) # Separate shared splits into splits for the individual grids spg = tuple(zip(*(tuple(spl[i] for i in islice) for spl in splits))) grids = tuple(g.amend(s) for g, s in zip(self.grids, spg)) return self.__class__(*grids, atLevel=self.atLevel)
[docs] def at(self, level: int): level = self._parse_level(level) return self.atLevel(*tuple(g.at(level) for g in self.grids))
[docs] class FlatGridAtLevel(GridAtLevel): """Same as :class:`GridAtLevel` but with a single global integer index for each voxel.""" grid_at_level: GridAtLevel = field(metadata=dict(static=False)) all_shapes: tuple[npt.NDArray[np.int_]] all_splits: tuple[npt.NDArray[np.int_]] ordering: str
[docs] def __init__(self, grid_at_level, *, all_shapes, all_splits, ordering="nest"): if not isinstance(grid_at_level, GridAtLevel): raise TypeError(f"Grid {grid_at_level.__name__} of invalid type") self.grid_at_level = grid_at_level ordering = str(ordering).lower() if ordering not in ("serial", "nest"): raise ValueError(f"invalid flat index ordering scheme {ordering}") self.ordering = ordering self.all_shapes = tuple(np.atleast_1d(sh) for sh in all_shapes) self.all_splits = tuple( np.broadcast_to(sp, shp.shape) for sp, shp in zip(all_splits, self.all_shapes) ) super().__init__( shape=np.prod( grid_at_level.shape, keepdims=True ), # np.array([reduce(operator.mul, grid_at_level.shape, 1),], splits=( np.prod(grid_at_level.splits, keepdims=True) if grid_at_level.splits is not None else None ), parent_splits=( np.prod(grid_at_level.parent_splits, keepdims=True) if grid_at_level.parent_splits is not None else None ), )
@property def raw_grids(self): return self.grid_at_level.raw_grids def _weights_serial(self, levelshift): if levelshift not in (-1, 0, 1): raise ValueError(f"invalid shift in level {levelshift!r}") shape = self.all_shapes[levelshift - 2] return np.cumprod(np.append(shape[1:], 1)[::-1])[::-1] def _weights_nest(self, levelshift): if levelshift not in (-1, 0, 1): raise ValueError(f"invalid shift in level {levelshift!r}") bases = self.all_splits[: (len(self.all_splits) - 2 + levelshift)] shape = self.all_shapes[levelshift - 2] base_shape = shape // reduce(operator.mul, bases, np.ones_like(shape)) wgts = (base_shape,) + bases return np.stack(wgts, axis=0)
[docs] def index2flatindex(self, index, levelshift=0): if self.ordering == "serial": wgt = self._weights_serial(levelshift) wgt = wgt[(slice(None),) + (np.newaxis,) * (index.ndim - 1)] res = (wgt * index).sum(axis=0).astype(index.dtype) elif self.ordering == "nest": fid = jnp.zeros(index.shape[1:], dtype=index.dtype) wgts = self._weights_nest(levelshift) for n, ww in enumerate(wgts): j = 0 for ax in range(ww.size): j *= ww[ax] j += (index[ax] // wgts[(n + 1) :, ax].prod()) % ww[ax] fid *= ww.prod() fid += j res = fid else: raise RuntimeError return res[jnp.newaxis, ...]
[docs] def flatindex2index(self, index, levelshift=0): dtp = index.dtype if self.ordering == "serial": wgt = self._weights_serial(levelshift) tm = jnp.copy(index[0]) index = np.zeros(wgt.shape + index.shape[1:], dtype=dtp) index = [] for w in wgt: tmfl = tm // w tm -= w * tmfl index.append(tmfl) res = jnp.stack(index, axis=0).astype(dtp) elif self.ordering == "nest": wgts = self._weights_nest(levelshift) fid = jnp.copy(index[0]) index = jnp.zeros((wgts.shape[1],) + index.shape[1:], dtype=dtp) for n, ww in reversed(list(enumerate(wgts))): fct = ww.prod() j = fid % fct for ax in range(ww.size)[::-1]: index = index.at[ax].add(wgts[(n + 1) :, ax].prod() * (j % ww[ax])) j //= ww[ax] fid //= fct res = index.astype(dtp) else: raise RuntimeError return res
[docs] def refined_indices(self): ids = self.grid_at_level.refined_indices() res = self.index2flatindex(ids) if self.ordering == "nest": return jnp.sort(res.flatten()).reshape((1, -1)) else: return res.reshape((1, -1))
def _is_index_refined(self, index): index = self._parse_index(index) index = self.flatindex2index(index) return self.grid_at_level._is_index_refined(index)
[docs] def resort(self, batched_ar, /): if self.ordering == "nest": return super().resort(batched_ar) if self.ordering == "serial": parent_splits = self.all_splits[-3] shape = self.all_shapes[-2] if batched_ar.ndim != 2: raise ValueError( f"batched_ar must have 2 dimensions, got {batched_ar.ndim}" ) if batched_ar.shape[1] != np.prod(parent_splits): raise ValueError shp = tuple(shape // parent_splits) + tuple(parent_splits) batched_ar = batched_ar.reshape(shp) ndim = shape.size idx = np.arange(ndim) axes = reduce(operator.add, ((a, b) for a, b in zip(idx, ndim + idx))) return jnp.transpose(batched_ar, axes).ravel() raise RuntimeError
[docs] def children(self, index) -> npt.NDArray: index = self._parse_index(index) index = self.flatindex2index(index) children = self.grid_at_level.children(index).reshape(index.shape + (-1,)) return self.index2flatindex(children, +1)
[docs] def neighborhood(self, index, window_size: Iterable[int]): index = self._parse_index(index) index = self.flatindex2index(index) window = self.grid_at_level.neighborhood(index, window_size=window_size) return self.index2flatindex(window.reshape(index.shape + (-1,)))
[docs] def parent(self, index): index = self._parse_index(index) index = self.flatindex2index(index) window = self.grid_at_level.parent(index) return self.index2flatindex(window, -1)
[docs] def index2coord(self, index, **kwargs): index = self._parse_index(index) index = self.flatindex2index(index) return self.grid_at_level.index2coord(index, **kwargs)
[docs] def coord2index(self, coord, *, return_valid=False, **kwargs): index = self.grid_at_level.coord2index(coord, **kwargs) if return_valid: valid = reduce( operator.mul, ( (ii >= 0) * (ii < sh) for ii, sh in zip(index, self.grid_at_level.shape) ), ) index = self.grid_at_level._parse_index(index) index = self.index2flatindex(index) if return_valid: return index, valid return index
[docs] def index2volume(self, index, **kwargs): index = self._parse_index(index) index = self.flatindex2index(index) return self.grid_at_level.index2volume(index, **kwargs)
def _check_open(grid): if isinstance(grid, OpenGrid): return True if isinstance(grid, MGrid): for g in grid.grids: if _check_open(g): return True
[docs] class FlatGrid(Grid): """Same as :class:`Grid` but with a single global integer index for each voxel.""" grid: Grid = field(metadata=dict(static=False)) ordering: str
[docs] def __init__(self, grid, *, ordering="serial", atLevel=FlatGridAtLevel): if not isinstance(grid, Grid): raise TypeError(f"Grid {grid.__name__} of invalid type") self.grid = grid ordering = str(ordering).lower() if ordering not in ("serial", "nest"): raise ValueError(f"invalid flat index ordering scheme {ordering}") if ordering == "nest": if _check_open(grid): msg = "Nest ordering is not supported for OpenGrids; Use `SparseGrid` or `serial` ordering instead." raise ValueError(msg) self.ordering = ordering shape0 = np.array([np.prod(grid.shape0)]) splits = tuple(np.array([np.prod(spl)]) for spl in grid.splits) super().__init__(shape0=shape0, splits=splits, atLevel=atLevel)
[docs] def amend(self, splits): grid = self.grid.amend(splits) return self.__class__(grid=grid, ordering=self.ordering)
[docs] def at(self, level: int): level = self._parse_level(level) shapes = [] splits = [] for lvl in range(level + 2): if lvl <= self.depth: atlvl = self.grid.at(lvl) shapes.append(atlvl.shape) splits.append(atlvl.splits) else: shapes.append(None) splits.append(None) return self.atLevel( self.grid.at(level), all_shapes=shapes, all_splits=splits, ordering=self.ordering, )
[docs] class SparseGridAtLevel(FlatGridAtLevel): mapping: jnp.ndarray = field(metadata=dict(static=False)) parent_mapping: Optional[jnp.ndarray] = field(metadata=dict(static=False), default=None) children_mapping: Optional[jnp.ndarray] = field(metadata=dict(static=False), default=None)
[docs] def __init__( self, grid_at_level, all_shapes, all_splits, mapping, parent_mapping=None, children_mapping=None, _debug=False, ): if not isinstance(grid_at_level, GridAtLevel): raise TypeError(f"Grid {grid_at_level.__name__} of invalid type") self.mapping = mapping self.parent_mapping = parent_mapping self.children_mapping = children_mapping self._debug = _debug super().__init__( grid_at_level=grid_at_level, all_shapes=all_shapes, all_splits=all_splits, ordering="nest", ) # Overrides shape to utilize base functions self.shape = np.array([self.mapping.size])
def _mapping(self, levelshift): if levelshift == -1: mapping = self.parent_mapping elif levelshift == 0: mapping = self.mapping elif levelshift == 1: mapping = self.children_mapping else: raise ValueError(f"invalid shift in level: {levelshift}") return mapping
[docs] def arrayindex2flatindex(self, index, levelshift=0): index = self._parse_index(index) return self._mapping(levelshift)[index]
[docs] def flatindex2arrayindex(self, index, levelshift=0, return_valid=False): mapping = self._mapping(levelshift) arrayid = jnp.searchsorted(mapping, index) valid = jnp.searchsorted(mapping, index, side="right") == arrayid + 1 valid = valid[0] if self._debug: if not jnp.all(valid): msg = f"flat index {arrayid[:, ~valid]} not on child grid of {self.__class__.__name__}" raise ValueError(msg) if return_valid: return arrayid, valid return arrayid
[docs] def refined_indices(self): index = jnp.arange(self.mapping.size, dtype=self.mapping.dtype)[jnp.newaxis, :] return index[:, self._is_index_refined(index)]
def _is_index_refined(self, index): index = self.arrayindex2flatindex(index) children = self.to_flat_grid().children(index) isin = jnp.isin(children[0], self.children_mapping) return jnp.all(isin, axis=-1)
[docs] def resort(self, batched_ar, /): return super().resort(batched_ar)
[docs] def children(self, index) -> jnp.ndarray: index = self.arrayindex2flatindex(index) index = self.flatindex2index(index) children = self.grid_at_level.children(index).reshape(index.shape + (-1,)) children = self.index2flatindex(children, +1) return self.flatindex2arrayindex(children, +1)
[docs] def neighborhood(self, index, window_size: Iterable[int]): index = self.arrayindex2flatindex(index) index = self.flatindex2index(index) window = self.grid_at_level.neighborhood(index, window_size=window_size) window = self.index2flatindex(window.reshape(index.shape + (-1,))) return self.flatindex2arrayindex(window)
[docs] def parent(self, index): index = self.arrayindex2flatindex(index) index = self.flatindex2index(index) parent = self.grid_at_level.parent(index) parent = self.index2flatindex(parent, -1) return self.flatindex2arrayindex(parent, -1)
[docs] def index2coord(self, index, **kwargs): index = self.arrayindex2flatindex(index) index = self.flatindex2index(index) return self.grid_at_level.index2coord(index, **kwargs)
[docs] def coord2index(self, coord, return_valid=False, **kwargs): index = self.grid_at_level.coord2index(coord, **kwargs) index = self.index2flatindex(index) return self.flatindex2arrayindex(index, return_valid=return_valid)
[docs] def index2volume(self, index, **kwargs): index = self.arrayindex2flatindex(index) index = self.flatindex2index(index) return self.grid_at_level.index2volume(index, **kwargs)
[docs] def is_leaf(self, index): if self.children_mapping is None: return jnp.ones_like(index, dtype=bool) else: children = self.children(index) children = self.arrayindex2flatindex(children)[0] ischild = jnp.isin(children, self.children_mapping) if self._debug: n_children = ischild.shape[-1] check = jnp.sum(ischild, axis=-1) assert jnp.all(check[check > 0] == n_children) return ischild
[docs] def to_flat_grid(self): return FlatGridAtLevel( self.grid_at_level, all_shapes=self.all_shapes, all_splits=self.all_splits, ordering="nest", )
[docs] class SparseGrid(FlatGrid): """Same as :class:`FlatGrid` but keeping track of the indices that are actually being modeled. This class is especially convenient for open boundary conditions but works for arbitrarily sparsely resolved grids.""" mapping: tuple[jnp.ndarray] = field(metadata=dict(static=False))
[docs] def __init__( self, grid, mapping, *, atLevel=SparseGridAtLevel, _check_mapping=True, _debug=False, ): if isinstance(grid, FlatGrid): if grid.ordering == "serial": raise ValueError("Serial ordering is not supported for SparseGrids") grid = grid.grid if not isinstance(grid, Grid): raise TypeError(f"Grid {grid.__class__.__name__} of invalid type") self.grid = grid self._check_mapping = _check_mapping self._debug = _debug if isinstance(mapping, list): mapping = tuple(mapping) mapping = (mapping,) if not isinstance(mapping, tuple) else mapping mapping = tuple(jnp.atleast_1d(jnp.array(m)) for m in mapping) if _check_mapping: if len(mapping) != grid.depth + 1: md, gd = len(mapping), grid.depth nm = grid.__class__.__name__ msg = f"Map depth {md} does not match grid {nm} depth {gd}" raise ValueError(msg) for mm in mapping: if mm.ndim != 1: raise IndexError("Mapping must be one dimensional") if np.any(mm[1:] <= mm[:-1]): print(mm) raise IndexError("Mapping must be unique and sorted") self.mapping = mapping super().__init__(grid=grid, ordering="nest", atLevel=atLevel)
[docs] def amend(self, splits, mapping, **kwargs): grid = self.grid.amend(splits, **kwargs) mapping = (mapping,) if not isinstance(mapping, tuple) else mapping return self.__class__( grid, self.mapping + mapping, _check_mapping=self._check_mapping, _debug=self._debug, )
[docs] def get_flat_grid(self): return FlatGrid(self.grid, ordering="nest")
[docs] def at(self, level: int): level = self._parse_level(level) shapes = [] splits = [] for lvl in range(level + 2): if lvl <= self.depth: atlvl = self.grid.at(lvl) shapes.append(atlvl.shape) splits.append(atlvl.splits) else: shapes.append(None) splits.append(None) return self.atLevel( self.grid.at(level), all_shapes=shapes, all_splits=splits, mapping=self.mapping[level], parent_mapping=None if level == 0 else self.mapping[level - 1], children_mapping=None if level == self.depth else self.mapping[level + 1], _debug=self._debug, )