PreallocationTools.jl icon indicating copy to clipboard operation
PreallocationTools.jl copied to clipboard

Resizing multi-dimensional `DiffCache`s

Open ranocha opened this issue 5 months ago • 4 comments

We use some multi-dimensional caches in Trixi.jl that we have to resize! for some operations. Since Julia only supports to resize! vectors, we construct the plain storage as vectors and unsafe_wrap them in multi-dimensional arrays, e.g.,

# create multi-dimensional cache
_cache = zeros(10)
cache = unsafe_wrap(Array, pointer(_cache), (2, 5))

# resize it
resize!(_cache, 12)
cache = unsafe_wrap(Array, pointer(_cache), (2, 6))

To use the same pattern with DiffCaches, we have to use knowledge about the interval structure of them at the moment, e.g.,

# create multi-dimensional cache
_cache = DiffCache(zeros(10))
s = (2, 5)
cache = DiffCache(unsafe_wrap(Array, pointer(_cache.du), s),
                  unsafe_wrap(Array, pointer(_cache.dual_du), s),
                  Any[])

# resize it
resize!(_cache, 12)
s = (2, 6)
cache = DiffCache(unsafe_wrap(Array, pointer(_cache.du), s),
                  unsafe_wrap(Array, pointer(_cache.dual_du), s),
                  Any[])
  • Can we assume that this is safe to do?
  • If not, can we add something to the public API of PreallocationTools.jl that allows us to obtain multi-dimensional DiffCaches that can be resize!d like this without allocating a lot of memory every time?

ranocha avatar Aug 29 '25 13:08 ranocha