Skip to content

Experimental: NumPy Interoperability#119

Draft
woodtp wants to merge 5 commits into
PyORBIT-Collaboration:mainfrom
woodtp:feature/spacecharge_grid_numpy_interop
Draft

Experimental: NumPy Interoperability#119
woodtp wants to merge 5 commits into
PyORBIT-Collaboration:mainfrom
woodtp:feature/spacecharge_grid_numpy_interop

Conversation

@woodtp
Copy link
Copy Markdown
Contributor

@woodtp woodtp commented Jun 5, 2026

This PR introduces C-extensions that handle NumPy interop with Bunch and Grid3D.

New for Bunch:

import numpy as np
from orbit.core.bunch import Bunch

# construct a new Bunch instance from an existing numpy array
coords = np.random.normal(size=(1000, 6))

bunch = Bunch.from_numpy(coords)

# Get the coordinates stored within a bunch
coords = bunch.to_numpy()

# Update coordinates of an existing Bunch instance with the values from an array
bunch.update_from_numpy(coords)

Similarly for Grid3D:

import numpy as np
from orbit.core.spacecharge import Grid3D

nx = ny = nz = 100

np_grid = np.random.normal(size=(nx, ny, nz))


# Initialize grid
g = Grid3D(nx, ny, nz)

# Populate grid with external data
g.from_numpy(np_grid)

# Maybe there should be something like:
# g = Grid3D.from_numpy(np_grid)

# Extract grid data to numpy
np_grid = g.to_numpy()

To test the build:

meson setup build -DPyORBIT_EXPERIMENTAL_WITH_NUMPY=true                                                                                                                                          
meson compile -C ./build
pip install . --config-settings=builddir=./build

Resolves #36

@woodtp woodtp self-assigned this Jun 5, 2026
@woodtp woodtp added the enhancement New feature or request label Jun 5, 2026
@woodtp woodtp force-pushed the feature/spacecharge_grid_numpy_interop branch from 9c2701e to f60044a Compare June 5, 2026 16:30
woodtp added 5 commits June 5, 2026 12:43
Add optional compile-time flag that will compile wrap_grid3D against
numpy, enabling to/from_numpy methods for Grid3D instances. When flag is
disabled, to/from_numpy don't do anything.
@woodtp woodtp force-pushed the feature/spacecharge_grid_numpy_interop branch from f60044a to 6d29eab Compare June 5, 2026 16:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

How to build a Bunch from numpy effectively?

1 participant