forked from sunqm/capi_example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcythonenergy.pyx
58 lines (51 loc) · 1.68 KB
/
cythonenergy.pyx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#cython: boundscheck=False
#cython: wraparound=False
#cython: overflowcheck.fold=False
#cython: cdivision=True
import numpy
cimport numpy
cimport cython
cimport libc.math
import fortranenergy
from libcpp.vector cimport vector
cdef extern double run_(double *coord1, double *coord2,
double *charge1, double *charge2)
cdef extern from 'cppenergy.h' namespace 'coulomb':
double runcpp(vector[double]& ri, vector[double]& rj,
double chg1, double chg2)
def energy_naive(numpy.ndarray[double,ndim=2] coord, numpy.ndarray[double] charge):
nc = len(charge)
e = 0
for i in range(nc):
for j in range(i):
dr = coord[i] - coord[j]
e += charge[i] * charge[j] / numpy.linalg.norm(dr)
return e
def energy_fast(double[:,:] coord, double[:] charge):
cdef int i
cdef int j
cdef int nc = len(charge)
cdef double e = 0
cdef double dx, dy, dz
for i in range(nc):
for j in range(i):
dx = coord[i,0] - coord[j,0]
dy = coord[i,1] - coord[j,1]
dz = coord[i,2] - coord[j,2]
r = libc.math.sqrt(dx*dx+dy*dy+dz*dz)
e += charge[i] * charge[j] / r
return e
def energy_f(numpy.ndarray[double,ndim=2] coord, numpy.ndarray[double] charge):
nc = len(charge)
e = 0
for i in range(nc):
for j in range(i):
e += run_(&coord[i,0], &coord[j,0], &charge[i], &charge[j])
return e
def energy_cpp(numpy.ndarray[double,ndim=2] coord, numpy.ndarray[double] charge):
nc = len(charge)
e = 0
for i in range(nc):
for j in range(i):
e += runcpp(coord[i], coord[j], charge[i], charge[j])
return e