1cimport numpy as np 2from libc.math cimport sqrt, exp 3 4from ..utils._typedefs cimport DTYPE_t, ITYPE_t 5 6###################################################################### 7# Inline distance functions 8# 9# We use these for the default (euclidean) case so that they can be 10# inlined. This leads to faster computation for the most common case 11cdef inline DTYPE_t euclidean_dist(const DTYPE_t* x1, const DTYPE_t* x2, 12 ITYPE_t size) nogil except -1: 13 cdef DTYPE_t tmp, d=0 14 cdef np.intp_t j 15 for j in range(size): 16 tmp = x1[j] - x2[j] 17 d += tmp * tmp 18 return sqrt(d) 19 20 21cdef inline DTYPE_t euclidean_rdist(const DTYPE_t* x1, const DTYPE_t* x2, 22 ITYPE_t size) nogil except -1: 23 cdef DTYPE_t tmp, d=0 24 cdef np.intp_t j 25 for j in range(size): 26 tmp = x1[j] - x2[j] 27 d += tmp * tmp 28 return d 29 30 31cdef inline DTYPE_t euclidean_dist_to_rdist(const DTYPE_t dist) nogil except -1: 32 return dist * dist 33 34 35cdef inline DTYPE_t euclidean_rdist_to_dist(const DTYPE_t dist) nogil except -1: 36 return sqrt(dist) 37 38 39###################################################################### 40# DistanceMetric base class 41cdef class DistanceMetric: 42 # The following attributes are required for a few of the subclasses. 43 # we must define them here so that cython's limited polymorphism will work. 44 # Because we don't expect to instantiate a lot of these objects, the 45 # extra memory overhead of this setup should not be an issue. 46 cdef DTYPE_t p 47 cdef DTYPE_t[::1] vec 48 cdef DTYPE_t[:, ::1] mat 49 cdef ITYPE_t size 50 cdef object func 51 cdef object kwargs 52 53 cdef DTYPE_t dist(self, const DTYPE_t* x1, const DTYPE_t* x2, 54 ITYPE_t size) nogil except -1 55 56 cdef DTYPE_t rdist(self, const DTYPE_t* x1, const DTYPE_t* x2, 57 ITYPE_t size) nogil except -1 58 59 cdef int pdist(self, const DTYPE_t[:, ::1] X, DTYPE_t[:, ::1] D) except -1 60 61 cdef int cdist(self, const DTYPE_t[:, ::1] X, const DTYPE_t[:, ::1] Y, 62 DTYPE_t[:, ::1] D) except -1 63 64 cdef DTYPE_t _rdist_to_dist(self, DTYPE_t rdist) nogil except -1 65 66 cdef DTYPE_t _dist_to_rdist(self, DTYPE_t dist) nogil except -1 67