Run the simulations in parallel for speed

This commit is contained in:
Chris Greening 2022-11-23 16:19:12 +00:00
parent 370fba91fc
commit 2c03cca84f
2 changed files with 27 additions and 14 deletions

View file

@ -5,3 +5,4 @@ pandas
scikit-spatial scikit-spatial
pre-commit pre-commit
plotly plotly
multiprocess

View file

@ -290,6 +290,20 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"import multiprocess as mp\n",
"\n",
"\n",
"def calculate_forces_on_coil(coil, x, y, z):\n",
" points = coil.copy()\n",
" for i in range(len(points)):\n",
" points[i][0] = points[i][0] / 100 + x\n",
" points[i][1] = points[i][1] / 100 + y\n",
" points[i][2] = points[i][2] / 100 + z\n",
" # feel the force\n",
" Fx_, Fy_, Fz_ = calculate_forces_on_wire_points(points)\n",
" return sum(Fx_), sum(Fy_), sum(Fz_)\n",
"\n",
"\n",
"# instead of sweeping horizontally, we'll sweep the coils around a circle\n", "# instead of sweeping horizontally, we'll sweep the coils around a circle\n",
"def sweep_coil_circle(coil, coil_center_radius, theta):\n", "def sweep_coil_circle(coil, coil_center_radius, theta):\n",
" X = coil_center_radius * np.cos(np.deg2rad(theta))\n", " X = coil_center_radius * np.cos(np.deg2rad(theta))\n",
@ -300,21 +314,19 @@
" Fx = []\n", " Fx = []\n",
" Fy = []\n", " Fy = []\n",
" Fz = []\n", " Fz = []\n",
" for p in range(len(theta)):\n",
" x = X[p]\n",
" y = Y[p]\n",
" z = Z\n",
"\n", "\n",
" points = coil.copy()\n", " # run this in parallel\n",
" for i in range(len(points)):\n", " with mp.Pool(mp.cpu_count()) as pool:\n",
" points[i][0] = points[i][0] / 100 + x\n", " params = [(coil, X[p], Y[p], Z) for p in range(len(theta))]\n",
" points[i][1] = points[i][1] / 100 + y\n", " results = [\n",
" points[i][2] = points[i][2] / 100 + z\n", " pool.apply_async(calculate_forces_on_coil, params) for params in params\n",
" # feel the force\n", " ]\n",
" Fx_, Fy_, Fz_ = calculate_forces_on_wire_points(points)\n", "\n",
" Fx.append(sum(Fx_))\n", " for result in results:\n",
" Fy.append(sum(Fy_))\n", " fx, fy, fz = result.get()\n",
" Fz.append(sum(Fz_))\n", " Fx.append(fx)\n",
" Fy.append(fy)\n",
" Fz.append(fz)\n",
" return Fx, Fy, Fz\n", " return Fx, Fy, Fz\n",
"\n", "\n",
"\n", "\n",