From 2c03cca84fb755b941efa1b2197148cc27735b89 Mon Sep 17 00:00:00 2001 From: Chris Greening Date: Wed, 23 Nov 2022 16:19:12 +0000 Subject: [PATCH] Run the simulations in parallel for speed --- requirements.txt | 1 + simulations/magnetic_force_on_coils.ipynb | 40 +++++++++++++++-------- 2 files changed, 27 insertions(+), 14 deletions(-) diff --git a/requirements.txt b/requirements.txt index d76c92f..5cd3dad 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,3 +5,4 @@ pandas scikit-spatial pre-commit plotly +multiprocess \ No newline at end of file diff --git a/simulations/magnetic_force_on_coils.ipynb b/simulations/magnetic_force_on_coils.ipynb index 3e955f6..add5cec 100644 --- a/simulations/magnetic_force_on_coils.ipynb +++ b/simulations/magnetic_force_on_coils.ipynb @@ -290,6 +290,20 @@ "metadata": {}, "outputs": [], "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", "def sweep_coil_circle(coil, coil_center_radius, theta):\n", " X = coil_center_radius * np.cos(np.deg2rad(theta))\n", @@ -300,21 +314,19 @@ " Fx = []\n", " Fy = []\n", " Fz = []\n", - " for p in range(len(theta)):\n", - " x = X[p]\n", - " y = Y[p]\n", - " z = Z\n", "\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", - " Fx.append(sum(Fx_))\n", - " Fy.append(sum(Fy_))\n", - " Fz.append(sum(Fz_))\n", + " # run this in parallel\n", + " with mp.Pool(mp.cpu_count()) as pool:\n", + " params = [(coil, X[p], Y[p], Z) for p in range(len(theta))]\n", + " results = [\n", + " pool.apply_async(calculate_forces_on_coil, params) for params in params\n", + " ]\n", + "\n", + " for result in results:\n", + " fx, fy, fz = result.get()\n", + " Fx.append(fx)\n", + " Fy.append(fy)\n", + " Fz.append(fz)\n", " return Fx, Fy, Fz\n", "\n", "\n",