Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/compilation.yml
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,9 @@ jobs:
pip install -U pip
pip install -r requirements.txt
pip install -U setuptools
pip install numpy
pip install --no-build-isolation --editable ".[numpy]" \
--config-settings=setup-args="-DUSE_NUMPY=true" \
--config-settings=setup-args="-DUSE_FFTW_THREADS=true" \
--config-settings=setup-args="-DUSE_OPENMP=true"

Expand Down
1 change: 1 addition & 0 deletions meson_options.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
option('USE_MPI', type: 'string', value: 'auto', description: 'Choose MPI implementation (mpich, openmpi, none, auto)')
option('USE_FFTW_THREADS', type: 'boolean', value: false, description: 'Build with threaded version of FFTW')
option('USE_OPENMP', type: 'boolean', value: false, description: 'Build with OpenMP (multi-threading) support')
option('USE_NUMPY', type: 'boolean', value: false, description: 'Build Bunch.addParticles and Bunch.coordinates with the NumPy C API')

239 changes: 239 additions & 0 deletions py/orbit/core/bunch.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,239 @@
"""Types for orbit.core.bunch, including optional USE_NUMPY methods."""

from typing import Any, overload

import numpy as np
from numpy.typing import ArrayLike, NDArray

class Bunch:
def __init__(self) -> None: ...
# Communicators are extension objects from the currently untyped orbit_mpi module.
def getMPIComm(self) -> Any: ...
def setMPIComm(self, mpi_comm: Any, /) -> None: ...
def getSyncParticle(self) -> SyncParticle: ...
def addParticle(
self, x: float, xp: float, y: float, yp: float, z: float, dE: float, /
) -> int: ...
def addParticles(self, coordinates: ArrayLike, /) -> None:
"""Append local (N, 6) coordinates in (x, xp, y, yp, z, dE) order.

Requires a USE_NUMPY build. Uses existing units; accepts nested sequences
and compatible NumPy arrays. Does not compress or distribute particles.
"""
def coordinates(self) -> NDArray[np.float64]:
"""Return an owned, C-contiguous (getSize(), 6) local-coordinate snapshot.

Requires a USE_NUMPY build. Columns are (x, xp, y, yp, z, dE) in existing
units. No MPI communication, attributes, or reference-particle metadata.
Does not compress or filter dead slots: call compress() after deletions
before exporting to avoid reviving deleted particles via addParticles().
"""
def deleteParticle(self, index: int, /) -> int: ...
def deleteParticleFast(self, index: int, /) -> int: ...
def recoverParticle(self, index: int, /) -> None: ...
def deleteAllParticles(self) -> None: ...
def compress(self) -> None: ...
@overload
def x(self, index: int, /) -> float: ...
@overload
def x(self, index: int, value: float, /) -> float: ...
@overload
def y(self, index: int, /) -> float: ...
@overload
def y(self, index: int, value: float, /) -> float: ...
@overload
def z(self, index: int, /) -> float: ...
@overload
def z(self, index: int, value: float, /) -> float: ...
@overload
def px(self, index: int, /) -> float: ...
@overload
def px(self, index: int, value: float, /) -> float: ...
@overload
def py(self, index: int, /) -> float: ...
@overload
def py(self, index: int, value: float, /) -> float: ...
@overload
def pz(self, index: int, /) -> float: ...
@overload
def pz(self, index: int, value: float, /) -> float: ...
@overload
def xp(self, index: int, /) -> float: ...
@overload
def xp(self, index: int, value: float, /) -> float: ...
@overload
def yp(self, index: int, /) -> float: ...
@overload
def yp(self, index: int, value: float, /) -> float: ...
@overload
def dE(self, index: int, /) -> float: ...
@overload
def dE(self, index: int, value: float, /) -> float: ...
def flag(self, index: int, /) -> int: ...
def ringwrap(self, ring_length: float, /) -> None: ...
@overload
def mass(self) -> float: ...
@overload
def mass(self, value: float, /) -> float: ...
def classicalRadius(self) -> float: ...
def B_Rho(self) -> float: ...
@overload
def charge(self) -> float: ...
@overload
def charge(self, value: float, /) -> float: ...
@overload
def macroSize(self) -> float: ...
@overload
def macroSize(self, value: float, /) -> float: ...
def initBunchAttr(self, file_name: str, /) -> None: ...
@overload
def bunchAttrDouble(self, name: str, /) -> float: ...
@overload
def bunchAttrDouble(self, name: str, value: float, /) -> float: ...
@overload
def bunchAttrInt(self, name: str, /) -> int: ...
@overload
def bunchAttrInt(self, name: str, value: int, /) -> int: ...
def bunchAttrDoubleNames(self) -> tuple[str, ...]: ...
def bunchAttrIntNames(self) -> tuple[str, ...]: ...
def hasBunchAttrDouble(self, name: str, /) -> int: ...
def hasBunchAttrInt(self, name: str, /) -> int: ...
def addPartAttr(self, name: str, params: dict[str, float] = ..., /) -> None: ...
def removePartAttr(self, name: str, /) -> None: ...
def removeAllPartAttr(self) -> None: ...
def getPartAttrNames(self) -> tuple[str, ...]: ...
def getPartAttrDicts(self) -> dict[str, dict[str, float]]: ...
def getPossiblePartAttrNames(self) -> tuple[str, ...]: ...
def clearAllPartAttrAndMemorize(self) -> None: ...
def restoreAllPartAttrFromMemory(self) -> None: ...
def hasPartAttr(self, name: str, /) -> int: ...
def readPartAttrNames(self, file_name: str, /) -> tuple[str, ...]: ...
def readPartAttrDicts(self, file_name: str, /) -> dict[str, dict[str, float]]: ...
def readPartAttr(self, file_name: str, /) -> None: ...
def getPartAttrSize(self, name: str, /) -> int: ...
@overload
def partAttrValue(self, name: str, part_index: int, attr_index: int, /) -> float: ...
@overload
def partAttrValue(
self, name: str, part_index: int, attr_index: int, value: float, /
) -> float: ...
def getSize(self) -> int: ...
def getSizeGlobal(self) -> int: ...
def getSizeGlobalFromMemory(self) -> int: ...
def getTotalCount(self) -> int: ...
def getCapacity(self) -> int: ...
def dumpBunch(self, file_name: str = ..., /) -> None: ...
def readBunch(self, file_name: str, nParts: int = ..., /) -> None: ...
def copyEmptyBunchTo(self, target: Bunch, /) -> None: ...
def copyBunchTo(self, target: Bunch, /) -> None: ...
def addParticlesTo(self, target: Bunch, /) -> None: ...


class SyncParticle:
"""Reference particle owned by a Bunch; obtain via Bunch.getSyncParticle().

Direct construction is reserved for the Bunch wrapper's initialization.
"""

def __init__(self, bunch: Bunch, /) -> None: ...
def mass(self) -> float: ...
@overload
def momentum(self) -> float: ...
@overload
def momentum(self, value: float, /) -> float: ...
def beta(self) -> float: ...
def gamma(self) -> float: ...
@overload
def kinEnergy(self) -> float: ...
@overload
def kinEnergy(self, value: float, /) -> float: ...
@overload
def time(self) -> float: ...
@overload
def time(self, value: float, /) -> None: ...
@overload
def x(self) -> float: ...
@overload
def x(self, value: float, /) -> None: ...
@overload
def y(self) -> float: ...
@overload
def y(self, value: float, /) -> None: ...
@overload
def z(self) -> float: ...
@overload
def z(self, value: float, /) -> None: ...
@overload
def px(self) -> float: ...
@overload
def px(self, value: float, /) -> None: ...
@overload
def py(self) -> float: ...
@overload
def py(self, value: float, /) -> None: ...
@overload
def pz(self) -> float: ...
@overload
def pz(self, value: float, /) -> None: ...
@overload
def pVector(self) -> tuple[float, float, float]: ...
@overload
def pVector(self, value: tuple[float, float, float], /) -> None: ...
@overload
def rVector(self) -> tuple[float, float, float]: ...
@overload
def rVector(self, value: tuple[float, float, float], /) -> None: ...
@overload
def nxVector(self) -> tuple[float, float, float]: ...
@overload
def nxVector(self, value: tuple[float, float, float], /) -> None: ...
def nyVector(self) -> tuple[float, float, float]: ...
def energyToMomentum(self, value: float, /) -> float: ...
def momentumToEnergy(self, value: float, /) -> float: ...


class BunchTwissAnalysis:
def __init__(self) -> None: ...
def analyzeBunch(self, bunch: Bunch, /) -> None: ...
def computeBunchMoments(
self, bunch: Bunch, order: int, dispterm: int, emitnormterm: int, /
) -> None: ...
def getCorrelation(self, ic: int, jc: int, /) -> float: ...
def getBunchMoment(self, i: int, j: int, /) -> float: ...
def getAverage(self, ic: int, /) -> float: ...
def getGlobalCount(self) -> int: ...
def getGlobalMacrosize(self) -> float: ...
def getEmittance(self, ic: int, /) -> float: ...
def getEmittanceNormalized(self, ic: int, /) -> float: ...
def getAlpha(self, ic: int, /) -> float: ...
def getBeta(self, ic: int, /) -> float: ...
def getGamma(self, ic: int, /) -> float: ...
def getTwiss(self, ic: int, /) -> tuple[float, float, float, float]: ...
def getDispersion(self, ic: int, /) -> float: ...
def getDispersionDerivative(self, ic: int, /) -> float: ...
def getEffectiveEmittance(self, ic: int, /) -> float: ...
def getEffectiveAlpha(self, ic: int, /) -> float: ...
def getEffectiveBeta(self, ic: int, /) -> float: ...
def getEffectiveGamma(self, ic: int, /) -> float: ...


class BunchTuneAnalysis:
def __init__(self) -> None: ...
def analyzeBunch(self, bunch: Bunch, /) -> None: ...
def setNormMatrixElement(self, i: int, j: int, value: float, /) -> None: ...
def getNormMatrixElement(self, i: int, j: int, /) -> float: ...
def setNormMatrixFromTwiss(
self, betax: float, alphax: float, etax: float, etapx: float,
betay: float, alphay: float, /
) -> None: ...


class SynchPartRedefinitionZdE:
def __init__(self) -> None: ...
def analyzeBunch(self, bunch: Bunch, /) -> None: ...
def center_dE(self, bunch: Bunch, /) -> None: ...
def center_Z(self, bunch: Bunch, /) -> None: ...
def shift_dE(self, bunch: Bunch, delta_E: float, /) -> None: ...
def shift_Z(self, bunch: Bunch, delta_z: float, /) -> None: ...
def getAvg_Z(self) -> float: ...
def getAvg_dE(self) -> float: ...
2 changes: 2 additions & 0 deletions py/orbit/core/meson.build
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@

py_sources = files([
'__init__.py',
'bunch.pyi',
'py.typed',
])

python.install_sources(
Expand Down
Empty file added py/orbit/core/py.typed
Empty file.
4 changes: 4 additions & 0 deletions src/meson.build
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ endif
dependencies = []

dependencies += python.dependency()
if get_option('USE_NUMPY')
dependencies += dependency('numpy')
add_project_arguments('-DWITH_NUMPY', language: 'cpp')
endif
dep_fftw = dependency('fftw3', version: '>= 3.0.0', required: true)
dependencies += dep_fftw

Expand Down
81 changes: 81 additions & 0 deletions src/orbit/wrap_bunch.cc
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
//
///////////////////////////////////////////////////////////////////////////
#include "wrap_bunch.hh"
#ifdef WITH_NUMPY
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <numpy/arrayobject.h>
#endif
#include "wrap_syncpart.hh"
#include "wrap_bunch_twiss_analysis.hh"
#include "wrap_bunch_tune_analysis.hh"
Expand Down Expand Up @@ -124,6 +128,70 @@ namespace wrap_orbit_bunch{
}


#ifdef WITH_NUMPY
//Returns an owned snapshot without compressing or filtering deleted particles.
static PyObject* Bunch_coordinates(PyObject *self, PyObject*)
{
Bunch* cpp_bunch = static_cast<Bunch*>(
reinterpret_cast<pyORBIT_Object*>(self)->cpp_obj);

const int count = cpp_bunch->getSize();
npy_intp shape[2] = {static_cast<npy_intp>(count), 6};

PyObject* result = PyArray_SimpleNew(2, shape, NPY_DOUBLE);

if(result == NULL) return NULL;

double* data = static_cast<double*>(
PyArray_DATA(reinterpret_cast<PyArrayObject*>(result)));

double** coordinates = cpp_bunch->coordArr();

#pragma omp parallel for schedule(static)
for(int i = 0; i < count; ++i) {
for(int j = 0; j < 6; ++j) {
data[static_cast<npy_intp>(i)*6 + j] = coordinates[i][j];
}
}

return result;
}

//Appends local particle coordinates from an array-like object of shape (N, 6).
static PyObject* Bunch_addParticles(PyObject *self, PyObject *coordinates)
{
PyArrayObject* array = reinterpret_cast<PyArrayObject*>(PyArray_FROM_OTF(
coordinates, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY));

if(array == NULL) return NULL;

if(PyArray_NDIM(array) != 2 || PyArray_DIM(array,1) != 6){
Py_DECREF(array);
PyErr_SetString(PyExc_ValueError,
"addParticles expects coordinates with shape (N, 6)");
return NULL;
}

Bunch* cpp_bunch = static_cast<Bunch*>(
reinterpret_cast<pyORBIT_Object*>(self)->cpp_obj);

const double* data = static_cast<const double*>(PyArray_DATA(array));
const npy_intp count = PyArray_DIM(array,0);

// TODO: Due to Bunch's lack of a bulk-append method, it's not currently
// thread-safe to parallelize this loop, but doing it serially is already pretty fast.
// Investigate the potential for parallelization later.
for(npy_intp i = 0; i < count; ++i) {
const double* row = data + 6*i;
cpp_bunch->addParticle(row[0],row[1],row[2],row[3],row[4],row[5]);
}

Py_DECREF(array);
Py_RETURN_NONE;
}

#endif

//removes a particle to the Bunch object
//returns the number of particles in the bunch
//this is implementation of the deleteParticle(int index) method
Expand Down Expand Up @@ -1192,6 +1260,16 @@ namespace wrap_orbit_bunch{
{ "setMPIComm", Bunch_setMPIComm ,METH_VARARGS,"Sets a new MPI Comm for this bunch"},
{ "getSyncParticle", Bunch_getSyncParticle ,METH_VARARGS,"Returns syncParticle class instance"},
{ "addParticle", Bunch_addParticle ,METH_VARARGS,"Adds a macro-particle to the bunch"},
#ifdef WITH_NUMPY
{ "addParticles", Bunch_addParticles ,METH_O,
"Append local coordinates of shape (N, 6), ordered (x, xp, y, yp, z, dE). Returns None."},
{ "coordinates", Bunch_coordinates ,METH_NOARGS,
"Return an independent C-contiguous float64 array of local coordinates.\n"
"Shape (getSize(), 6); columns (x, xp, y, yp, z, dE), in existing units.\n"
"No MPI communication, particle attributes, or metadata are included.\n"
"Does not compress or filter deleted particles. Call compress() first if\n"
"particles have been deleted; otherwise addParticles() can revive dead slots."},
#endif
{ "deleteParticle", Bunch_deleteParticle ,METH_VARARGS,"Removes macro-particle from the bunch and call compress inside"},
{ "deleteParticleFast", Bunch_deleteParticleFast ,METH_VARARGS,"Removes macro-particle from the bunch very fast"},
{ "recoverParticle", Bunch_recoverParticle ,METH_VARARGS,"Recovers a particle marked for removal"},
Expand Down Expand Up @@ -1315,6 +1393,9 @@ extern "C" {

/* The name of the function was changed to avoid collision with PyImport magic naming */
PyMODINIT_FUNC initbunch(void) {
#ifdef WITH_NUMPY
import_array();
#endif
//check that the Bunch wrapper is ready
if(PyType_Ready(&pyORBIT_Bunch_Type) < 0) return NULL;
Py_INCREF(&pyORBIT_Bunch_Type);
Expand Down
2 changes: 1 addition & 1 deletion src/orbit/wrap_bunch.hh
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
// INCLUDE FILES
//
///////////////////////////////////////////////////////////////////////////
#include "Python.h"
#include <Python.h>

#ifdef __cplusplus
extern "C" {
Expand Down
Loading
Loading