flumpy
: Zero-data-copy bridge between flex and numpy
#377
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This adds the module
dxtbx.flumpy
and primarily the functionsflumpy.to_numpy
andflumpy.from_numpy
. These will convert:And exposes flex arrays as a generic PEP3118 buffer protocol object,
Scuffer
. This exposes the flex array in a way that anything that understands this protocol can access the structured memory. This means numpy, but also things like Cython will accept buffers directly. Currently this is only one-way, it doesn't read generic buffer objects into flex but should be simple enough.Referencing the internal memory means that no memory needs to be copied, and changes to one object will be reflected in the other. The numpy array holds a reference to the flex object, ensuring memory lifetime, and if cctbx/cctbx_project#618 is merged, the flex objects will hold an internal reference to the numpy object.
Alongside the standard data types,
flex.vec2*
andflex.vec3*
will be converted toNx...x2
andNx...x3
numpy arrays, andflex.mat3*
will be converted toNx....x3x3
numpy objects.vec2*
,vec3*
andmat3*
can also be converted from numpy to flex arrays, but currently require the use offlumpy.vec_from_numpy
(and anNx[2,3]
sized numpy array), orflumpy.mat3_from_numpy
(and either aNx9
orNx3x3
numpy array).The data types that aren't wrapped are
flex.std_string
andflex.sym_mat3_double
, which don't linearly map to memory.Usage example: