Debian Codegraph @

brian2/memory/cythondynamicarray.pyx

raw
1 # cython: language_level=3
2 # distutils: language = c++
3 # distutils: include_dirs = brian2/devices/cpp_standalone/brianlib
4 # distutils: extra_compile_args = -std=c++11
5
6
7 import numpy as np
8 cimport numpy as cnp
9 cimport cython
10 from libc.string cimport memset
11 from libc.stdint cimport int64_t, int32_t
12 from cython cimport view
13 from cpython.pycapsule cimport PyCapsule_New
14 from cpython.ref cimport PyTypeObject
15
16 cnp.import_array()
17
18 cdef extern from "numpy/ndarrayobject.h":
19 object PyArray_NewFromDescr(PyTypeObject* subtype,
20 cnp.PyArray_Descr* descr,
21 int nd,
22 cnp.npy_intp* dims,
23 cnp.npy_intp* strides,
24 void* data,
25 int flags,
26 object obj)
27 cnp.PyArray_Descr* PyArray_DescrFromType(int)
28
29 cdef extern from "numpy/ndarraytypes.h":
30 void PyArray_CLEARFLAGS(cnp.PyArrayObject *arr, int flags)
31 enum:
32 NPY_ARRAY_C_CONTIGUOUS
33 NPY_ARRAY_F_CONTIGUOUS
34 NPY_ARRAY_OWNDATA
35 NPY_ARRAY_WRITEABLE
36 NPY_ARRAY_ALIGNED
37 NPY_ARRAY_WRITEBACKIFCOPY
38 NPY_ARRAY_UPDATEIFCOPY
39
40 cdef extern from "dynamic_array.h":
41 cdef cppclass DynamicArray1DCpp "DynamicArray1D"[T]:
42 DynamicArray1DCpp(size_t,double) except +
43 void resize(size_t) except +
44 void shrink_to_fit()
45 void shrink(size_t) except +
46 T& operator[](size_t)
47 T* get_data_ptr()
48 size_t size()
49 size_t capacity()
50
51
52 cdef cppclass DynamicArray2DCpp "DynamicArray2D"[T]:
53 size_t n # rows
54 size_t m # cols
55 DynamicArray2DCpp(size_t, size_t, double) except +
56 DynamicArray2DCpp(int, int) except + # Legacy constructor
57 void resize(size_t, size_t) except +
58 void resize(int, int) except + # Legacy method
59 void resize() except +
60 void resize_along_first(size_t) except +
61 void shrink_to_fit()
62 void shrink(size_t, size_t) except +
63 void shrink(size_t) except +
64 T& operator()(size_t, size_t)
65 T& operator()(int, int)
66 T* get_data_ptr()
67 size_t rows()
68 size_t cols()
69 size_t stride()
70
71
72 # We have to define a mapping for numpy dtypes to our class
73 cdef dict NUMPY_TYPE_MAP = {
74 np.float64: cnp.NPY_DOUBLE,
75 np.float32: cnp.NPY_FLOAT,
76 np.int32: cnp.NPY_INT32,
77 np.int64: cnp.NPY_INT64,
78 np.bool_: cnp.NPY_BOOL
79 }
80
81
82 cdef class DynamicArray1DClass:
83 cdef void* thisptr
84 cdef int numpy_type
85 cdef object dtype
86 cdef double factor
87
88 def __cinit__(self,size_t intial_size, dtype = np.float64, double factor=2.0):
89 self.dtype = np.dtype(dtype)
90 self.factor = factor
91 self.numpy_type = NUMPY_TYPE_MAP[self.dtype.type]
92
93 if self.dtype == np.float64:
94 self.thisptr = new DynamicArray1DCpp[double](intial_size,factor)
95 elif self.dtype == np.float32:
96 self.thisptr = new DynamicArray1DCpp[float](intial_size,factor)
97 elif self.dtype == np.int32:
98 self.thisptr = new DynamicArray1DCpp[int32_t](intial_size,factor)
99 elif self.dtype == np.int64:
100 self.thisptr = new DynamicArray1DCpp[int64_t](intial_size,factor)
101 elif self.dtype == np.bool_:
102 # When asked for a bool array, we create a char array in C++ as for bool, C++ tries to optimize and save memory by packing all the boolean values tightly — 1 bit per value, instead of 1 byte.
103 self.thisptr = new DynamicArray1DCpp[char](intial_size,factor)
104 else:
105 raise TypeError("Unsupported dtype: {}".format(self.dtype))
106
107 def __dealloc__(self):
108 cdef DynamicArray1DCpp[double]* ptr_double
109 cdef DynamicArray1DCpp[float]* ptr_float
110 cdef DynamicArray1DCpp[int32_t]* ptr_int
111 cdef DynamicArray1DCpp[int64_t]* ptr_long
112 cdef DynamicArray1DCpp[char]* ptr_bool
113 if self.thisptr != NULL:
114 if self.numpy_type == cnp.NPY_DOUBLE:
115 ptr_double = <DynamicArray1DCpp[double]*>self.thisptr
116 del ptr_double
117 elif self.numpy_type == cnp.NPY_FLOAT:
118 ptr_float = <DynamicArray1DCpp[float]*>self.thisptr
119 del ptr_float
120 elif self.numpy_type == cnp.NPY_INT32:
121 ptr_int = <DynamicArray1DCpp[int32_t]*>self.thisptr
122 del ptr_int
123 elif self.numpy_type == cnp.NPY_INT64:
124 ptr_long = <DynamicArray1DCpp[int64_t]*>self.thisptr
125 del ptr_long
126 elif self.numpy_type == cnp.NPY_BOOL:
127 ptr_bool = <DynamicArray1DCpp[char]*>self.thisptr
128 del ptr_bool
129
130
131 cdef void* get_data_ptr(self) :
132 """C-level access to data pointer"""
133 if self.dtype == np.float64:
134 return <void*>(<DynamicArray1DCpp[double]*>self.thisptr).get_data_ptr()
135 elif self.dtype == np.float32:
136 return <void*>(<DynamicArray1DCpp[float]*>self.thisptr).get_data_ptr()
137 elif self.dtype == np.int32:
138 return <void*>(<DynamicArray1DCpp[int32_t]*>self.thisptr).get_data_ptr()
139 elif self.dtype == np.int64:
140 return <void*>(<DynamicArray1DCpp[int64_t]*>self.thisptr).get_data_ptr()
141 elif self.dtype == np.bool_:
142 return <void*>(<DynamicArray1DCpp[char]*>self.thisptr).get_data_ptr()
143 return NULL
144
145 def get_capsule(self):
146 """
147 Returns a PyCapsule object wrapping the underlying C++ Dynamic1D Array class pointer.
148
149 PyCapsules are used to safely pass raw C/C++ pointers between Python modules
150 or C extensions without exposing the actual implementation details to Python.
151 """
152 return PyCapsule_New(<void*>self.thisptr, "DynamicArray1D", NULL)
153
154 cdef size_t get_size(self):
155 """C-level access to size"""
156 if self.dtype == np.float64:
157 return (<DynamicArray1DCpp[double]*>self.thisptr).size()
158 elif self.dtype == np.float32:
159 return (<DynamicArray1DCpp[float]*>self.thisptr).size()
160 elif self.dtype == np.int32:
161 return (<DynamicArray1DCpp[int32_t]*>self.thisptr).size()
162 elif self.dtype == np.int64:
163 return (<DynamicArray1DCpp[int64_t]*>self.thisptr).size()
164 elif self.dtype == np.bool_:
165 return (<DynamicArray1DCpp[char]*>self.thisptr).size()
166 return 0
167
168 def resize(self, size_t new_size):
169 """Resize array to new size"""
170 if self.dtype == np.float64:
171 (<DynamicArray1DCpp[double]*>self.thisptr).resize(new_size)
172 elif self.dtype == np.float32:
173 (<DynamicArray1DCpp[float]*>self.thisptr).resize(new_size)
174 elif self.dtype == np.int32:
175 (<DynamicArray1DCpp[int32_t]*>self.thisptr).resize(new_size)
176 elif self.dtype == np.int64:
177 (<DynamicArray1DCpp[int64_t]*>self.thisptr).resize(new_size)
178 elif self.dtype == np.bool_:
179 (<DynamicArray1DCpp[char]*>self.thisptr).resize(new_size)
180
181 def shrink(self, size_t new_size):
182 """Shrink array to exact new size, freeing unused memory"""
183 if self.dtype == np.float64:
184 (<DynamicArray1DCpp[double]*>self.thisptr).shrink(new_size)
185 elif self.dtype == np.float32:
186 (<DynamicArray1DCpp[float]*>self.thisptr).shrink(new_size)
187 elif self.dtype == np.int32:
188 (<DynamicArray1DCpp[int32_t]*>self.thisptr).shrink(new_size)
189 elif self.dtype == np.int64:
190 (<DynamicArray1DCpp[int64_t]*>self.thisptr).shrink(new_size)
191 elif self.dtype == np.bool_:
192 (<DynamicArray1DCpp[char]*>self.thisptr).shrink(new_size)
193
194 @property
195 def data(self):
196 """Return numpy array view of underlying data"""
197 cdef cnp.npy_intp shape[1]
198 cdef size_t size = self.get_size()
199 cdef void* data_ptr = self.get_data_ptr()
200
201 shape[0] = size
202 if size == 0:
203 return np.array([], dtype=self.dtype)
204 # Note : This creates a zero-copy NumPy view over the memory allocated by the C++ backend —
205 # changes to the NumPy array will reflect in the C++ array and vice versa.
206 return cnp.PyArray_SimpleNewFromData(1, shape, self.numpy_type, data_ptr)
207
208 @property
209 def shape(self):
210 return (self.get_size(),)
211
212 def __getitem__(self, item):
213 return self.data[item]
214
215 def __setitem__(self, item, val):
216 cdef cnp.ndarray arr = self.data
217 arr[item] = val
218
219 def __len__(self):
220 return self.get_size()
221
222
223 cdef class DynamicArray2DClass:
224 cdef void* thisptr
225 cdef int numpy_type
226 cdef object dtype
227 cdef double factor
228
229 def __cinit__(self, tuple shape, dtype=np.float64, double factor=2.0):
230 cdef size_t rows = shape[0] if len(shape) > 0 else 0
231 cdef size_t cols = shape[1] if len(shape) > 1 else 0
232
233 self.dtype = np.dtype(dtype)
234 self.factor = factor
235 self.numpy_type = NUMPY_TYPE_MAP[self.dtype.type]
236
237 if self.dtype == np.float64:
238 self.thisptr = new DynamicArray2DCpp[double](rows, cols, factor)
239 elif self.dtype == np.float32:
240 self.thisptr = new DynamicArray2DCpp[float](rows, cols, factor)
241 elif self.dtype == np.int32:
242 self.thisptr = new DynamicArray2DCpp[int32_t](rows, cols, factor)
243 elif self.dtype == np.int64:
244 self.thisptr = new DynamicArray2DCpp[int64_t](rows, cols, factor)
245 elif self.dtype == np.bool_:
246 # When asked for a bool array, we create a char array in C++ as for bool, C++ tries to optimize and save memory by packing all the boolean values tightly — 1 bit per value, instead of 1 byte.
247 self.thisptr = new DynamicArray2DCpp[char](rows, cols, factor)
248 else:
249 raise TypeError(f"Unsupported dtype: {dtype}")
250
251 def __dealloc__(self):
252 cdef DynamicArray2DCpp[double]* ptr_double
253 cdef DynamicArray2DCpp[float]* ptr_float
254 cdef DynamicArray2DCpp[int32_t]* ptr_int
255 cdef DynamicArray2DCpp[int64_t]* ptr_long
256 cdef DynamicArray2DCpp[char]* ptr_bool
257 if self.thisptr != NULL:
258 if self.numpy_type == cnp.NPY_DOUBLE:
259 ptr_double = <DynamicArray2DCpp[double]*>self.thisptr
260 del ptr_double
261 elif self.numpy_type == cnp.NPY_FLOAT:
262 ptr_float = <DynamicArray2DCpp[float]*>self.thisptr
263 del ptr_float
264 elif self.numpy_type == cnp.NPY_INT32:
265 ptr_int = <DynamicArray2DCpp[int32_t]*>self.thisptr
266 del ptr_int
267 elif self.numpy_type == cnp.NPY_INT64:
268 ptr_long = <DynamicArray2DCpp[int64_t]*>self.thisptr
269 del ptr_long
270 elif self.numpy_type == cnp.NPY_BOOL:
271 ptr_bool = <DynamicArray2DCpp[char]*>self.thisptr
272 del ptr_bool
273
274 def get_capsule(self):
275 """
276 Returns a PyCapsule object wrapping the underlying C++ Dynamic1D Array class pointer.
277
278 PyCapsules are used to safely pass raw C/C++ pointers between Python modules
279 or C extensions without exposing the actual implementation details to Python.
280 """
281 return PyCapsule_New(<void*>self.thisptr, "DynamicArray2D", NULL)
282
283 cdef void* get_data_ptr(self):
284 """C-level access to data pointer"""
285 if self.dtype == np.float64:
286 return <void*>(<DynamicArray2DCpp[double]*>self.thisptr).get_data_ptr()
287 elif self.dtype == np.float32:
288 return <void*>(<DynamicArray2DCpp[float]*>self.thisptr).get_data_ptr()
289 elif self.dtype == np.int32:
290 return <void*>(<DynamicArray2DCpp[int32_t]*>self.thisptr).get_data_ptr()
291 elif self.dtype == np.int64:
292 return <void*>(<DynamicArray2DCpp[int64_t]*>self.thisptr).get_data_ptr()
293 elif self.dtype == np.bool_:
294 return <void*>(<DynamicArray2DCpp[char]*>self.thisptr).get_data_ptr()
295 return NULL
296
297 cdef size_t get_rows(self):
298 """C-level access to rows"""
299 if self.dtype == np.float64:
300 return (<DynamicArray2DCpp[double]*>self.thisptr).rows()
301 elif self.dtype == np.float32:
302 return (<DynamicArray2DCpp[float]*>self.thisptr).rows()
303 elif self.dtype == np.int32:
304 return (<DynamicArray2DCpp[int32_t]*>self.thisptr).rows()
305 elif self.dtype == np.int64:
306 return (<DynamicArray2DCpp[int64_t]*>self.thisptr).rows()
307 elif self.dtype == np.bool_:
308 return (<DynamicArray2DCpp[char]*>self.thisptr).rows()
309 return 0
310
311 cdef size_t get_cols(self):
312 """C-level access to cols"""
313 if self.dtype == np.float64:
314 return (<DynamicArray2DCpp[double]*>self.thisptr).cols()
315 elif self.dtype == np.float32:
316 return (<DynamicArray2DCpp[float]*>self.thisptr).cols()
317 elif self.dtype == np.int32:
318 return (<DynamicArray2DCpp[int32_t]*>self.thisptr).cols()
319 elif self.dtype == np.int64:
320 return (<DynamicArray2DCpp[int64_t]*>self.thisptr).cols()
321 elif self.dtype == np.bool_:
322 return (<DynamicArray2DCpp[char]*>self.thisptr).cols()
323 return 0
324
325
326 cdef size_t get_stride(self):
327 """C-level access to stride"""
328 if self.dtype == np.float64:
329 return (<DynamicArray2DCpp[double]*>self.thisptr).stride()
330 elif self.dtype == np.float32:
331 return (<DynamicArray2DCpp[float]*>self.thisptr).stride()
332 elif self.dtype == np.int32:
333 return (<DynamicArray2DCpp[int32_t]*>self.thisptr).stride()
334 elif self.dtype == np.int64:
335 return (<DynamicArray2DCpp[int64_t]*>self.thisptr).stride()
336 elif self.dtype == np.bool_:
337 return (<DynamicArray2DCpp[char]*>self.thisptr).stride()
338 return 0
339
340 def resize(self, new_shape):
341 if isinstance(new_shape, (tuple, list)) and new_shape[1] != self.get_cols():
342 raise ValueError("Resizing is only supported along the first dimension")
343 self.resize_along_first(new_shape)
344
345 def resize_along_first(self, new_shape):
346 """Resize along first dimension (rows), keeping columns unchanged"""
347 if isinstance(new_shape, int):
348 new_rows = new_shape
349 elif isinstance(new_shape, (tuple, list)):
350 new_rows = new_shape[0]
351 else:
352 raise ValueError("new_shape must be int, tuple, or list")
353
354 cdef size_t rows = new_rows
355 if self.dtype == np.float64:
356 (<DynamicArray2DCpp[double]*>self.thisptr).resize_along_first(rows)
357 elif self.dtype == np.float32:
358 (<DynamicArray2DCpp[float]*>self.thisptr).resize_along_first(rows)
359 elif self.dtype == np.int32:
360 (<DynamicArray2DCpp[int32_t]*>self.thisptr).resize_along_first(rows)
361 elif self.dtype == np.int64:
362 (<DynamicArray2DCpp[int64_t]*>self.thisptr).resize_along_first(rows)
363 elif self.dtype == np.bool_:
364 (<DynamicArray2DCpp[char]*>self.thisptr).resize_along_first(rows)
365
366 def shrink(self, new_shape):
367 """Shrink array to exact new shape, freeing unused memory"""
368 cdef size_t new_rows
369 cdef size_t new_cols
370 if isinstance(new_shape, int):
371 # Shrink just rows, keep cols
372 new_rows = new_shape
373 if self.dtype == np.float64:
374 (<DynamicArray2DCpp[double]*>self.thisptr).shrink(new_rows)
375 elif self.dtype == np.float32:
376 (<DynamicArray2DCpp[float]*>self.thisptr).shrink(new_rows)
377 elif self.dtype == np.int32:
378 (<DynamicArray2DCpp[int32_t]*>self.thisptr).shrink(new_rows)
379 elif self.dtype == np.int64:
380 (<DynamicArray2DCpp[int64_t]*>self.thisptr).shrink(new_rows)
381 elif self.dtype == np.bool_:
382 (<DynamicArray2DCpp[char]*>self.thisptr).shrink(new_rows)
383 else:
384 # Shrink both dimensions
385 new_rows = new_shape[0]
386 new_cols = new_shape[1]
387 if self.dtype == np.float64:
388 (<DynamicArray2DCpp[double]*>self.thisptr).shrink(new_rows, new_cols)
389 elif self.dtype == np.float32:
390 (<DynamicArray2DCpp[float]*>self.thisptr).shrink(new_rows, new_cols)
391 elif self.dtype == np.int32:
392 (<DynamicArray2DCpp[int32_t]*>self.thisptr).shrink(new_rows, new_cols)
393 elif self.dtype == np.int64:
394 (<DynamicArray2DCpp[int64_t]*>self.thisptr).shrink(new_rows, new_cols)
395 elif self.dtype == np.bool_:
396 (<DynamicArray2DCpp[char]*>self.thisptr).shrink(new_rows, new_cols)
397
398 @property
399 def data(self):
400 """
401 The magic getter! This creates a zero-copy NumPy 'view' of our C++ data.
402 It's not a copy; it's a direct window into the C++ memory, which is why it's so fast.
403 Every time our code accesses `my_array.data`, this code runs to build that view on the fly.
404 """
405 # First, what's the logical shape the user sees,we get it ...
406 cdef size_t rows = self.get_rows()
407 cdef size_t cols = self.get_cols()
408 # Now, the two most important pieces for our zero-copy trick:
409 # 1. The actual memory address where our data lives in C++.
410 cdef void* data_ptr = self.get_data_ptr()
411 # 2. The *physical* width of a row in memory. This might be wider than `cols`
412 # if we've over-allocated space to make future growth faster.
413 cdef size_t stride = self.get_stride()
414 # How many bytes does one element take up? (e.g., 8 for a float64)
415 cdef size_t itemsize = self.dtype.itemsize
416
417 # --- Now we create the "map" that tells NumPy how to navigate our C++ memory correctly ---
418
419 # These are C-style arrays to hold the shape and the "stride map".
420 cdef cnp.npy_intp shape[2]
421 cdef cnp.npy_intp strides[2]
422
423 # So the shape is easy as it's just the logical dimensions.
424 shape[0] = rows
425 shape[1] = cols
426
427 # Now, the stride map. This tells NumPy how many *bytes* to jump to move through the data.
428 # To move to the next item in the same row (j -> j+1), just jump by one item's size.
429 strides[1] = itemsize
430 # To move to the *next row* (i -> i+1), we have to jump over a whole physical row in memory.
431 strides[0] = stride * itemsize
432
433 # We also need to describe our data type (e.g., float64) to NumPy in its native C language.
434 cdef cnp.PyArray_Descr* descr = PyArray_DescrFromType(self.numpy_type)
435
436 # Now we set the permissions and properties for our numpy view
437 # Let's start with a crucial permission: making the array writeable!
438 # Without this, NumPy would make it read-only, and `arr[i] = x` would fail.
439 cdef int flags = cnp.NPY_ARRAY_WRITEABLE
440
441 # A little optimization: if the memory is perfectly packed (no extra space in rows),
442 # we can tell NumPy it's "C-contiguous". This can speed up some operations.
443 if stride == cols:
444 flags |= cnp.NPY_ARRAY_C_CONTIGUOUS
445
446 # Here we call the master C-API function, we give it:
447 # the memory pointer, the shape map, the stride map, the data type, and the permissions.
448 cdef cnp.ndarray result = <cnp.ndarray>PyArray_NewFromDescr(
449 <PyTypeObject*>np.ndarray,
450 descr,
451 2,
452 shape,
453 strides,
454 data_ptr,
455 flags, # Use our flags variable
456 None
457 )
458
459 # By default, NumPy assumes it owns the data and will try to free it later.
460 # But *our* C++ vector owns it! Clearing this flag prevents a double-free, which would crash the program.
461 cnp.PyArray_CLEARFLAGS(result, cnp.NPY_ARRAY_OWNDATA)
462 return result
463
464 @property
465 def shape(self):
466 return (self.get_rows(), self.get_cols())
467
468 def __getitem__(self, item):
469 return self.data[item]
470
471 def __setitem__(self, item, val):
472 cdef cnp.ndarray arr = self.data
473 arr[item] = val
474
475 def __len__(self):
476 return self.get_rows()
477
478
479 # Factory functions matching original API we had in python code
480 def DynamicArray(shape, dtype=float, factor=2, use_numpy_resize=False, refcheck=True):
481 """Create appropriate dynamic array based on shape"""
482 if isinstance(shape, int):
483 shape = (shape,)
484
485 if len(shape) == 1:
486 return DynamicArray1DClass(shape[0], dtype, factor)
487 elif len(shape) == 2:
488 return DynamicArray2DClass(shape, dtype, factor)
489 else:
490 raise ValueError(
491 f"DynamicArray only supports 1D or 2D shapes. Got shape={shape} (dim={len(shape)})"
492 )
493
494 def DynamicArray1D(shape, dtype=float, factor=2, use_numpy_resize=False, refcheck=True):
495 """Create 1D dynamic array"""
496 if isinstance(shape, int):
497 shape = (shape,)
498 return DynamicArray1DClass(shape[0], dtype, factor)