Skip to content

Commit

Permalink
Updated cimport for numpy to maintain cimport consistency (#4346)
Browse files Browse the repository at this point in the history
* Updated cimport for numpy to maintain cimport consistency

* Updated CHANGELOG and AUTHORS file
  • Loading branch information
Sumit112192 authored Dec 11, 2023
1 parent 51e45be commit 6179b2b
Show file tree
Hide file tree
Showing 13 changed files with 99 additions and 97 deletions.
1 change: 1 addition & 0 deletions package/AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,7 @@ Chronological list of authors
- Shubham Kumar
- Zaheer Timol
- Geongi Moon
- Sumit Gupta

External code
-------------
Expand Down
1 change: 1 addition & 0 deletions package/CHANGELOG
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ The rules for this file:
* 2.7.0

Fixes
* Updated cimport for numpy to maintain cimport consistency (Issue #3908)
* Fix `NoJump` unwrapping for jumps on the second frame in a
trajectory (PR #4258, Issue #4257)
* Deprecated np.float_ and np.NaN aliases have been replaced with
Expand Down
10 changes: 5 additions & 5 deletions package/MDAnalysis/analysis/encore/cutils.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -32,19 +32,19 @@ Mixed Cython utils for ENCORE


import numpy as np
cimport numpy as np
cimport numpy as cnp
import cython
from libc.math cimport sqrt

np.import_array()
cnp.import_array()


@cython.boundscheck(False)
@cython.wraparound(False)
def PureRMSD(np.ndarray[np.float64_t, ndim=2] coordsi,
np.ndarray[np.float64_t, ndim=2] coordsj,
def PureRMSD(cnp.ndarray[cnp.float64_t, ndim=2] coordsi,
cnp.ndarray[cnp.float64_t, ndim=2] coordsj,
int atomsn,
np.ndarray[np.float64_t, ndim=1] masses,
cnp.ndarray[cnp.float64_t, ndim=1] masses,
double summasses):

cdef int k
Expand Down
2 changes: 1 addition & 1 deletion package/MDAnalysis/coordinates/timestep.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -729,7 +729,7 @@ cdef class Timestep:
"""
if isinstance(atoms, numbers.Integral):
return self._pos[atoms]
elif isinstance(atoms, (slice, np.ndarray)):
elif isinstance(atoms, (slice, cnp.ndarray)):
return self._pos[atoms]
else:
raise TypeError
Expand Down
6 changes: 3 additions & 3 deletions package/MDAnalysis/lib/_augment.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,13 @@
import cython
import numpy as np
from .mdamath import triclinic_vectors
cimport numpy as np
cimport numpy as cnp
cimport MDAnalysis.lib._cutil
from MDAnalysis.lib._cutil cimport _dot, _norm, _cross

from libcpp.vector cimport vector

np.import_array()
cnp.import_array()


__all__ = ['augment_coordinates', 'undo_augment']
Expand Down Expand Up @@ -301,7 +301,7 @@ def augment_coordinates(float[:, ::1] coordinates, float[:] box, float r):

@cython.boundscheck(False)
@cython.wraparound(False)
def undo_augment(np.intp_t[:] results, np.intp_t[:] translation, int nreal):
def undo_augment(cnp.intp_t[:] results, cnp.intp_t[:] translation, int nreal):
"""Translate augmented indices back to original indices.
Parameters
Expand Down
40 changes: 20 additions & 20 deletions package/MDAnalysis/lib/_cutil.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

import cython
import numpy as np
cimport numpy as np
cimport numpy as cnp
from libc.math cimport sqrt, fabs

from MDAnalysis import NoDataError
Expand All @@ -35,7 +35,7 @@ from libcpp.vector cimport vector
from libcpp.utility cimport pair
from cython.operator cimport dereference as deref

np.import_array()
cnp.import_array()

__all__ = ['unique_int_1d', 'make_whole', 'find_fragments',
'_sarrus_det_single', '_sarrus_det_multiple']
Expand All @@ -51,7 +51,7 @@ ctypedef cmap[int, intset] intmap

@cython.boundscheck(False) # turn off bounds-checking for entire function
@cython.wraparound(False) # turn off negative index wrapping for entire function
def unique_int_1d(np.intp_t[:] values):
def unique_int_1d(cnp.intp_t[:] values):
"""Find the unique elements of a 1D array of integers.
This function is optimal on sorted arrays.
Expand All @@ -73,7 +73,7 @@ def unique_int_1d(np.intp_t[:] values):
cdef int i = 0
cdef int j = 0
cdef int n_values = values.shape[0]
cdef np.intp_t[:] result = np.empty(n_values, dtype=np.intp)
cdef cnp.intp_t[:] result = np.empty(n_values, dtype=np.intp)

if n_values == 0:
return np.array(result)
Expand All @@ -93,7 +93,7 @@ def unique_int_1d(np.intp_t[:] values):


@cython.boundscheck(False)
def _in2d(np.intp_t[:, :] arr1, np.intp_t[:, :] arr2):
def _in2d(cnp.intp_t[:, :] arr1, cnp.intp_t[:, :] arr2):
"""Similar to np.in1d except works on 2d arrays
Parameters
Expand All @@ -110,8 +110,8 @@ def _in2d(np.intp_t[:, :] arr1, np.intp_t[:, :] arr2):
"""
cdef object out
cdef ssize_t i
cdef cset[pair[np.intp_t, np.intp_t]] hits
cdef pair[np.intp_t, np.intp_t] p
cdef cset[pair[cnp.intp_t, cnp.intp_t]] hits
cdef pair[cnp.intp_t, cnp.intp_t] p

"""
Construct a set from arr2 called hits
Expand All @@ -130,13 +130,13 @@ def _in2d(np.intp_t[:, :] arr1, np.intp_t[:, :] arr2):
raise ValueError("Both arrays must be (n, 2) arrays")

for i in range(arr2.shape[0]):
p = pair[np.intp_t, np.intp_t](arr2[i, 0], arr2[i, 1])
p = pair[cnp.intp_t, cnp.intp_t](arr2[i, 0], arr2[i, 1])
hits.insert(p)

out = np.empty(arr1.shape[0], dtype=np.uint8)
cdef unsigned char[::1] results = out
for i in range(arr1.shape[0]):
p = pair[np.intp_t, np.intp_t](arr1[i, 0], arr1[i, 1])
p = pair[cnp.intp_t, cnp.intp_t](arr1[i, 0], arr1[i, 1])

if hits.count(p):
results[i] = True
Expand Down Expand Up @@ -243,7 +243,7 @@ def make_whole(atomgroup, reference_atom=None, inplace=True):
are returned as a numpy array.
"""
cdef intset refpoints, todo, done
cdef np.intp_t i, j, nloops, ref, atom, other, natoms
cdef cnp.intp_t i, j, nloops, ref, atom, other, natoms
cdef cmap[int, int] ix_to_rel
cdef intmap bonding
cdef int[:, :] bonds
Expand Down Expand Up @@ -334,7 +334,7 @@ def make_whole(atomgroup, reference_atom=None, inplace=True):
newpos[ref, i] = oldpos[ref, i]

nloops = 0
while <np.intp_t> refpoints.size() < natoms and nloops < natoms:
while <cnp.intp_t> refpoints.size() < natoms and nloops < natoms:
# count iterations to prevent infinite loop here
nloops += 1

Expand Down Expand Up @@ -362,7 +362,7 @@ def make_whole(atomgroup, reference_atom=None, inplace=True):
refpoints.insert(other)
done.insert(atom)

if <np.intp_t> refpoints.size() < natoms:
if <cnp.intp_t> refpoints.size() < natoms:
raise ValueError("AtomGroup was not contiguous from bonds, process failed")
if inplace:
atomgroup.positions = newpos
Expand Down Expand Up @@ -411,9 +411,9 @@ cdef float _norm(float * a):
@cython.boundscheck(False)
@cython.wraparound(False)
cpdef np.float64_t _sarrus_det_single(np.float64_t[:, ::1] m):
cpdef cnp.float64_t _sarrus_det_single(cnp.float64_t[:, ::1] m):
"""Computes the determinant of a 3x3 matrix."""
cdef np.float64_t det
cdef cnp.float64_t det
det = m[0, 0] * m[1, 1] * m[2, 2]
det -= m[0, 0] * m[1, 2] * m[2, 1]
det += m[0, 1] * m[1, 2] * m[2, 0]
Expand All @@ -425,11 +425,11 @@ cpdef np.float64_t _sarrus_det_single(np.float64_t[:, ::1] m):
@cython.boundscheck(False)
@cython.wraparound(False)
cpdef np.ndarray _sarrus_det_multiple(np.float64_t[:, :, ::1] m):
cpdef cnp.ndarray _sarrus_det_multiple(cnp.float64_t[:, :, ::1] m):
"""Computes all determinants of an array of 3x3 matrices."""
cdef np.intp_t n
cdef np.intp_t i
cdef np.float64_t[:] det
cdef cnp.intp_t n
cdef cnp.intp_t i
cdef cnp.float64_t[:] det
n = m.shape[0]
det = np.empty(n, dtype=np.float64)
for i in range(n):
Expand Down Expand Up @@ -470,8 +470,8 @@ def find_fragments(atoms, bondlist):
cdef intset todo, frag_todo, frag_done
cdef vector[int] this_frag
cdef int i, a, b
cdef np.int64_t[:] atoms_view
cdef np.int32_t[:, :] bonds_view
cdef cnp.int64_t[:] atoms_view
cdef cnp.int32_t[:, :] bonds_view

atoms_view = np.asarray(atoms, dtype=np.int64)
bonds_view = np.asarray(bondlist, dtype=np.int32)
Expand Down
6 changes: 3 additions & 3 deletions package/MDAnalysis/lib/formats/cython_util.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,6 @@
# MDAnalysis: A Toolkit for the Analysis of Molecular Dynamics Simulations.
# J. Comput. Chem. 32 (2011), 2319--2327, doi:10.1002/jcc.21787
#
cimport numpy as np
np.import_array()
cdef np.ndarray ptr_to_ndarray(void* data_ptr, np.int64_t[:] dim, int data_type)
cimport numpy as cnp
cnp.import_array()
cdef cnp.ndarray ptr_to_ndarray(void* data_ptr, cnp.int64_t[:] dim, int data_type)
12 changes: 6 additions & 6 deletions package/MDAnalysis/lib/formats/cython_util.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@
# J. Comput. Chem. 32 (2011), 2319--2327, doi:10.1002/jcc.21787
#
import numpy as np
cimport numpy as np
cimport numpy as cnp

from libc.stdlib cimport free
from cpython cimport PyObject, Py_INCREF

np.import_array()
cnp.import_array()


cdef class ArrayWrapper:
Expand Down Expand Up @@ -74,8 +74,8 @@ cdef class ArrayWrapper:
def __array__(self):
""" Here we use the __array__ method, that is called when numpy
tries to get an array from the object."""
ndarray = np.PyArray_SimpleNewFromData(self.ndim,
<np.npy_intp*> self.dim,
ndarray = cnp.PyArray_SimpleNewFromData(self.ndim,
<cnp.npy_intp*> self.dim,
self.data_type,
self.data_ptr)
return ndarray
Expand All @@ -87,7 +87,7 @@ cdef class ArrayWrapper:
# free(<int*>self.dim)


cdef np.ndarray ptr_to_ndarray(void* data_ptr, np.int64_t[:] dim, int data_type):
cdef cnp.ndarray ptr_to_ndarray(void* data_ptr, cnp.int64_t[:] dim, int data_type):
"""convert a pointer to an arbitrary C-pointer to a ndarray. The ndarray is
constructed so that the array it's holding will be freed when the array is
destroyed.
Expand All @@ -110,7 +110,7 @@ cdef np.ndarray ptr_to_ndarray(void* data_ptr, np.int64_t[:] dim, int data_type)
array_wrapper = ArrayWrapper()
array_wrapper.set_data(<void*> data_ptr, <int*> &dim[0], dim.size, data_type)

cdef np.ndarray ndarray = np.array(array_wrapper, copy=False)
cdef cnp.ndarray ndarray = np.array(array_wrapper, copy=False)
# Assign our object to the 'base' of the ndarray object
ndarray[:] = array_wrapper.__array__()
# Increment the reference count, as the above assignement was done in
Expand Down
8 changes: 4 additions & 4 deletions package/MDAnalysis/lib/formats/libdcd.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@ from libc.stdint cimport uintptr_t
from libc.stdio cimport SEEK_SET, SEEK_CUR, SEEK_END
import cython

cimport numpy as np
cimport numpy as cnp

np.import_array()
cnp.import_array()


# Tell cython about the off_t type. It doesn't need to match exactly what is
Expand Down Expand Up @@ -131,9 +131,9 @@ cdef class DCDFile:


# buffer for reading coordinates
cdef np.ndarray _coordinate_buffer
cdef cnp.ndarray _coordinate_buffer
# buffer for reading unitcell
cdef np.ndarray _unitcell_buffer
cdef cnp.ndarray _unitcell_buffer

# fortran contiguious memoryviews of the buffers to pass to the C code
cdef float[::1] xview
Expand Down
32 changes: 16 additions & 16 deletions package/MDAnalysis/lib/formats/libdcd.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -71,12 +71,12 @@ import string
import sys
import cython

cimport numpy as np
cimport numpy as cnp
from libc.stdio cimport SEEK_SET, SEEK_CUR, SEEK_END
from libc.stdint cimport uintptr_t
from libc.stdlib cimport free

np.import_array()
cnp.import_array()

_whence_vals = {"FIO_SEEK_SET": SEEK_SET,
"FIO_SEEK_CUR": SEEK_CUR,
Expand Down Expand Up @@ -342,14 +342,14 @@ cdef class DCDFile:
self.remarks = py_remarks

cdef void _setup_buffers(self):
cdef np.npy_intp[2] dims
cdef cnp.npy_intp[2] dims
dims[0] = self.natoms
dims[1] = self.ndims
# note use of fortran flag (1)
self._coordinate_buffer = np.PyArray_EMPTY(2, dims, np.NPY_FLOAT32, 1)
cdef np.npy_intp[1] unitcell_dims
self._coordinate_buffer = cnp.PyArray_EMPTY(2, dims, cnp.NPY_FLOAT32, 1)
cdef cnp.npy_intp[1] unitcell_dims
unitcell_dims[0] = 6
self._unitcell_buffer = np.PyArray_EMPTY(1, unitcell_dims, np.NPY_FLOAT64, 0)
self._unitcell_buffer = cnp.PyArray_EMPTY(1, unitcell_dims, cnp.NPY_FLOAT64, 0)

# fortran contiguity
self.xview = self._coordinate_buffer[:, 0]
Expand Down Expand Up @@ -515,8 +515,8 @@ cdef class DCDFile:

if not self.wrote_header:
raise IOError("write header first before frames can be written")
cdef np.ndarray xyz_ = np.asarray(xyz, order='F', dtype=FLOAT)
cdef np.npy_intp[2] shape = np.PyArray_DIMS(xyz_)
cdef cnp.ndarray xyz_ = np.asarray(xyz, order='F', dtype=FLOAT)
cdef cnp.npy_intp[2] shape = cnp.PyArray_DIMS(xyz_)
if (shape[0] != self.natoms) or (shape[1] != 3):
raise ValueError("xyz shape is wrong should be (natoms, 3), got:".format(xyz.shape))
cdef double[::1] c_box = np.asarray(box, order='C', dtype=DOUBLE)
Expand Down Expand Up @@ -638,15 +638,15 @@ cdef class DCDFile:
cdef int n
n = len(range(start, stop, step))
cdef int natoms
cdef np.ndarray[np.int64_t, ndim=1] c_indices
cdef cnp.ndarray[cnp.int64_t, ndim=1] c_indices
if indices is None:
c_indices = np.PyArray_Arange(0, self.natoms, 1, np.NPY_INT64)
c_indices = cnp.PyArray_Arange(0, self.natoms, 1, cnp.NPY_INT64)
natoms = self.natoms
else:
natoms = len(indices)
c_indices = np.asarray(indices, dtype=np.int64)

cdef np.npy_intp[3] dims
cdef cnp.npy_intp[3] dims
cdef int hash_order = -1
if order == 'fac':
dims[0] = n
Expand Down Expand Up @@ -681,17 +681,17 @@ cdef class DCDFile:
else:
raise ValueError("unkown order '{}'".format(order))

cdef np.ndarray[float, ndim=3] xyz = np.PyArray_EMPTY(3, dims, np.NPY_FLOAT32, 0)
cdef np.npy_intp[2] unitcell_dims
cdef cnp.ndarray[float, ndim=3] xyz = cnp.PyArray_EMPTY(3, dims, cnp.NPY_FLOAT32, 0)
cdef cnp.npy_intp[2] unitcell_dims
unitcell_dims[0] = n
unitcell_dims[1] = 6
cdef np.ndarray[double, ndim=2] box = np.PyArray_EMPTY(2, unitcell_dims, np.NPY_FLOAT64, 0)
cdef cnp.ndarray[double, ndim=2] box = cnp.PyArray_EMPTY(2, unitcell_dims, cnp.NPY_FLOAT64, 0)

cdef np.npy_intp[2] xyz_tmp_dims
cdef cnp.npy_intp[2] xyz_tmp_dims
xyz_tmp_dims[0] = self.natoms
xyz_tmp_dims[1] = self.ndims
# note fortran flag (1)
cdef np.ndarray[float, ndim=2] xyz_tmp = np.PyArray_EMPTY(2, xyz_tmp_dims, np.NPY_FLOAT32, 1)
cdef cnp.ndarray[float, ndim=2] xyz_tmp = cnp.PyArray_EMPTY(2, xyz_tmp_dims, cnp.NPY_FLOAT32, 1)

# memoryviews for slices into xyz_temp, note fortran contiguous
cdef float[::1] x = xyz_tmp[:, 0]
Expand Down
Loading

0 comments on commit 6179b2b

Please sign in to comment.