Skip to content

Commit

Permalink
Add an imageseries adapter for arbitrary functions
Browse files Browse the repository at this point in the history
This adds a highly customizable imageseries adapter that simply
accepts a function and a number of frames. The function takes a
single argument (an integer for the frame index), and returns a
2D numpy array for that frame.

This will be used for streaming in data, where the data is compressed
in memory (not on disk), and the custom function simply decompresses
the frame and returns it.

We will then use this to create a sparse data writer.

Signed-off-by: Patrick Avery <[email protected]>
  • Loading branch information
psavery committed May 18, 2024
1 parent 9c500f8 commit d8d2d19
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 1 deletion.
2 changes: 1 addition & 1 deletion hexrd/imageseries/load/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class ImageSeriesAdapter(ImageSeriesABC, metaclass=_RegisterAdapterClass):
# import all adapter modules

from . import (
array, framecache, hdf5, imagefiles, rawimage, metadata, trivial
array, framecache, function, hdf5, imagefiles, rawimage, metadata, trivial
)

try:
Expand Down
60 changes: 60 additions & 0 deletions hexrd/imageseries/load/function.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
"""Adapter class for a custom function that takes an int as an argument
and returns a 2D numpy array.
"""
from . import ImageSeriesAdapter
from ..imageseriesiter import ImageSeriesIterator


class FunctionImageSeriesAdapter(ImageSeriesAdapter):
"""Collection of Images in numpy array
Parameters
----------
fname: None
should be None
func: a function that returns a numpy array for a index
num_frames: the number of frames provided by the function
metadata: dict (optional)
the metadata dictionary
"""
format = 'function'

def __init__(self, fname, **kwargs):
self._func = kwargs['func']
self._nframes = kwargs['num_frames']

self._meta = kwargs.pop('meta', {})

first_frame = self._first_frame
self._nxny = first_frame.shape
self._dtype = first_frame.dtype

@property
def metadata(self):
"""Image sequence metadata"""
return self._meta

@property
def _first_frame(self):
return self._func(0)

@property
def shape(self):
return self._nxny

@property
def dtype(self):
return self._dtype

def __getitem__(self, key):
if not isinstance(key, int):
msg = f'Only int keys are supported, but "{key}" was provided'
raise Exception(msg)

return self._func(key)

def __iter__(self):
return ImageSeriesIterator(self)

def __len__(self):
return self._nframes

0 comments on commit d8d2d19

Please sign in to comment.