Created
July 13, 2021 15:54
-
-
Save lgarrison/3a60218005cf2e822127367da211dad3 to your computer and use it in GitHub Desktop.
simple N^2 gravitational potential calculator in numba
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"cells": [ | |
{ | |
"cell_type": "code", | |
"execution_count": 1, | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"name": "stdout", | |
"output_type": "stream", | |
"text": [ | |
"13.8 ms ± 142 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)\n" | |
] | |
} | |
], | |
"source": [ | |
"import numba\n", | |
"import numpy as np\n", | |
"\n", | |
"@numba.njit(parallel=True,fastmath=True)\n", | |
"def potential(X, eps, dtype=np.float32, nthread=1):\n", | |
" # things to check:\n", | |
" # - parallel and serial give same answer\n", | |
" # - big halos give same answer for dtype=np.float64 and float32\n", | |
" \n", | |
" numba.set_num_threads(nthread)\n", | |
" \n", | |
" N = len(X)\n", | |
" pot = np.zeros(N, dtype=dtype)\n", | |
" eps2 = dtype(eps**2)\n", | |
" \n", | |
" for i in numba.prange(N):\n", | |
" x1,y1,z1 = X[i][0],X[i][1],X[i][2]\n", | |
" for j in range(N):\n", | |
" x2,y2,z2 = X[j][0],X[j][1],X[j][2]\n", | |
" invr = dtype(1.)/np.sqrt( (x1 - x2)**2 + (y1 - y2)**2 + (z1 - z2)**2 + eps2)\n", | |
" pot[i] += invr\n", | |
" \n", | |
" pot -= 1/eps # remove self-potential\n", | |
" return pot\n", | |
"\n", | |
"rng = np.random.default_rng()\n", | |
"pos = rng.random((10**4,3), dtype=np.float32)\n", | |
"\n", | |
"%timeit potential(pos, 1e-3, nthread=16)" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": {}, | |
"outputs": [], | |
"source": [] | |
} | |
], | |
"metadata": { | |
"kernelspec": { | |
"display_name": "forge", | |
"language": "python", | |
"name": "forge" | |
}, | |
"language_info": { | |
"codemirror_mode": { | |
"name": "ipython", | |
"version": 3 | |
}, | |
"file_extension": ".py", | |
"mimetype": "text/x-python", | |
"name": "python", | |
"nbconvert_exporter": "python", | |
"pygments_lexer": "ipython3", | |
"version": "3.8.2" | |
} | |
}, | |
"nbformat": 4, | |
"nbformat_minor": 4 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment