├── .github ├── CODEOWNERS ├── ISSUE_TEMPLATE.md └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── CONTRIBUTING.md ├── Ch02 ├── 02_02_numpyintro-complete.ipynb ├── 02_02_numpyintro.ipynb ├── 02_03_numpycompute-complete.ipynb ├── 02_03_numpycompute.ipynb ├── 02_04_numpymatrix-complete.ipynb ├── 02_04_numpymatrix.ipynb ├── 02_05_codegeneration-complete.ipynb ├── 02_05_codegeneration.ipynb ├── 02_06_legacywrap-complete.ipynb ├── 02_06_legacywrap.ipynb ├── 02_07_challenge-complete.ipynb ├── 02_07_challenge.ipynb ├── 02_08_solution.ipynb ├── 02_08_solution_complete.ipynb └── image.npy ├── Ch03 ├── 03_02_sympy-complete.ipynb ├── 03_02_sympy.ipynb ├── 03_03_astropy-complete.ipynb ├── 03_03_astropy.ipynb ├── 03_04_ode-complete.ipynb ├── 03_04_ode.ipynb ├── 03_05_morescipy-complete.ipynb ├── 03_05_morescipy.ipynb ├── 03_06_debugging-complete.ipynb ├── 03_06_debugging.ipynb ├── 03_07_challenge-complete.ipynb ├── 03_07_challenge.ipynb ├── 03_08_solution-complete.ipynb └── 03_08_solution.ipynb ├── Ch04 ├── 04_02_web-complete.ipynb ├── 04_02_web.ipynb ├── 04_03_pandas-complete.ipynb ├── 04_03_pandas.ipynb ├── 04_04_hdf5-complete.ipynb ├── 04_04_hdf5.ipynb ├── 04_05_scripting-complete.ipynb ├── 04_05_scripting.ipynb ├── 04_06_snakemake-complete.ipynb ├── 04_06_snakemake.ipynb ├── 04_07_challenge-complete.ipynb ├── 04_07_challenge.ipynb ├── 04_08_solution-complete.ipynb ├── 04_08_solution.ipynb ├── cache │ ├── GW150914-v3.pickle │ ├── H-H1_GWOSC_4KHZ_R1-1126259447-32.hdf5 │ ├── L-L1_GWOSC_4KHZ_R1-1126259447-32.hdf5 │ └── gwtc-20210726.csv ├── events │ └── .gitignore ├── hdfdownload.py └── plotsignal.py ├── LICENSE ├── NOTICE └── README.md /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | # Codeowners for these exercise files: 2 | # * (asterisk) deotes "all files and folders" 3 | # Example: * @producer @instructor 4 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 7 | 8 | ## Issue Overview 9 | 10 | 11 | ## Describe your environment 12 | 13 | 14 | ## Steps to Reproduce 15 | 16 | 1. 17 | 2. 18 | 3. 19 | 4. 20 | 21 | ## Expected Behavior 22 | 23 | 24 | ## Current Behavior 25 | 26 | 27 | ## Possible Solution 28 | 29 | 30 | ## Screenshots / Video 31 | 32 | 33 | ## Related Issues 34 | 35 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | .tmp 4 | npm-debug.log 5 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | 2 | Contribution Agreement 3 | ====================== 4 | 5 | This repository does not accept pull requests (PRs). All pull requests will be closed. 6 | 7 | However, if any contributions (through pull requests, issues, feedback or otherwise) are provided, as a contributor, you represent that the code you submit is your original work or that of your employer (in which case you represent you have the right to bind your employer). By submitting code (or otherwise providing feedback), you (and, if applicable, your employer) are licensing the submitted code (and/or feedback) to LinkedIn and the open source community subject to the BSD 2-Clause license. 8 | -------------------------------------------------------------------------------- /Ch02/02_02_numpyintro.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 02_02_numpyintro.ipynb - Introduction to NumPy arrays" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "import numpy as np\n", 17 | "import matplotlib.pyplot as pp" 18 | ] 19 | }, 20 | { 21 | "cell_type": "code", 22 | "execution_count": null, 23 | "metadata": {}, 24 | "outputs": [], 25 | "source": [ 26 | "array = np.load('image.npy')" 27 | ] 28 | }, 29 | { 30 | "cell_type": "code", 31 | "execution_count": null, 32 | "metadata": {}, 33 | "outputs": [], 34 | "source": [ 35 | "type(array)" 36 | ] 37 | }, 38 | { 39 | "cell_type": "code", 40 | "execution_count": null, 41 | "metadata": {}, 42 | "outputs": [], 43 | "source": [ 44 | "array.ndim" 45 | ] 46 | }, 47 | { 48 | "cell_type": "code", 49 | "execution_count": null, 50 | "metadata": {}, 51 | "outputs": [], 52 | "source": [ 53 | "array.shape" 54 | ] 55 | }, 56 | { 57 | "cell_type": "code", 58 | "execution_count": null, 59 | "metadata": {}, 60 | "outputs": [], 61 | "source": [ 62 | "array.dtype" 63 | ] 64 | }, 65 | { 66 | "cell_type": "code", 67 | "execution_count": null, 68 | "metadata": {}, 69 | "outputs": [], 70 | "source": [ 71 | "array.size, 599 * 402 * 3" 72 | ] 73 | }, 74 | { 75 | "cell_type": "code", 76 | "execution_count": null, 77 | "metadata": {}, 78 | "outputs": [], 79 | "source": [ 80 | "pp.imshow(array)" 81 | ] 82 | }, 83 | { 84 | "cell_type": "code", 85 | "execution_count": null, 86 | "metadata": {}, 87 | "outputs": [], 88 | "source": [ 89 | "array[100,200,0]" 90 | ] 91 | }, 92 | { 93 | "cell_type": "code", 94 | "execution_count": null, 95 | "metadata": {}, 96 | "outputs": [], 97 | "source": [ 98 | "array[100,200,0] = 255" 99 | ] 100 | }, 101 | { 102 | "cell_type": "code", 103 | "execution_count": null, 104 | "metadata": {}, 105 | "outputs": [], 106 | "source": [ 107 | "array[100,200,0]" 108 | ] 109 | }, 110 | { 111 | "cell_type": "code", 112 | "execution_count": null, 113 | "metadata": {}, 114 | "outputs": [], 115 | "source": [ 116 | "array[10,0]" 117 | ] 118 | }, 119 | { 120 | "cell_type": "code", 121 | "execution_count": null, 122 | "metadata": {}, 123 | "outputs": [], 124 | "source": [ 125 | "subarray = array[0:150, 75:275, :]" 126 | ] 127 | }, 128 | { 129 | "cell_type": "code", 130 | "execution_count": null, 131 | "metadata": {}, 132 | "outputs": [], 133 | "source": [ 134 | "pp.imshow(subarray)" 135 | ] 136 | }, 137 | { 138 | "cell_type": "code", 139 | "execution_count": null, 140 | "metadata": {}, 141 | "outputs": [], 142 | "source": [ 143 | "subarray[80:100, :, :] = 0" 144 | ] 145 | }, 146 | { 147 | "cell_type": "code", 148 | "execution_count": null, 149 | "metadata": {}, 150 | "outputs": [], 151 | "source": [ 152 | "pp.imshow(subarray)" 153 | ] 154 | }, 155 | { 156 | "cell_type": "code", 157 | "execution_count": null, 158 | "metadata": {}, 159 | "outputs": [], 160 | "source": [ 161 | "pp.imshow(array)" 162 | ] 163 | }, 164 | { 165 | "cell_type": "code", 166 | "execution_count": null, 167 | "metadata": {}, 168 | "outputs": [], 169 | "source": [ 170 | "downscaled = array[0:599:20, 0:402:20, :]" 171 | ] 172 | }, 173 | { 174 | "cell_type": "code", 175 | "execution_count": null, 176 | "metadata": {}, 177 | "outputs": [], 178 | "source": [ 179 | "pp.imshow(downscaled)" 180 | ] 181 | }, 182 | { 183 | "cell_type": "code", 184 | "execution_count": null, 185 | "metadata": {}, 186 | "outputs": [], 187 | "source": [ 188 | "array.strides" 189 | ] 190 | }, 191 | { 192 | "cell_type": "code", 193 | "execution_count": null, 194 | "metadata": {}, 195 | "outputs": [], 196 | "source": [ 197 | "downscaled.strides" 198 | ] 199 | }, 200 | { 201 | "cell_type": "code", 202 | "execution_count": null, 203 | "metadata": {}, 204 | "outputs": [], 205 | "source": [ 206 | "grayscale = np.mean(array, axis=2) # remember we count from zero" 207 | ] 208 | }, 209 | { 210 | "cell_type": "code", 211 | "execution_count": null, 212 | "metadata": {}, 213 | "outputs": [], 214 | "source": [ 215 | "pp.imshow(grayscale, cmap='gray')" 216 | ] 217 | }, 218 | { 219 | "cell_type": "code", 220 | "execution_count": null, 221 | "metadata": {}, 222 | "outputs": [], 223 | "source": [ 224 | "grayscale[grayscale < 100] = 0" 225 | ] 226 | }, 227 | { 228 | "cell_type": "code", 229 | "execution_count": null, 230 | "metadata": {}, 231 | "outputs": [], 232 | "source": [ 233 | "grayscale > 0" 234 | ] 235 | }, 236 | { 237 | "cell_type": "code", 238 | "execution_count": null, 239 | "metadata": {}, 240 | "outputs": [], 241 | "source": [ 242 | "grayscale[grayscale > 0] = 255" 243 | ] 244 | }, 245 | { 246 | "cell_type": "code", 247 | "execution_count": null, 248 | "metadata": {}, 249 | "outputs": [], 250 | "source": [ 251 | "pp.imshow(grayscale, cmap='gray')" 252 | ] 253 | }, 254 | { 255 | "cell_type": "code", 256 | "execution_count": null, 257 | "metadata": {}, 258 | "outputs": [], 259 | "source": [ 260 | "downscaled.shape" 261 | ] 262 | }, 263 | { 264 | "cell_type": "code", 265 | "execution_count": null, 266 | "metadata": {}, 267 | "outputs": [], 268 | "source": [ 269 | "reshaped = downscaled.reshape((30//2,21*2,3))" 270 | ] 271 | }, 272 | { 273 | "cell_type": "code", 274 | "execution_count": null, 275 | "metadata": {}, 276 | "outputs": [], 277 | "source": [ 278 | "pp.imshow(reshaped)" 279 | ] 280 | } 281 | ], 282 | "metadata": { 283 | "kernelspec": { 284 | "display_name": "Python 3", 285 | "language": "python", 286 | "name": "python3" 287 | }, 288 | "language_info": { 289 | "codemirror_mode": { 290 | "name": "ipython", 291 | "version": 3 292 | }, 293 | "file_extension": ".py", 294 | "mimetype": "text/x-python", 295 | "name": "python", 296 | "nbconvert_exporter": "python", 297 | "pygments_lexer": "ipython3", 298 | "version": "3.8.8" 299 | }, 300 | "toc": { 301 | "base_numbering": 1, 302 | "nav_menu": {}, 303 | "number_sections": true, 304 | "sideBar": true, 305 | "skip_h1_title": false, 306 | "title_cell": "Table of Contents", 307 | "title_sidebar": "Contents", 308 | "toc_cell": false, 309 | "toc_position": {}, 310 | "toc_section_display": true, 311 | "toc_window_display": false 312 | } 313 | }, 314 | "nbformat": 4, 315 | "nbformat_minor": 4 316 | } 317 | -------------------------------------------------------------------------------- /Ch02/02_03_numpycompute.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 02_03_numpycompute.ipynb - Matrix operations with NumPy" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "import math\n", 17 | "\n", 18 | "import numpy as np\n", 19 | "import matplotlib.pyplot as pp" 20 | ] 21 | }, 22 | { 23 | "cell_type": "markdown", 24 | "metadata": {}, 25 | "source": [ 26 | "**Poisson equation**:\n", 27 | "\n", 28 | "$$\\frac{\\partial^2 \\phi(x,y)}{\\partial x^2} + \\frac{\\partial^2 \\phi(x,y)}{\\partial y^2} = 0$$" 29 | ] 30 | }, 31 | { 32 | "cell_type": "markdown", 33 | "metadata": {}, 34 | "source": [ 35 | "**Finite-difference representation of second derivatives:**\n", 36 | "\n", 37 | "$$\\frac{\\partial^2 \\phi(x_i,y_j)}{\\partial x^2} + \\frac{\\partial^2 \\phi(x_i,y_j)}{\\partial y^2} \\simeq\n", 38 | "\\phi(x_{i-1},y_j) + \\phi(x_{i+1},y_j) + \\phi(x_i,y_{j-1}) + \\phi(x_i,y_{j+1}) - 4 \\phi(x_i,y_j)$$" 39 | ] 40 | }, 41 | { 42 | "cell_type": "code", 43 | "execution_count": null, 44 | "metadata": {}, 45 | "outputs": [], 46 | "source": [ 47 | "n = 64\n", 48 | "phi = np.zeros((n,n), 'd') # 'd' is shorthand for np.float64" 49 | ] 50 | }, 51 | { 52 | "cell_type": "code", 53 | "execution_count": null, 54 | "metadata": {}, 55 | "outputs": [], 56 | "source": [ 57 | "phi[-1,:] = 1" 58 | ] 59 | }, 60 | { 61 | "cell_type": "code", 62 | "execution_count": null, 63 | "metadata": {}, 64 | "outputs": [], 65 | "source": [ 66 | "# show transpose and set origin='lower' for Cartesian convention \n", 67 | "pp.imshow(phi.T, origin='lower', extent=(0,1,0,1))" 68 | ] 69 | }, 70 | { 71 | "cell_type": "markdown", 72 | "metadata": {}, 73 | "source": [ 74 | "**Boundary conditions:**\n", 75 | "\n", 76 | "$$\\begin{eqnarray}\\phi(x=0, y) &=& 0 \\\\\n", 77 | "\\phi(x, y=0) &=& 0 \\\\\n", 78 | "\\phi(x, y=1) &=& \\sin(2 \\pi x) \\\\\n", 79 | "\\phi(x=1, y) &=& -\\sin(2 \\pi y)\\end{eqnarray}$$" 80 | ] 81 | }, 82 | { 83 | "cell_type": "code", 84 | "execution_count": null, 85 | "metadata": {}, 86 | "outputs": [], 87 | "source": [ 88 | "dx = 1/n\n", 89 | "xs = np.linspace(0.5*dx, 1-0.5*dx, n)" 90 | ] 91 | }, 92 | { 93 | "cell_type": "code", 94 | "execution_count": null, 95 | "metadata": {}, 96 | "outputs": [], 97 | "source": [ 98 | "xs" 99 | ] 100 | }, 101 | { 102 | "cell_type": "code", 103 | "execution_count": null, 104 | "metadata": {}, 105 | "outputs": [], 106 | "source": [ 107 | "for i in range(n):\n", 108 | " phi[i,-1] = math.sin(2 * math.pi * xs[i])" 109 | ] 110 | }, 111 | { 112 | "cell_type": "code", 113 | "execution_count": null, 114 | "metadata": {}, 115 | "outputs": [], 116 | "source": [ 117 | "np.sin(2 * math.pi * xs)" 118 | ] 119 | }, 120 | { 121 | "cell_type": "code", 122 | "execution_count": null, 123 | "metadata": {}, 124 | "outputs": [], 125 | "source": [ 126 | "phi[:,-1] = np.sin(2 * math.pi * xs)" 127 | ] 128 | }, 129 | { 130 | "cell_type": "code", 131 | "execution_count": null, 132 | "metadata": {}, 133 | "outputs": [], 134 | "source": [ 135 | "phi[-1,:] = -np.sin(2 * math.pi * xs)" 136 | ] 137 | }, 138 | { 139 | "cell_type": "code", 140 | "execution_count": null, 141 | "metadata": {}, 142 | "outputs": [], 143 | "source": [ 144 | "def initphi(n=64):\n", 145 | " dx = 1/n\n", 146 | " xs = np.linspace(0.5*dx, 1-0.5*dx, n)\n", 147 | " \n", 148 | " phi = np.zeros((n,n), 'd')\n", 149 | " \n", 150 | " phi[:,-1] = np.sin(2 * math.pi * xs)\n", 151 | " phi[-1,:] = -np.sin(2 * math.pi * xs)\n", 152 | " \n", 153 | " return phi" 154 | ] 155 | }, 156 | { 157 | "cell_type": "code", 158 | "execution_count": null, 159 | "metadata": {}, 160 | "outputs": [], 161 | "source": [ 162 | "def showphi(array, colorbar=True):\n", 163 | " pp.imshow(array.T, origin='lower', extent=(0,1,0,1),\n", 164 | " vmin=-1, vmax=1, cmap='coolwarm')\n", 165 | " \n", 166 | " if colorbar:\n", 167 | " pp.colorbar()" 168 | ] 169 | }, 170 | { 171 | "cell_type": "code", 172 | "execution_count": null, 173 | "metadata": {}, 174 | "outputs": [], 175 | "source": [ 176 | "showphi(initphi())" 177 | ] 178 | }, 179 | { 180 | "cell_type": "code", 181 | "execution_count": null, 182 | "metadata": {}, 183 | "outputs": [], 184 | "source": [ 185 | "def jacobi(array):\n", 186 | " # make a copy of the array to store new values\n", 187 | " updated = array.copy()\n", 188 | " \n", 189 | " # iterate only on the \"bulk\", using but not changing boundary values \n", 190 | " for i in range(1, n-1):\n", 191 | " for j in range(1, n-1):\n", 192 | " updated[i,j] = (array[i-1,j] + array[i+1,j] + array[i,j-1] + array[i,j+1]) / 4\n", 193 | " \n", 194 | " return updated" 195 | ] 196 | }, 197 | { 198 | "cell_type": "code", 199 | "execution_count": null, 200 | "metadata": {}, 201 | "outputs": [], 202 | "source": [ 203 | "showphi(jacobi(phi))" 204 | ] 205 | }, 206 | { 207 | "cell_type": "code", 208 | "execution_count": null, 209 | "metadata": {}, 210 | "outputs": [], 211 | "source": [ 212 | "%timeit jacobi(phi)" 213 | ] 214 | }, 215 | { 216 | "cell_type": "code", 217 | "execution_count": null, 218 | "metadata": {}, 219 | "outputs": [], 220 | "source": [ 221 | "phi[0:-2,1:-1] + phi[2:,1:-1]" 222 | ] 223 | }, 224 | { 225 | "cell_type": "code", 226 | "execution_count": null, 227 | "metadata": {}, 228 | "outputs": [], 229 | "source": [ 230 | "def matrixjacobi(array):\n", 231 | " updated = array.copy()\n", 232 | " \n", 233 | " updated[1:-1,1:-1] = (array[0:-2,1:-1] + array[2:,1:-1] + array[1:-1,0:-2] + array[1:-1,2:]) / 4\n", 234 | " \n", 235 | " return updated" 236 | ] 237 | }, 238 | { 239 | "cell_type": "code", 240 | "execution_count": null, 241 | "metadata": {}, 242 | "outputs": [], 243 | "source": [ 244 | "%timeit matrixjacobi(phi)" 245 | ] 246 | }, 247 | { 248 | "cell_type": "code", 249 | "execution_count": null, 250 | "metadata": {}, 251 | "outputs": [], 252 | "source": [ 253 | "def residual(array):\n", 254 | " laplace = array[0:-2,1:-1] + array[2:,1:-1] + array[1:-1,0:-2] + array[1:-1,2:] - 4*array[1:-1,1:-1]\n", 255 | " return np.mean(np.abs(laplace))" 256 | ] 257 | }, 258 | { 259 | "cell_type": "code", 260 | "execution_count": null, 261 | "metadata": {}, 262 | "outputs": [], 263 | "source": [ 264 | "pp.figure(figsize=(12,12))\n", 265 | "\n", 266 | "phi = initphi(64)\n", 267 | "\n", 268 | "# loop from 1 to 16 (subplot indexes from one)\n", 269 | "for i in range(1, 1+16):\n", 270 | " pp.subplot(4, 4, i)\n", 271 | " showphi(phi, colorbar=False)\n", 272 | " \n", 273 | " for j in range(32):\n", 274 | " phi = matrixjacobi(phi)\n", 275 | " \n", 276 | " meanres = residual(phi)\n", 277 | " pp.title(f'Iteration {i*32}: {meanres:.2e}')\n", 278 | " \n", 279 | "# save space among subplots\n", 280 | "pp.tight_layout()" 281 | ] 282 | } 283 | ], 284 | "metadata": { 285 | "kernelspec": { 286 | "display_name": "Python 3", 287 | "language": "python", 288 | "name": "python3" 289 | }, 290 | "language_info": { 291 | "codemirror_mode": { 292 | "name": "ipython", 293 | "version": 3 294 | }, 295 | "file_extension": ".py", 296 | "mimetype": "text/x-python", 297 | "name": "python", 298 | "nbconvert_exporter": "python", 299 | "pygments_lexer": "ipython3", 300 | "version": "3.8.8" 301 | }, 302 | "toc": { 303 | "base_numbering": 1, 304 | "nav_menu": {}, 305 | "number_sections": true, 306 | "sideBar": true, 307 | "skip_h1_title": false, 308 | "title_cell": "Table of Contents", 309 | "title_sidebar": "Contents", 310 | "toc_cell": false, 311 | "toc_position": {}, 312 | "toc_section_display": true, 313 | "toc_window_display": false 314 | } 315 | }, 316 | "nbformat": 4, 317 | "nbformat_minor": 4 318 | } 319 | -------------------------------------------------------------------------------- /Ch02/02_04_numpymatrix.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 02_04_numpymatrix.ipynb - Linear algebra and sparse matrices with NumPy and SciPy" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "import math\n", 17 | "\n", 18 | "import numpy as np\n", 19 | "import scipy.linalg as sl\n", 20 | "import scipy.sparse as ss\n", 21 | "import scipy.sparse.linalg as ssl\n", 22 | "import matplotlib.pyplot as pp" 23 | ] 24 | }, 25 | { 26 | "cell_type": "markdown", 27 | "metadata": {}, 28 | "source": [ 29 | "#### Code from last video" 30 | ] 31 | }, 32 | { 33 | "cell_type": "code", 34 | "execution_count": null, 35 | "metadata": {}, 36 | "outputs": [], 37 | "source": [ 38 | "def initphi(n=64):\n", 39 | " dx = 1/n\n", 40 | " xs = np.linspace(0.5*dx, 1-0.5*dx, n)\n", 41 | " \n", 42 | " phi = np.zeros((n,n), 'd')\n", 43 | " \n", 44 | " phi[:,-1] = np.sin(2 * math.pi * xs)\n", 45 | " phi[-1,:] = -np.sin(2 * math.pi * xs)\n", 46 | " \n", 47 | " return phi" 48 | ] 49 | }, 50 | { 51 | "cell_type": "code", 52 | "execution_count": null, 53 | "metadata": {}, 54 | "outputs": [], 55 | "source": [ 56 | "def showphi(array, colorbar=True):\n", 57 | " pp.imshow(array.T, origin='lower', extent=(0,1,0,1),\n", 58 | " vmin=-1, vmax=1, cmap='coolwarm')\n", 59 | " \n", 60 | " if colorbar:\n", 61 | " pp.colorbar()" 62 | ] 63 | }, 64 | { 65 | "cell_type": "markdown", 66 | "metadata": {}, 67 | "source": [ 68 | "#### Statement of the linear algebra problem" 69 | ] 70 | }, 71 | { 72 | "cell_type": "markdown", 73 | "metadata": {}, 74 | "source": [ 75 | "$$A_{ijkl} y_{kl} = b_{ij} \\quad \\text{(summation implied)}$$" 76 | ] 77 | }, 78 | { 79 | "cell_type": "markdown", 80 | "metadata": {}, 81 | "source": [ 82 | "$$\\biggl(\\frac{\\partial^2}{\\partial x^2} + \\frac{\\partial^2}{\\partial y^2}\\biggr) y_{kl} \\rightarrow\n", 83 | "\\bigl(y_{(k-1)l} + y_{(k+1)l} + y_{k(l-1)} + y_{k(l+1)} - 4y_{kl}\\bigr) / \\Delta x^2$$\n", 84 | "\n", 85 | "_In the bulk_:\n", 86 | "\n", 87 | "$$A_{ijkl} = 0 \\quad\\text{except for}\\quad A_{ij(i-1)j} = A_{ij(i+1)j} = A_{iji(j-1)} = A_{iji(j+1)} = (\\Delta x)^{-2}$$\n", 88 | "\n", 89 | "and\n", 90 | "\n", 91 | "$$A_{ijij} = -4 (\\Delta x)^{-2}$$\n", 92 | "\n", 93 | "_On the boundary_:\n", 94 | "\n", 95 | "$$A_{0j0j} = A_{(-1)j(-1)j} = A_{i0i0} = A_{i(-1)i(-1)} = 1.$$" 96 | ] 97 | }, 98 | { 99 | "cell_type": "markdown", 100 | "metadata": {}, 101 | "source": [ 102 | "#### Let's go!" 103 | ] 104 | }, 105 | { 106 | "cell_type": "code", 107 | "execution_count": null, 108 | "metadata": {}, 109 | "outputs": [], 110 | "source": [ 111 | "def laplacematrix(n):\n", 112 | " A = np.zeros((n,n,n,n), 'd')\n", 113 | "\n", 114 | " dx = 1/n\n", 115 | " \n", 116 | " for i in range(1,n-1):\n", 117 | " for j in range(1,n-1):\n", 118 | " A[i,j,i-1,j] = A[i,j,i+1,j] = A[i,j,i,j-1] = A[i,j,i,j+1] = 1 / dx**2\n", 119 | " A[i,j,i,j] = -4 / dx**2\n", 120 | "\n", 121 | " for i in range(0,n):\n", 122 | " A[0,i,0,i] = A[-1,i,-1,i] = A[i,0,i,0] = A[i,-1,i,-1] = 1\n", 123 | " \n", 124 | " return A" 125 | ] 126 | }, 127 | { 128 | "cell_type": "code", 129 | "execution_count": null, 130 | "metadata": {}, 131 | "outputs": [], 132 | "source": [ 133 | "n = 8\n", 134 | "A = laplacematrix(n).reshape((n*n,n*n))" 135 | ] 136 | }, 137 | { 138 | "cell_type": "code", 139 | "execution_count": null, 140 | "metadata": {}, 141 | "outputs": [], 142 | "source": [ 143 | "pp.matshow(A)" 144 | ] 145 | }, 146 | { 147 | "cell_type": "code", 148 | "execution_count": null, 149 | "metadata": {}, 150 | "outputs": [], 151 | "source": [ 152 | "n = 64\n", 153 | "A = laplacematrix(n).reshape((n*n,n*n))" 154 | ] 155 | }, 156 | { 157 | "cell_type": "code", 158 | "execution_count": null, 159 | "metadata": {}, 160 | "outputs": [], 161 | "source": [ 162 | "b = initphi(n).reshape((n*n),)" 163 | ] 164 | }, 165 | { 166 | "cell_type": "code", 167 | "execution_count": null, 168 | "metadata": {}, 169 | "outputs": [], 170 | "source": [ 171 | "%%time\n", 172 | "\n", 173 | "ysol = np.linalg.solve(A, b)" 174 | ] 175 | }, 176 | { 177 | "cell_type": "code", 178 | "execution_count": null, 179 | "metadata": {}, 180 | "outputs": [], 181 | "source": [ 182 | "showphi(ysol.reshape((n,n)))" 183 | ] 184 | }, 185 | { 186 | "cell_type": "code", 187 | "execution_count": null, 188 | "metadata": {}, 189 | "outputs": [], 190 | "source": [ 191 | "showphi( (np.dot(A, ysol) - b).reshape((n,n)) )" 192 | ] 193 | }, 194 | { 195 | "cell_type": "code", 196 | "execution_count": null, 197 | "metadata": {}, 198 | "outputs": [], 199 | "source": [ 200 | "A @ ysol - b" 201 | ] 202 | }, 203 | { 204 | "cell_type": "code", 205 | "execution_count": null, 206 | "metadata": {}, 207 | "outputs": [], 208 | "source": [ 209 | "np.max(np.abs(A @ ysol - b))" 210 | ] 211 | }, 212 | { 213 | "cell_type": "code", 214 | "execution_count": null, 215 | "metadata": { 216 | "scrolled": true 217 | }, 218 | "outputs": [], 219 | "source": [ 220 | "help(sl)" 221 | ] 222 | }, 223 | { 224 | "cell_type": "code", 225 | "execution_count": null, 226 | "metadata": {}, 227 | "outputs": [], 228 | "source": [ 229 | "A_s = ss.csc_matrix(A)" 230 | ] 231 | }, 232 | { 233 | "cell_type": "code", 234 | "execution_count": null, 235 | "metadata": {}, 236 | "outputs": [], 237 | "source": [ 238 | "A_s" 239 | ] 240 | }, 241 | { 242 | "cell_type": "code", 243 | "execution_count": null, 244 | "metadata": {}, 245 | "outputs": [], 246 | "source": [ 247 | "b_s = ss.csc_matrix(b)" 248 | ] 249 | }, 250 | { 251 | "cell_type": "code", 252 | "execution_count": null, 253 | "metadata": {}, 254 | "outputs": [], 255 | "source": [ 256 | "%time\n", 257 | "ysol_s = ss.linalg.spsolve(A_s, b_s)" 258 | ] 259 | }, 260 | { 261 | "cell_type": "code", 262 | "execution_count": null, 263 | "metadata": {}, 264 | "outputs": [], 265 | "source": [ 266 | "b_s = ss.csc_matrix(b.reshape((n*n,1)))" 267 | ] 268 | }, 269 | { 270 | "cell_type": "code", 271 | "execution_count": null, 272 | "metadata": {}, 273 | "outputs": [], 274 | "source": [ 275 | "%time\n", 276 | "ysol_s = ssl.spsolve(A_s, b_s)" 277 | ] 278 | }, 279 | { 280 | "cell_type": "code", 281 | "execution_count": null, 282 | "metadata": {}, 283 | "outputs": [], 284 | "source": [ 285 | "showphi(ysol_s.reshape((n,n)))" 286 | ] 287 | } 288 | ], 289 | "metadata": { 290 | "kernelspec": { 291 | "display_name": "Python 3", 292 | "language": "python", 293 | "name": "python3" 294 | }, 295 | "language_info": { 296 | "codemirror_mode": { 297 | "name": "ipython", 298 | "version": 3 299 | }, 300 | "file_extension": ".py", 301 | "mimetype": "text/x-python", 302 | "name": "python", 303 | "nbconvert_exporter": "python", 304 | "pygments_lexer": "ipython3", 305 | "version": "3.8.8" 306 | }, 307 | "toc": { 308 | "base_numbering": 1, 309 | "nav_menu": {}, 310 | "number_sections": true, 311 | "sideBar": true, 312 | "skip_h1_title": false, 313 | "title_cell": "Table of Contents", 314 | "title_sidebar": "Contents", 315 | "toc_cell": false, 316 | "toc_position": {}, 317 | "toc_section_display": true, 318 | "toc_window_display": false 319 | } 320 | }, 321 | "nbformat": 4, 322 | "nbformat_minor": 4 323 | } 324 | -------------------------------------------------------------------------------- /Ch02/02_05_codegeneration.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 02_05_codegeneration.ipynb - Code generation with Numba and Cython" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "**Problem: perform the integral**\n", 15 | "\n", 16 | "$$\\int_0^\\pi \\left[ \\sum_{k=1}^{\\infty} \\frac{\\cos(k \\sin \\theta)}{k^2} \\right] d\\theta$$" 17 | ] 18 | }, 19 | { 20 | "cell_type": "code", 21 | "execution_count": null, 22 | "metadata": {}, 23 | "outputs": [], 24 | "source": [ 25 | "import math\n", 26 | "import numpy as np\n", 27 | "import scipy\n", 28 | "import scipy.integrate as si\n", 29 | "import numba" 30 | ] 31 | }, 32 | { 33 | "cell_type": "code", 34 | "execution_count": null, 35 | "metadata": {}, 36 | "outputs": [], 37 | "source": [ 38 | "def integrand(theta):\n", 39 | " return sum(math.cos(k * math.sin(theta))/k**2 for k in range(1, 200))" 40 | ] 41 | }, 42 | { 43 | "cell_type": "code", 44 | "execution_count": null, 45 | "metadata": {}, 46 | "outputs": [], 47 | "source": [ 48 | "%time si.quad(integrand, 0, math.pi)" 49 | ] 50 | }, 51 | { 52 | "cell_type": "code", 53 | "execution_count": null, 54 | "metadata": {}, 55 | "outputs": [], 56 | "source": [ 57 | "@numba.jit\n", 58 | "def integrand_nj(theta):\n", 59 | " return sum(math.cos(k * math.sin(theta))/k**2 for k in range(1, 200))" 60 | ] 61 | }, 62 | { 63 | "cell_type": "code", 64 | "execution_count": null, 65 | "metadata": {}, 66 | "outputs": [], 67 | "source": [ 68 | "integrand_nj(1)" 69 | ] 70 | }, 71 | { 72 | "cell_type": "code", 73 | "execution_count": null, 74 | "metadata": {}, 75 | "outputs": [], 76 | "source": [ 77 | "@numba.jit\n", 78 | "def integrand_nj(theta):\n", 79 | " mysum = 0\n", 80 | " \n", 81 | " for k in range(1, 200):\n", 82 | " mysum = mysum + math.cos(k * math.sin(theta)) / k**2\n", 83 | " \n", 84 | " return mysum" 85 | ] 86 | }, 87 | { 88 | "cell_type": "code", 89 | "execution_count": null, 90 | "metadata": {}, 91 | "outputs": [], 92 | "source": [ 93 | "integrand_nj(1)" 94 | ] 95 | }, 96 | { 97 | "cell_type": "code", 98 | "execution_count": null, 99 | "metadata": {}, 100 | "outputs": [], 101 | "source": [ 102 | "si.quad(integrand_nj, 0, math.pi)" 103 | ] 104 | }, 105 | { 106 | "cell_type": "code", 107 | "execution_count": null, 108 | "metadata": {}, 109 | "outputs": [], 110 | "source": [ 111 | "%timeit si.quad(integrand_nj, 0, math.pi)" 112 | ] 113 | }, 114 | { 115 | "cell_type": "code", 116 | "execution_count": null, 117 | "metadata": {}, 118 | "outputs": [], 119 | "source": [ 120 | "%load_ext cython" 121 | ] 122 | }, 123 | { 124 | "cell_type": "code", 125 | "execution_count": null, 126 | "metadata": {}, 127 | "outputs": [], 128 | "source": [ 129 | "%%cython\n", 130 | "\n", 131 | "# import trigonometric functions from the standard C library\n", 132 | "from libc.math cimport sin, cos\n", 133 | "\n", 134 | "def integrand_cc(double theta):\n", 135 | " cdef double mysum = 0.0\n", 136 | " cdef int k\n", 137 | " \n", 138 | " for k in range(1, 200):\n", 139 | " mysum = mysum + cos(k * sin(theta)) / k**2\n", 140 | " \n", 141 | " return mysum" 142 | ] 143 | }, 144 | { 145 | "cell_type": "code", 146 | "execution_count": null, 147 | "metadata": {}, 148 | "outputs": [], 149 | "source": [ 150 | "integrand_cc(1)" 151 | ] 152 | }, 153 | { 154 | "cell_type": "code", 155 | "execution_count": null, 156 | "metadata": {}, 157 | "outputs": [], 158 | "source": [ 159 | "si.quad(integrand_cc, 0, math.pi)" 160 | ] 161 | }, 162 | { 163 | "cell_type": "code", 164 | "execution_count": null, 165 | "metadata": {}, 166 | "outputs": [], 167 | "source": [ 168 | "%timeit si.quad(integrand_cc, 0, math.pi)" 169 | ] 170 | }, 171 | { 172 | "cell_type": "code", 173 | "execution_count": null, 174 | "metadata": {}, 175 | "outputs": [], 176 | "source": [ 177 | "def jacobi(array): \n", 178 | " updated = array.copy()\n", 179 | " \n", 180 | " for i in range(1, array.shape[0]-1):\n", 181 | " for j in range(1, array.shape[1]-1):\n", 182 | " updated[i,j] = (array[i-1,j] + array[i+1,j] + array[i,j-1] + array[i,j+1]) / 4\n", 183 | " \n", 184 | " return updated" 185 | ] 186 | }, 187 | { 188 | "cell_type": "code", 189 | "execution_count": null, 190 | "metadata": {}, 191 | "outputs": [], 192 | "source": [ 193 | "phi = np.random.randn(64,64)" 194 | ] 195 | }, 196 | { 197 | "cell_type": "code", 198 | "execution_count": null, 199 | "metadata": {}, 200 | "outputs": [], 201 | "source": [ 202 | "%timeit jacobi(phi)" 203 | ] 204 | }, 205 | { 206 | "cell_type": "code", 207 | "execution_count": null, 208 | "metadata": {}, 209 | "outputs": [], 210 | "source": [ 211 | "@numba.jit\n", 212 | "def jacobi_numba(array): \n", 213 | " updated = array.copy()\n", 214 | " \n", 215 | " for i in range(1, array.shape[0]-1):\n", 216 | " for j in range(1, array.shape[1]-1):\n", 217 | " updated[i,j] = (array[i-1,j] + array[i+1,j] + array[i,j-1] + array[i,j+1]) / 4\n", 218 | " \n", 219 | " return updated" 220 | ] 221 | }, 222 | { 223 | "cell_type": "code", 224 | "execution_count": null, 225 | "metadata": {}, 226 | "outputs": [], 227 | "source": [ 228 | "%timeit jacobi_numba(phi)" 229 | ] 230 | }, 231 | { 232 | "cell_type": "markdown", 233 | "metadata": {}, 234 | "source": [ 235 | "#### Code generation for `scipy` applications—the case of multiple parameters" 236 | ] 237 | }, 238 | { 239 | "cell_type": "markdown", 240 | "metadata": {}, 241 | "source": [ 242 | "We'll perform the parametrized definite integral" 243 | ] 244 | }, 245 | { 246 | "cell_type": "markdown", 247 | "metadata": {}, 248 | "source": [ 249 | "$$I(z) = \\int_0^\\pi \\cos(z \\sin \\theta) d\\theta$$" 250 | ] 251 | }, 252 | { 253 | "cell_type": "markdown", 254 | "metadata": {}, 255 | "source": [ 256 | "With Numba, we need to use a more specialized decorator than the simple `numba.jit`, and we need to take all parameters as a C array of double-precision floats. The C function takes a first argument of the number of parameters, and a second argument of a pointer to the array." 257 | ] 258 | }, 259 | { 260 | "cell_type": "code", 261 | "execution_count": null, 262 | "metadata": {}, 263 | "outputs": [], 264 | "source": [ 265 | "# numba will generate a function with C-like calling interface (\"cfunc\")\n", 266 | "# that takes a 32-bit integer and a pointer to an array of 64-bit floats,\n", 267 | "# and returns a single float\n", 268 | "\n", 269 | "@numba.cfunc(\"float64(int32,CPointer(float64))\")\n", 270 | "def integrand_nc(n, x):\n", 271 | " # unpack the array, Python-style\n", 272 | " theta, z = x[0], x[1]\n", 273 | " \n", 274 | " return math.cos(z * math.sin(theta))" 275 | ] 276 | }, 277 | { 278 | "cell_type": "markdown", 279 | "metadata": {}, 280 | "source": [ 281 | "`scipy.integrate.quad` also needs some help to understand what arguments it's being given. That help is provided by `scipy.LowLevelCallable`, which can take several descriptions of C-like functions. Note that we provide the value of additional parameters (here $z$) as a tuple with the keyword argument `args`." 282 | ] 283 | }, 284 | { 285 | "cell_type": "code", 286 | "execution_count": null, 287 | "metadata": {}, 288 | "outputs": [], 289 | "source": [ 290 | "si.quad(scipy.LowLevelCallable(integrand_nc.ctypes), 0, math.pi, args=(5,))" 291 | ] 292 | }, 293 | { 294 | "cell_type": "markdown", 295 | "metadata": {}, 296 | "source": [ 297 | "With Cython, we cannot work entirely within the notebook as we did before, but we need to write a Cython header and a Cython source file that will be compiled to a C extension that we can import and use. Note the use of the iPython magic `%%file` to write the content of the cell to a file." 298 | ] 299 | }, 300 | { 301 | "cell_type": "code", 302 | "execution_count": null, 303 | "metadata": {}, 304 | "outputs": [], 305 | "source": [ 306 | "%%file integrand.pxd\n", 307 | "\n", 308 | "# a quasi-C declaration of our Cython function; note \"cdef\"\n", 309 | "cdef double integrand_cc(int n, double[] x)" 310 | ] 311 | }, 312 | { 313 | "cell_type": "code", 314 | "execution_count": null, 315 | "metadata": {}, 316 | "outputs": [], 317 | "source": [ 318 | "%%file integrand.pyx\n", 319 | "\n", 320 | "# \"cimport\" gives us access to functions in the C standard library\n", 321 | "from libc.math cimport sin, cos\n", 322 | "\n", 323 | "# \"cdef\" creates a function callable from C only\n", 324 | "# (while def in the %%cython block above, creates a Python callable)\n", 325 | "cdef double integrand_cc(int n, double x[]):\n", 326 | " return cos(x[1] * sin(x[0]))" 327 | ] 328 | }, 329 | { 330 | "cell_type": "markdown", 331 | "metadata": {}, 332 | "source": [ 333 | "We can take advantage of the `pyximport` module, which takes care of compiling the extension transparently. Note that C extensions can only be imported once, so modifying the code, recompiling it with the same name, and reimporting it would have no effect. I have wasted lots of debugging code this way!" 334 | ] 335 | }, 336 | { 337 | "cell_type": "code", 338 | "execution_count": null, 339 | "metadata": {}, 340 | "outputs": [], 341 | "source": [ 342 | "import pyximport\n", 343 | "pyximport.install(language_level=3) # Python 3 of course" 344 | ] 345 | }, 346 | { 347 | "cell_type": "code", 348 | "execution_count": null, 349 | "metadata": {}, 350 | "outputs": [], 351 | "source": [ 352 | "import integrand" 353 | ] 354 | }, 355 | { 356 | "cell_type": "markdown", 357 | "metadata": {}, 358 | "source": [ 359 | "And again we need some work to dig out and wrap the C-like function we're calling." 360 | ] 361 | }, 362 | { 363 | "cell_type": "code", 364 | "execution_count": null, 365 | "metadata": {}, 366 | "outputs": [], 367 | "source": [ 368 | "si.quad(scipy.LowLevelCallable(integrand.__pyx_capi__['integrand_cc']), 0, math.pi, args=(5,))" 369 | ] 370 | }, 371 | { 372 | "cell_type": "markdown", 373 | "metadata": {}, 374 | "source": [ 375 | "That's it!" 376 | ] 377 | } 378 | ], 379 | "metadata": { 380 | "kernelspec": { 381 | "display_name": "Python 3", 382 | "language": "python", 383 | "name": "python3" 384 | }, 385 | "language_info": { 386 | "codemirror_mode": { 387 | "name": "ipython", 388 | "version": 3 389 | }, 390 | "file_extension": ".py", 391 | "mimetype": "text/x-python", 392 | "name": "python", 393 | "nbconvert_exporter": "python", 394 | "pygments_lexer": "ipython3", 395 | "version": "3.8.8" 396 | }, 397 | "toc": { 398 | "base_numbering": 1, 399 | "nav_menu": {}, 400 | "number_sections": true, 401 | "sideBar": true, 402 | "skip_h1_title": false, 403 | "title_cell": "Table of Contents", 404 | "title_sidebar": "Contents", 405 | "toc_cell": false, 406 | "toc_position": {}, 407 | "toc_section_display": true, 408 | "toc_window_display": false 409 | } 410 | }, 411 | "nbformat": 4, 412 | "nbformat_minor": 4 413 | } 414 | -------------------------------------------------------------------------------- /Ch02/02_06_legacywrap.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 02_06_legacywrap.ipynb - Wrapping legacy code with Cython, CFFI, and F2PY" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "import math\n", 17 | "import numpy as np\n", 18 | "import matplotlib.pyplot as pp" 19 | ] 20 | }, 21 | { 22 | "cell_type": "markdown", 23 | "metadata": {}, 24 | "source": [ 25 | "#### Code from 02_03_numpycompute.ipynb" 26 | ] 27 | }, 28 | { 29 | "cell_type": "code", 30 | "execution_count": null, 31 | "metadata": {}, 32 | "outputs": [], 33 | "source": [ 34 | "def initphi(n=64):\n", 35 | " dx = 1/n\n", 36 | " xs = np.linspace(0.5*dx, 1-0.5*dx, n)\n", 37 | " \n", 38 | " phi = np.zeros((n,n), 'd')\n", 39 | " \n", 40 | " phi[:,-1] = np.sin(2 * math.pi * xs)\n", 41 | " phi[-1,:] = -np.sin(2 * math.pi * xs)\n", 42 | " \n", 43 | " return phi" 44 | ] 45 | }, 46 | { 47 | "cell_type": "code", 48 | "execution_count": null, 49 | "metadata": {}, 50 | "outputs": [], 51 | "source": [ 52 | "def showphi(array, colorbar=True):\n", 53 | " pp.imshow(array.T, origin='lower', extent=(0,1,0,1),\n", 54 | " vmin=-1, vmax=1, cmap='coolwarm')\n", 55 | " \n", 56 | " if colorbar:\n", 57 | " pp.colorbar()" 58 | ] 59 | }, 60 | { 61 | "cell_type": "markdown", 62 | "metadata": {}, 63 | "source": [ 64 | "#### Wrapping C with Cython" 65 | ] 66 | }, 67 | { 68 | "cell_type": "code", 69 | "execution_count": null, 70 | "metadata": {}, 71 | "outputs": [], 72 | "source": [ 73 | "%%file gauss_iterate.c\n", 74 | "\n", 75 | "#define A(i,j) (array[(i)*nx + (j)])\n", 76 | "\n", 77 | "void gauss_iterate(int nx, int ny, double *array, int iterations) {\n", 78 | " for(int k=0; k" 81 | ] 82 | }, 83 | "metadata": { 84 | "needs_background": "light" 85 | }, 86 | "output_type": "display_data" 87 | } 88 | ], 89 | "source": [ 90 | "pp.figure(figsize=(6,2))\n", 91 | "pp.plot(xs, field)\n", 92 | "pp.axis(xmin=0,xmax=1);" 93 | ] 94 | }, 95 | { 96 | "cell_type": "code", 97 | "execution_count": null, 98 | "metadata": {}, 99 | "outputs": [], 100 | "source": [] 101 | } 102 | ], 103 | "metadata": { 104 | "kernelspec": { 105 | "display_name": "Python 3", 106 | "language": "python", 107 | "name": "python3" 108 | }, 109 | "language_info": { 110 | "codemirror_mode": { 111 | "name": "ipython", 112 | "version": 3 113 | }, 114 | "file_extension": ".py", 115 | "mimetype": "text/x-python", 116 | "name": "python", 117 | "nbconvert_exporter": "python", 118 | "pygments_lexer": "ipython3", 119 | "version": "3.8.8" 120 | }, 121 | "toc": { 122 | "base_numbering": 1, 123 | "nav_menu": {}, 124 | "number_sections": true, 125 | "sideBar": true, 126 | "skip_h1_title": false, 127 | "title_cell": "Table of Contents", 128 | "title_sidebar": "Contents", 129 | "toc_cell": false, 130 | "toc_position": {}, 131 | "toc_section_display": true, 132 | "toc_window_display": false 133 | } 134 | }, 135 | "nbformat": 4, 136 | "nbformat_minor": 4 137 | } 138 | -------------------------------------------------------------------------------- /Ch02/02_07_challenge.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 02_07_challenge.ipynb - Diffusion equation" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "import math\n", 17 | "\n", 18 | "import numpy as np\n", 19 | "import matplotlib.pyplot as pp" 20 | ] 21 | }, 22 | { 23 | "cell_type": "code", 24 | "execution_count": null, 25 | "metadata": {}, 26 | "outputs": [], 27 | "source": [ 28 | "n = 128" 29 | ] 30 | }, 31 | { 32 | "cell_type": "code", 33 | "execution_count": null, 34 | "metadata": {}, 35 | "outputs": [], 36 | "source": [ 37 | "dx = 1/n" 38 | ] 39 | }, 40 | { 41 | "cell_type": "code", 42 | "execution_count": null, 43 | "metadata": {}, 44 | "outputs": [], 45 | "source": [ 46 | "xs = np.linspace(0.5*dx, 1-0.5*dx, n)" 47 | ] 48 | }, 49 | { 50 | "cell_type": "code", 51 | "execution_count": null, 52 | "metadata": {}, 53 | "outputs": [], 54 | "source": [ 55 | "def initfield():\n", 56 | " array = np.sin(4 * math.pi * xs) + np.sin(9 * math.pi * xs)\n", 57 | " array[0] = array[-1] = 0\n", 58 | " \n", 59 | " return array" 60 | ] 61 | }, 62 | { 63 | "cell_type": "code", 64 | "execution_count": null, 65 | "metadata": {}, 66 | "outputs": [], 67 | "source": [ 68 | "field = initfield()" 69 | ] 70 | }, 71 | { 72 | "cell_type": "code", 73 | "execution_count": null, 74 | "metadata": {}, 75 | "outputs": [], 76 | "source": [ 77 | "pp.figure(figsize=(6,2))\n", 78 | "pp.plot(xs, field)\n", 79 | "pp.axis(xmin=0,xmax=1);" 80 | ] 81 | }, 82 | { 83 | "cell_type": "code", 84 | "execution_count": null, 85 | "metadata": {}, 86 | "outputs": [], 87 | "source": [] 88 | } 89 | ], 90 | "metadata": { 91 | "kernelspec": { 92 | "display_name": "Python 3", 93 | "language": "python", 94 | "name": "python3" 95 | }, 96 | "language_info": { 97 | "codemirror_mode": { 98 | "name": "ipython", 99 | "version": 3 100 | }, 101 | "file_extension": ".py", 102 | "mimetype": "text/x-python", 103 | "name": "python", 104 | "nbconvert_exporter": "python", 105 | "pygments_lexer": "ipython3", 106 | "version": "3.8.8" 107 | }, 108 | "toc": { 109 | "base_numbering": 1, 110 | "nav_menu": {}, 111 | "number_sections": true, 112 | "sideBar": true, 113 | "skip_h1_title": false, 114 | "title_cell": "Table of Contents", 115 | "title_sidebar": "Contents", 116 | "toc_cell": false, 117 | "toc_position": {}, 118 | "toc_section_display": true, 119 | "toc_window_display": false 120 | } 121 | }, 122 | "nbformat": 4, 123 | "nbformat_minor": 4 124 | } 125 | -------------------------------------------------------------------------------- /Ch02/02_08_solution.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 02_08_solution.ipynb - Diffusion equation" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "import math\n", 17 | "\n", 18 | "import numpy as np\n", 19 | "import matplotlib.pyplot as pp" 20 | ] 21 | }, 22 | { 23 | "cell_type": "code", 24 | "execution_count": null, 25 | "metadata": {}, 26 | "outputs": [], 27 | "source": [ 28 | "n = 128" 29 | ] 30 | }, 31 | { 32 | "cell_type": "code", 33 | "execution_count": null, 34 | "metadata": {}, 35 | "outputs": [], 36 | "source": [ 37 | "dx = 1/n" 38 | ] 39 | }, 40 | { 41 | "cell_type": "code", 42 | "execution_count": null, 43 | "metadata": {}, 44 | "outputs": [], 45 | "source": [ 46 | "xs = np.linspace(0.5*dx, 1-0.5*dx, n)" 47 | ] 48 | }, 49 | { 50 | "cell_type": "code", 51 | "execution_count": null, 52 | "metadata": {}, 53 | "outputs": [], 54 | "source": [ 55 | "def initfield():\n", 56 | " array = np.sin(4 * math.pi * xs) + np.sin(9 * math.pi * xs)\n", 57 | " array[0] = array[-1] = 0\n", 58 | " \n", 59 | " return array" 60 | ] 61 | }, 62 | { 63 | "cell_type": "code", 64 | "execution_count": null, 65 | "metadata": {}, 66 | "outputs": [], 67 | "source": [ 68 | "field = initfield()" 69 | ] 70 | }, 71 | { 72 | "cell_type": "code", 73 | "execution_count": null, 74 | "metadata": {}, 75 | "outputs": [], 76 | "source": [ 77 | "pp.figure(figsize=(6,2))\n", 78 | "pp.plot(xs, field)\n", 79 | "pp.axis(xmin=0,xmax=1);" 80 | ] 81 | }, 82 | { 83 | "cell_type": "markdown", 84 | "metadata": {}, 85 | "source": [ 86 | "#### Solving the equation" 87 | ] 88 | }, 89 | { 90 | "cell_type": "code", 91 | "execution_count": null, 92 | "metadata": {}, 93 | "outputs": [], 94 | "source": [ 95 | "def laplacian(array):\n", 96 | " ret = array.copy() \n", 97 | " ret[1:-1] = (array[2:] - 2*array[1:-1] + array[0:-2]) / dx**2\n", 98 | " \n", 99 | " return ret" 100 | ] 101 | }, 102 | { 103 | "cell_type": "code", 104 | "execution_count": null, 105 | "metadata": {}, 106 | "outputs": [], 107 | "source": [ 108 | "def evolve(array, dt):\n", 109 | " ret = array.copy()\n", 110 | " ret[1:-1] = ret[1:-1] + dt * laplacian(array)[1:-1]\n", 111 | " \n", 112 | " return ret" 113 | ] 114 | }, 115 | { 116 | "cell_type": "code", 117 | "execution_count": null, 118 | "metadata": {}, 119 | "outputs": [], 120 | "source": [ 121 | "dt = dx**2/2\n", 122 | "nsteps = 2000" 123 | ] 124 | }, 125 | { 126 | "cell_type": "code", 127 | "execution_count": null, 128 | "metadata": {}, 129 | "outputs": [], 130 | "source": [ 131 | "solution = []\n", 132 | "\n", 133 | "for i in range(nsteps):\n", 134 | " solution.append(field)\n", 135 | " field = evolve(field, dt)\n", 136 | " \n", 137 | "solution = np.array(solution)" 138 | ] 139 | }, 140 | { 141 | "cell_type": "code", 142 | "execution_count": null, 143 | "metadata": {}, 144 | "outputs": [], 145 | "source": [ 146 | "pp.imshow(solution.T, extent=[0,dt*nsteps,0,1], vmin=-1, vmax=1)\n", 147 | "pp.colorbar()\n", 148 | "pp.axis('auto');" 149 | ] 150 | }, 151 | { 152 | "cell_type": "code", 153 | "execution_count": null, 154 | "metadata": {}, 155 | "outputs": [], 156 | "source": [ 157 | "pp.figure(figsize=(6,2))\n", 158 | "pp.plot(xs, solution[0,:])\n", 159 | "pp.plot(xs, solution[-1,:])\n", 160 | "pp.axis(xmin=0, xmax=1)" 161 | ] 162 | }, 163 | { 164 | "cell_type": "code", 165 | "execution_count": null, 166 | "metadata": {}, 167 | "outputs": [], 168 | "source": [] 169 | } 170 | ], 171 | "metadata": { 172 | "kernelspec": { 173 | "display_name": "Python 3", 174 | "language": "python", 175 | "name": "python3" 176 | }, 177 | "language_info": { 178 | "codemirror_mode": { 179 | "name": "ipython", 180 | "version": 3 181 | }, 182 | "file_extension": ".py", 183 | "mimetype": "text/x-python", 184 | "name": "python", 185 | "nbconvert_exporter": "python", 186 | "pygments_lexer": "ipython3", 187 | "version": "3.8.8" 188 | }, 189 | "toc": { 190 | "base_numbering": 1, 191 | "nav_menu": {}, 192 | "number_sections": true, 193 | "sideBar": true, 194 | "skip_h1_title": false, 195 | "title_cell": "Table of Contents", 196 | "title_sidebar": "Contents", 197 | "toc_cell": false, 198 | "toc_position": {}, 199 | "toc_section_display": true, 200 | "toc_window_display": false 201 | } 202 | }, 203 | "nbformat": 4, 204 | "nbformat_minor": 4 205 | } 206 | -------------------------------------------------------------------------------- /Ch02/image.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkedInLearning/python-for-engineers-and-scientists-2425360/bf844b890dd42913910ed81abe2ddd2846801117/Ch02/image.npy -------------------------------------------------------------------------------- /Ch03/03_02_sympy.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 03_02_sympy.ipynb - Symbolic computation with SymPy" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "import sympy" 17 | ] 18 | }, 19 | { 20 | "cell_type": "code", 21 | "execution_count": null, 22 | "metadata": {}, 23 | "outputs": [], 24 | "source": [ 25 | "1/3" 26 | ] 27 | }, 28 | { 29 | "cell_type": "code", 30 | "execution_count": null, 31 | "metadata": {}, 32 | "outputs": [], 33 | "source": [ 34 | "sympy.S('1/3')" 35 | ] 36 | }, 37 | { 38 | "cell_type": "code", 39 | "execution_count": null, 40 | "metadata": {}, 41 | "outputs": [], 42 | "source": [ 43 | "type(sympy.S('1/3'))" 44 | ] 45 | }, 46 | { 47 | "cell_type": "code", 48 | "execution_count": null, 49 | "metadata": {}, 50 | "outputs": [], 51 | "source": [ 52 | "1 / sympy.S('3')" 53 | ] 54 | }, 55 | { 56 | "cell_type": "code", 57 | "execution_count": null, 58 | "metadata": {}, 59 | "outputs": [], 60 | "source": [ 61 | "sympy.pi" 62 | ] 63 | }, 64 | { 65 | "cell_type": "code", 66 | "execution_count": null, 67 | "metadata": {}, 68 | "outputs": [], 69 | "source": [ 70 | "sympy.E" 71 | ] 72 | }, 73 | { 74 | "cell_type": "code", 75 | "execution_count": null, 76 | "metadata": {}, 77 | "outputs": [], 78 | "source": [ 79 | "print(sympy.pi.n(1000)) # the first 1000 digits of pi" 80 | ] 81 | }, 82 | { 83 | "cell_type": "code", 84 | "execution_count": null, 85 | "metadata": {}, 86 | "outputs": [], 87 | "source": [ 88 | "x = sympy.Symbol('x')" 89 | ] 90 | }, 91 | { 92 | "cell_type": "code", 93 | "execution_count": null, 94 | "metadata": {}, 95 | "outputs": [], 96 | "source": [ 97 | "x" 98 | ] 99 | }, 100 | { 101 | "cell_type": "code", 102 | "execution_count": null, 103 | "metadata": {}, 104 | "outputs": [], 105 | "source": [ 106 | "type(x)" 107 | ] 108 | }, 109 | { 110 | "cell_type": "code", 111 | "execution_count": null, 112 | "metadata": {}, 113 | "outputs": [], 114 | "source": [ 115 | "x**2 - 2" 116 | ] 117 | }, 118 | { 119 | "cell_type": "code", 120 | "execution_count": null, 121 | "metadata": {}, 122 | "outputs": [], 123 | "source": [ 124 | "z**2 + 2" 125 | ] 126 | }, 127 | { 128 | "cell_type": "code", 129 | "execution_count": null, 130 | "metadata": {}, 131 | "outputs": [], 132 | "source": [ 133 | "(x**2 + 2*x + 1)/(x + 1)" 134 | ] 135 | }, 136 | { 137 | "cell_type": "code", 138 | "execution_count": null, 139 | "metadata": {}, 140 | "outputs": [], 141 | "source": [ 142 | "sympy.simplify(_)" 143 | ] 144 | }, 145 | { 146 | "cell_type": "code", 147 | "execution_count": null, 148 | "metadata": {}, 149 | "outputs": [], 150 | "source": [ 151 | "from sympy import sin, cos, exp, log" 152 | ] 153 | }, 154 | { 155 | "cell_type": "code", 156 | "execution_count": null, 157 | "metadata": {}, 158 | "outputs": [], 159 | "source": [ 160 | "sympy.simplify(cos(x)**2 - sin(x)**2)" 161 | ] 162 | }, 163 | { 164 | "cell_type": "code", 165 | "execution_count": null, 166 | "metadata": {}, 167 | "outputs": [], 168 | "source": [ 169 | "x**6 - 4*x**5 + x**3 - 8*x**2 + 18*x - 8" 170 | ] 171 | }, 172 | { 173 | "cell_type": "code", 174 | "execution_count": null, 175 | "metadata": {}, 176 | "outputs": [], 177 | "source": [ 178 | "sympy.factor(_) # _ is the result of the last evaluation" 179 | ] 180 | }, 181 | { 182 | "cell_type": "code", 183 | "execution_count": null, 184 | "metadata": {}, 185 | "outputs": [], 186 | "source": [ 187 | "_.expand()" 188 | ] 189 | }, 190 | { 191 | "cell_type": "code", 192 | "execution_count": null, 193 | "metadata": {}, 194 | "outputs": [], 195 | "source": [ 196 | "sympy.expand_trig(cos(2*x))" 197 | ] 198 | }, 199 | { 200 | "cell_type": "code", 201 | "execution_count": null, 202 | "metadata": {}, 203 | "outputs": [], 204 | "source": [ 205 | "a, b = sympy.symbols('a,b')" 206 | ] 207 | }, 208 | { 209 | "cell_type": "code", 210 | "execution_count": null, 211 | "metadata": {}, 212 | "outputs": [], 213 | "source": [ 214 | "a/(1+a) - b/(1+b)" 215 | ] 216 | }, 217 | { 218 | "cell_type": "code", 219 | "execution_count": null, 220 | "metadata": {}, 221 | "outputs": [], 222 | "source": [ 223 | "_.together()" 224 | ] 225 | }, 226 | { 227 | "cell_type": "code", 228 | "execution_count": null, 229 | "metadata": {}, 230 | "outputs": [], 231 | "source": [ 232 | "2 * a * x**2 + x**2 * sympy.cos(x) + (a + 1 + sympy.cos(2*x))*x" 233 | ] 234 | }, 235 | { 236 | "cell_type": "code", 237 | "execution_count": null, 238 | "metadata": {}, 239 | "outputs": [], 240 | "source": [ 241 | "_.collect(x)" 242 | ] 243 | }, 244 | { 245 | "cell_type": "code", 246 | "execution_count": null, 247 | "metadata": {}, 248 | "outputs": [], 249 | "source": [ 250 | "_.coeff(x)" 251 | ] 252 | }, 253 | { 254 | "cell_type": "code", 255 | "execution_count": null, 256 | "metadata": {}, 257 | "outputs": [], 258 | "source": [ 259 | "(x**3 + 2*x**2 + 1).subs({x: 2*(a+1)})" 260 | ] 261 | }, 262 | { 263 | "cell_type": "code", 264 | "execution_count": null, 265 | "metadata": {}, 266 | "outputs": [], 267 | "source": [ 268 | "_.simplify()" 269 | ] 270 | }, 271 | { 272 | "cell_type": "code", 273 | "execution_count": null, 274 | "metadata": {}, 275 | "outputs": [], 276 | "source": [ 277 | "_.expand()" 278 | ] 279 | }, 280 | { 281 | "cell_type": "code", 282 | "execution_count": null, 283 | "metadata": {}, 284 | "outputs": [], 285 | "source": [ 286 | "2*cos(2*a)" 287 | ] 288 | }, 289 | { 290 | "cell_type": "code", 291 | "execution_count": null, 292 | "metadata": {}, 293 | "outputs": [], 294 | "source": [ 295 | "_.rewrite(exp)" 296 | ] 297 | }, 298 | { 299 | "cell_type": "code", 300 | "execution_count": null, 301 | "metadata": {}, 302 | "outputs": [], 303 | "source": [ 304 | "_.simplify()" 305 | ] 306 | }, 307 | { 308 | "cell_type": "markdown", 309 | "metadata": {}, 310 | "source": [ 311 | "$$2 a \\cos(x) - 2 b \\sin(x) = 0$$" 312 | ] 313 | }, 314 | { 315 | "cell_type": "code", 316 | "execution_count": null, 317 | "metadata": {}, 318 | "outputs": [], 319 | "source": [ 320 | "sol = sympy.solve(2*a*sympy.cos(x) - 2*b*sympy.sin(x), x)\n", 321 | "sol" 322 | ] 323 | }, 324 | { 325 | "cell_type": "markdown", 326 | "metadata": {}, 327 | "source": [ 328 | "$$\\left\\{ \\begin{array}{c} 2 a + 1 = 0 \\\\ a + 3b = 1\\end{array} \\right.$$" 329 | ] 330 | }, 331 | { 332 | "cell_type": "code", 333 | "execution_count": null, 334 | "metadata": {}, 335 | "outputs": [], 336 | "source": [ 337 | "[sympy.Eq(2*a + 1, 0), sympy.Eq(2*a + 1, 1)] " 338 | ] 339 | }, 340 | { 341 | "cell_type": "code", 342 | "execution_count": null, 343 | "metadata": {}, 344 | "outputs": [], 345 | "source": [ 346 | "sympy.solve([sympy.Eq(2*a + 1, 0),\n", 347 | " sympy.Eq(a + 3*b, 1)], [a,b])" 348 | ] 349 | }, 350 | { 351 | "cell_type": "markdown", 352 | "metadata": {}, 353 | "source": [ 354 | "$$\\lim_{x \\rightarrow \\infty} x \\sin\\bigl(\\frac{1}{x}\\bigr)$$" 355 | ] 356 | }, 357 | { 358 | "cell_type": "code", 359 | "execution_count": null, 360 | "metadata": {}, 361 | "outputs": [], 362 | "source": [ 363 | "sympy.limit(x * sin(1/x), x, sympy.oo)" 364 | ] 365 | }, 366 | { 367 | "cell_type": "markdown", 368 | "metadata": {}, 369 | "source": [ 370 | "$$\\lim_{x \\rightarrow 0} (1 + x)^{1/x}$$" 371 | ] 372 | }, 373 | { 374 | "cell_type": "code", 375 | "execution_count": null, 376 | "metadata": {}, 377 | "outputs": [], 378 | "source": [ 379 | "sympy.limit((1 + x)**(1/x), x, 0)" 380 | ] 381 | }, 382 | { 383 | "cell_type": "markdown", 384 | "metadata": {}, 385 | "source": [ 386 | "$$\\sum_{n=0}^{\\infty} x^n$$" 387 | ] 388 | }, 389 | { 390 | "cell_type": "code", 391 | "execution_count": null, 392 | "metadata": {}, 393 | "outputs": [], 394 | "source": [ 395 | "n = sympy.Symbol('n')" 396 | ] 397 | }, 398 | { 399 | "cell_type": "code", 400 | "execution_count": null, 401 | "metadata": {}, 402 | "outputs": [], 403 | "source": [ 404 | "sympy.summation(x**n, (n, 0, sympy.oo))" 405 | ] 406 | }, 407 | { 408 | "cell_type": "code", 409 | "execution_count": null, 410 | "metadata": {}, 411 | "outputs": [], 412 | "source": [ 413 | "sympy.series(log(1 + x), x)" 414 | ] 415 | }, 416 | { 417 | "cell_type": "code", 418 | "execution_count": null, 419 | "metadata": {}, 420 | "outputs": [], 421 | "source": [ 422 | "_.removeO()" 423 | ] 424 | }, 425 | { 426 | "cell_type": "markdown", 427 | "metadata": {}, 428 | "source": [ 429 | "$$\\frac{\\mathrm{d}}{\\mathrm{d}x} \\bigl(x^2 \\cos(x) \\bigr)$$" 430 | ] 431 | }, 432 | { 433 | "cell_type": "code", 434 | "execution_count": null, 435 | "metadata": {}, 436 | "outputs": [], 437 | "source": [ 438 | "sympy.diff(x**2 * cos(x), x)" 439 | ] 440 | }, 441 | { 442 | "cell_type": "markdown", 443 | "metadata": {}, 444 | "source": [ 445 | "$$\\int \\frac{\\mathrm{d}}{\\mathrm{d}x} \\bigl(x^2 \\cos(x) \\bigr) \\, \\mathrm{d} x$$" 446 | ] 447 | }, 448 | { 449 | "cell_type": "code", 450 | "execution_count": null, 451 | "metadata": {}, 452 | "outputs": [], 453 | "source": [ 454 | "sympy.integrate(_, x)" 455 | ] 456 | }, 457 | { 458 | "cell_type": "markdown", 459 | "metadata": {}, 460 | "source": [ 461 | "$$\\int_0^\\pi x^2 \\cos(x) \\, \\mathrm{d} x$$" 462 | ] 463 | }, 464 | { 465 | "cell_type": "code", 466 | "execution_count": null, 467 | "metadata": {}, 468 | "outputs": [], 469 | "source": [ 470 | "sympy.integrate(_, (x, 0, sympy.pi))" 471 | ] 472 | }, 473 | { 474 | "cell_type": "code", 475 | "execution_count": null, 476 | "metadata": {}, 477 | "outputs": [], 478 | "source": [ 479 | "sympy.Integral(x**2 * cos(x), (x, 0, a))" 480 | ] 481 | }, 482 | { 483 | "cell_type": "code", 484 | "execution_count": null, 485 | "metadata": {}, 486 | "outputs": [], 487 | "source": [ 488 | "sympy.diff(_, a)" 489 | ] 490 | }, 491 | { 492 | "cell_type": "code", 493 | "execution_count": null, 494 | "metadata": {}, 495 | "outputs": [], 496 | "source": [ 497 | "y = sympy.Function('y')" 498 | ] 499 | }, 500 | { 501 | "cell_type": "code", 502 | "execution_count": null, 503 | "metadata": {}, 504 | "outputs": [], 505 | "source": [ 506 | "sympy.Derivative(y(x))" 507 | ] 508 | }, 509 | { 510 | "cell_type": "markdown", 511 | "metadata": {}, 512 | "source": [ 513 | "$$y' = t^3 y^2 - \\frac{4}{t} y$$" 514 | ] 515 | }, 516 | { 517 | "cell_type": "code", 518 | "execution_count": null, 519 | "metadata": {}, 520 | "outputs": [], 521 | "source": [ 522 | "sympy.Derivative(y(x)) - x**3 * y(x)**2 + (4/x) * y(x)" 523 | ] 524 | }, 525 | { 526 | "cell_type": "code", 527 | "execution_count": null, 528 | "metadata": {}, 529 | "outputs": [], 530 | "source": [ 531 | "sol = sympy.dsolve(_, y(x))" 532 | ] 533 | }, 534 | { 535 | "cell_type": "code", 536 | "execution_count": null, 537 | "metadata": {}, 538 | "outputs": [], 539 | "source": [ 540 | "sol" 541 | ] 542 | }, 543 | { 544 | "cell_type": "code", 545 | "execution_count": null, 546 | "metadata": {}, 547 | "outputs": [], 548 | "source": [ 549 | "sol.rhs" 550 | ] 551 | }, 552 | { 553 | "cell_type": "markdown", 554 | "metadata": {}, 555 | "source": [ 556 | "$$y(2) = -1$$" 557 | ] 558 | }, 559 | { 560 | "cell_type": "code", 561 | "execution_count": null, 562 | "metadata": {}, 563 | "outputs": [], 564 | "source": [ 565 | "sympy.solve(sol.rhs.subs({x: 2}) + 1, sympy.Symbol('C1'))" 566 | ] 567 | }, 568 | { 569 | "cell_type": "code", 570 | "execution_count": null, 571 | "metadata": {}, 572 | "outputs": [], 573 | "source": [ 574 | "sol.rhs.subs({'C1': _[0]})" 575 | ] 576 | }, 577 | { 578 | "cell_type": "code", 579 | "execution_count": null, 580 | "metadata": {}, 581 | "outputs": [], 582 | "source": [ 583 | "sympy.pycode(_), sympy.ccode(_)" 584 | ] 585 | }, 586 | { 587 | "cell_type": "code", 588 | "execution_count": null, 589 | "metadata": {}, 590 | "outputs": [], 591 | "source": [] 592 | } 593 | ], 594 | "metadata": { 595 | "kernelspec": { 596 | "display_name": "Python 3", 597 | "language": "python", 598 | "name": "python3" 599 | }, 600 | "language_info": { 601 | "codemirror_mode": { 602 | "name": "ipython", 603 | "version": 3 604 | }, 605 | "file_extension": ".py", 606 | "mimetype": "text/x-python", 607 | "name": "python", 608 | "nbconvert_exporter": "python", 609 | "pygments_lexer": "ipython3", 610 | "version": "3.8.8" 611 | }, 612 | "toc": { 613 | "base_numbering": 1, 614 | "nav_menu": {}, 615 | "number_sections": true, 616 | "sideBar": true, 617 | "skip_h1_title": false, 618 | "title_cell": "Table of Contents", 619 | "title_sidebar": "Contents", 620 | "toc_cell": false, 621 | "toc_position": {}, 622 | "toc_section_display": true, 623 | "toc_window_display": false 624 | } 625 | }, 626 | "nbformat": 4, 627 | "nbformat_minor": 4 628 | } 629 | -------------------------------------------------------------------------------- /Ch03/03_03_astropy.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 03_03_astropy.ipynb - Units, constants, timescales and more with Astropy" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "import math\n", 17 | "import datetime" 18 | ] 19 | }, 20 | { 21 | "cell_type": "code", 22 | "execution_count": null, 23 | "metadata": {}, 24 | "outputs": [], 25 | "source": [ 26 | "import numpy as np\n", 27 | "import matplotlib.pyplot as pp\n", 28 | "\n", 29 | "import astropy\n", 30 | "import astropy.units as au\n", 31 | "import astropy.constants as ac\n", 32 | "import astropy.time as at\n", 33 | "import astropy.coordinates as ao" 34 | ] 35 | }, 36 | { 37 | "cell_type": "code", 38 | "execution_count": null, 39 | "metadata": {}, 40 | "outputs": [], 41 | "source": [ 42 | "distance = 100 * au.m" 43 | ] 44 | }, 45 | { 46 | "cell_type": "code", 47 | "execution_count": null, 48 | "metadata": {}, 49 | "outputs": [], 50 | "source": [ 51 | "type(distance)" 52 | ] 53 | }, 54 | { 55 | "cell_type": "code", 56 | "execution_count": null, 57 | "metadata": {}, 58 | "outputs": [], 59 | "source": [ 60 | "distance" 61 | ] 62 | }, 63 | { 64 | "cell_type": "code", 65 | "execution_count": null, 66 | "metadata": {}, 67 | "outputs": [], 68 | "source": [ 69 | "distance.value, distance.unit" 70 | ] 71 | }, 72 | { 73 | "cell_type": "code", 74 | "execution_count": null, 75 | "metadata": {}, 76 | "outputs": [], 77 | "source": [ 78 | "speed = distance / (9.58 * au.s)" 79 | ] 80 | }, 81 | { 82 | "cell_type": "code", 83 | "execution_count": null, 84 | "metadata": {}, 85 | "outputs": [], 86 | "source": [ 87 | "speed" 88 | ] 89 | }, 90 | { 91 | "cell_type": "code", 92 | "execution_count": null, 93 | "metadata": {}, 94 | "outputs": [], 95 | "source": [ 96 | "speed.to('km/h')" 97 | ] 98 | }, 99 | { 100 | "cell_type": "code", 101 | "execution_count": null, 102 | "metadata": {}, 103 | "outputs": [], 104 | "source": [ 105 | "speed.si" 106 | ] 107 | }, 108 | { 109 | "cell_type": "code", 110 | "execution_count": null, 111 | "metadata": {}, 112 | "outputs": [], 113 | "source": [ 114 | "speed.cgs" 115 | ] 116 | }, 117 | { 118 | "cell_type": "code", 119 | "execution_count": null, 120 | "metadata": {}, 121 | "outputs": [], 122 | "source": [ 123 | "np.linspace(0, 100, 11) * au.km" 124 | ] 125 | }, 126 | { 127 | "cell_type": "code", 128 | "execution_count": null, 129 | "metadata": {}, 130 | "outputs": [], 131 | "source": [ 132 | "ac.c" 133 | ] 134 | }, 135 | { 136 | "cell_type": "code", 137 | "execution_count": null, 138 | "metadata": {}, 139 | "outputs": [], 140 | "source": [ 141 | "print(ac.c)" 142 | ] 143 | }, 144 | { 145 | "cell_type": "code", 146 | "execution_count": null, 147 | "metadata": {}, 148 | "outputs": [], 149 | "source": [ 150 | "ac.c.name, ac.c.uncertainty, ac.c.reference" 151 | ] 152 | }, 153 | { 154 | "cell_type": "code", 155 | "execution_count": null, 156 | "metadata": {}, 157 | "outputs": [], 158 | "source": [ 159 | "np.sqrt(ac.hbar * ac.G / ac.c**3)" 160 | ] 161 | }, 162 | { 163 | "cell_type": "code", 164 | "execution_count": null, 165 | "metadata": {}, 166 | "outputs": [], 167 | "source": [ 168 | "_.si" 169 | ] 170 | }, 171 | { 172 | "cell_type": "code", 173 | "execution_count": null, 174 | "metadata": {}, 175 | "outputs": [], 176 | "source": [ 177 | "at.Time('2001-01-01T12:30:00')" 178 | ] 179 | }, 180 | { 181 | "cell_type": "code", 182 | "execution_count": null, 183 | "metadata": {}, 184 | "outputs": [], 185 | "source": [ 186 | "at.Time(datetime.datetime(year=2001, month=1, day=1, hour=12, minute=30))" 187 | ] 188 | }, 189 | { 190 | "cell_type": "code", 191 | "execution_count": null, 192 | "metadata": {}, 193 | "outputs": [], 194 | "source": [ 195 | "at.Time(51910.52, format='mjd').format" 196 | ] 197 | }, 198 | { 199 | "cell_type": "code", 200 | "execution_count": null, 201 | "metadata": {}, 202 | "outputs": [], 203 | "source": [ 204 | "at.Time(662387341, format='gps')" 205 | ] 206 | }, 207 | { 208 | "cell_type": "code", 209 | "execution_count": null, 210 | "metadata": {}, 211 | "outputs": [], 212 | "source": [ 213 | "at.Time(51910.52, format='mjd').iso" 214 | ] 215 | }, 216 | { 217 | "cell_type": "code", 218 | "execution_count": null, 219 | "metadata": {}, 220 | "outputs": [], 221 | "source": [ 222 | "at.Time(at.Time(51910.52, format='mjd'), format='iso')" 223 | ] 224 | }, 225 | { 226 | "cell_type": "code", 227 | "execution_count": null, 228 | "metadata": {}, 229 | "outputs": [], 230 | "source": [ 231 | "t0 = at.Time('2021-07-01T00:00:00', scale='utc')" 232 | ] 233 | }, 234 | { 235 | "cell_type": "code", 236 | "execution_count": null, 237 | "metadata": {}, 238 | "outputs": [], 239 | "source": [ 240 | "t0.tai" 241 | ] 242 | }, 243 | { 244 | "cell_type": "code", 245 | "execution_count": null, 246 | "metadata": {}, 247 | "outputs": [], 248 | "source": [ 249 | "t0.ut1" 250 | ] 251 | }, 252 | { 253 | "cell_type": "code", 254 | "execution_count": null, 255 | "metadata": {}, 256 | "outputs": [], 257 | "source": [ 258 | "ao.get_body('jupiter', t0)" 259 | ] 260 | }, 261 | { 262 | "cell_type": "code", 263 | "execution_count": null, 264 | "metadata": {}, 265 | "outputs": [], 266 | "source": [ 267 | "ao.get_body_barycentric('jupiter', t0)" 268 | ] 269 | }, 270 | { 271 | "cell_type": "code", 272 | "execution_count": null, 273 | "metadata": {}, 274 | "outputs": [], 275 | "source": [ 276 | "ao.get_body_barycentric_posvel('jupiter', t0)" 277 | ] 278 | }, 279 | { 280 | "cell_type": "code", 281 | "execution_count": null, 282 | "metadata": {}, 283 | "outputs": [], 284 | "source": [ 285 | "ts = at.Time(np.linspace(at.Time('2021-07-01').mjd, at.Time('2031-07-01').mjd, 100),\n", 286 | " format='mjd')" 287 | ] 288 | }, 289 | { 290 | "cell_type": "code", 291 | "execution_count": null, 292 | "metadata": {}, 293 | "outputs": [], 294 | "source": [ 295 | "jposvel = ao.get_body_barycentric_posvel('jupiter', ts)" 296 | ] 297 | }, 298 | { 299 | "cell_type": "code", 300 | "execution_count": null, 301 | "metadata": {}, 302 | "outputs": [], 303 | "source": [ 304 | "jposvel[0]" 305 | ] 306 | }, 307 | { 308 | "cell_type": "code", 309 | "execution_count": null, 310 | "metadata": {}, 311 | "outputs": [], 312 | "source": [ 313 | "dir(jposvel[0])" 314 | ] 315 | }, 316 | { 317 | "cell_type": "code", 318 | "execution_count": null, 319 | "metadata": {}, 320 | "outputs": [], 321 | "source": [ 322 | "jposvel[0].xyz" 323 | ] 324 | }, 325 | { 326 | "cell_type": "code", 327 | "execution_count": null, 328 | "metadata": {}, 329 | "outputs": [], 330 | "source": [ 331 | "jposvel[0].xyz.shape" 332 | ] 333 | }, 334 | { 335 | "cell_type": "code", 336 | "execution_count": null, 337 | "metadata": {}, 338 | "outputs": [], 339 | "source": [ 340 | "jposvel[0].xyz.value" 341 | ] 342 | }, 343 | { 344 | "cell_type": "code", 345 | "execution_count": null, 346 | "metadata": {}, 347 | "outputs": [], 348 | "source": [ 349 | "def get_posvel(body, t):\n", 350 | " posvel = astropy.coordinates.get_body_barycentric_posvel(body, t)\n", 351 | " \n", 352 | " return np.hstack([posvel[0].xyz.value.T, posvel[1].xyz.value.T])" 353 | ] 354 | }, 355 | { 356 | "cell_type": "code", 357 | "execution_count": null, 358 | "metadata": {}, 359 | "outputs": [], 360 | "source": [ 361 | "jarray = get_posvel('jupiter', ts)" 362 | ] 363 | }, 364 | { 365 | "cell_type": "code", 366 | "execution_count": null, 367 | "metadata": {}, 368 | "outputs": [], 369 | "source": [ 370 | "jarray.shape" 371 | ] 372 | }, 373 | { 374 | "cell_type": "code", 375 | "execution_count": null, 376 | "metadata": {}, 377 | "outputs": [], 378 | "source": [ 379 | "pp.plot(jarray[:,0], jarray[:,1])\n", 380 | "pp.axis('equal')" 381 | ] 382 | }, 383 | { 384 | "cell_type": "code", 385 | "execution_count": null, 386 | "metadata": {}, 387 | "outputs": [], 388 | "source": [ 389 | "for i in range(3,6):\n", 390 | " pp.plot(ts.value, jarray[:,i])" 391 | ] 392 | } 393 | ], 394 | "metadata": { 395 | "kernelspec": { 396 | "display_name": "Python 3", 397 | "language": "python", 398 | "name": "python3" 399 | }, 400 | "language_info": { 401 | "codemirror_mode": { 402 | "name": "ipython", 403 | "version": 3 404 | }, 405 | "file_extension": ".py", 406 | "mimetype": "text/x-python", 407 | "name": "python", 408 | "nbconvert_exporter": "python", 409 | "pygments_lexer": "ipython3", 410 | "version": "3.8.8" 411 | }, 412 | "toc": { 413 | "base_numbering": 1, 414 | "nav_menu": {}, 415 | "number_sections": true, 416 | "sideBar": true, 417 | "skip_h1_title": false, 418 | "title_cell": "Table of Contents", 419 | "title_sidebar": "Contents", 420 | "toc_cell": false, 421 | "toc_position": {}, 422 | "toc_section_display": true, 423 | "toc_window_display": false 424 | } 425 | }, 426 | "nbformat": 4, 427 | "nbformat_minor": 4 428 | } 429 | -------------------------------------------------------------------------------- /Ch03/03_04_ode.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 03_04_ode.ipynb - Differential equations with SciPy" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "import math" 17 | ] 18 | }, 19 | { 20 | "cell_type": "code", 21 | "execution_count": null, 22 | "metadata": {}, 23 | "outputs": [], 24 | "source": [ 25 | "import numpy as np\n", 26 | "import scipy\n", 27 | "import scipy.integrate as si\n", 28 | "import matplotlib.pyplot as pp" 29 | ] 30 | }, 31 | { 32 | "cell_type": "code", 33 | "execution_count": null, 34 | "metadata": {}, 35 | "outputs": [], 36 | "source": [ 37 | "import numba\n", 38 | "\n", 39 | "import astropy\n", 40 | "import astropy.time\n", 41 | "import astropy.coordinates\n", 42 | "import astropy.units\n", 43 | "import astropy.constants" 44 | ] 45 | }, 46 | { 47 | "cell_type": "code", 48 | "execution_count": null, 49 | "metadata": {}, 50 | "outputs": [], 51 | "source": [ 52 | "import numba" 53 | ] 54 | }, 55 | { 56 | "cell_type": "markdown", 57 | "metadata": {}, 58 | "source": [ 59 | "$$y' = t^3 y^2 - \\frac{4}{t} y \\quad \\text{with} \\quad y(2) = -1$$.\n" 60 | ] 61 | }, 62 | { 63 | "cell_type": "code", 64 | "execution_count": null, 65 | "metadata": {}, 66 | "outputs": [], 67 | "source": [ 68 | "sol = si.solve_ivp(lambda t,y: t**3 * y**2 - (4 / t)*y, [2,3], [-1])" 69 | ] 70 | }, 71 | { 72 | "cell_type": "code", 73 | "execution_count": null, 74 | "metadata": {}, 75 | "outputs": [], 76 | "source": [ 77 | "sol" 78 | ] 79 | }, 80 | { 81 | "cell_type": "code", 82 | "execution_count": null, 83 | "metadata": {}, 84 | "outputs": [], 85 | "source": [ 86 | "pp.plot(sol.t, sol.y[0,:], '.--')\n", 87 | "\n", 88 | "x = np.linspace(2,3)\n", 89 | "pp.plot(x, 1/(x**4*(-np.log(x) - 1/16 + math.log(2))))" 90 | ] 91 | }, 92 | { 93 | "cell_type": "code", 94 | "execution_count": null, 95 | "metadata": {}, 96 | "outputs": [], 97 | "source": [ 98 | "def ydot(t, y):\n", 99 | " # how many bodies? make sure the answer is an integer\n", 100 | " n = int(y.shape[0] / 6)\n", 101 | "\n", 102 | " # make an empty container for the derivatives\n", 103 | " yd = np.zeros_like(y)\n", 104 | " \n", 105 | " # for each body\n", 106 | " for i in range(n):\n", 107 | " # set x_i' = v_i (array slice assignment)\n", 108 | " yd[i*6:i*6+3] = y[i*6+3:i*6+6]\n", 109 | " \n", 110 | " # loop over all other bodies\n", 111 | " for j in range(n):\n", 112 | " if i == j:\n", 113 | " continue\n", 114 | "\n", 115 | " # add contribution of planet j to v_i'\n", 116 | " rij = y[j*6:j*6+3] - y[i*6:i*6+3]\n", 117 | " yd[i*6+3:i*6+6] += G * masses[j] * rij / np.dot(rij,rij)**1.5\n", 118 | " \n", 119 | " return yd" 120 | ] 121 | }, 122 | { 123 | "cell_type": "code", 124 | "execution_count": null, 125 | "metadata": {}, 126 | "outputs": [], 127 | "source": [ 128 | "# IAU 2012 values from from http://maia.usno.navy.mil/NSFA/NSFA_cbe.html\n", 129 | "\n", 130 | "bodies = ['sun','mercury','venus','earth','mars','jupiter','saturn','uranus','neptune']\n", 131 | "\n", 132 | "# dictionary of masses\n", 133 | "massdict = {'sun': 1.0,\n", 134 | " 'mercury': 1.6601209949637026e-07,\n", 135 | " 'venus': 2.4478382857373332e-06,\n", 136 | " 'earth': 3.0034896946063695e-06,\n", 137 | " 'mars': 3.227156037857755e-07,\n", 138 | " 'jupiter': 0.0009547918983127075,\n", 139 | " 'saturn': 0.00028588567008942334,\n", 140 | " 'uranus': 4.3662495719438076e-05,\n", 141 | " 'neptune': 5.151383713179197e-05}\n", 142 | "\n", 143 | "# array of masses\n", 144 | "masses = np.array([massdict[body] for body in bodies])" 145 | ] 146 | }, 147 | { 148 | "cell_type": "code", 149 | "execution_count": null, 150 | "metadata": {}, 151 | "outputs": [], 152 | "source": [ 153 | "astropy.constants.G.to('AU^3 / (Msun d^2)')" 154 | ] 155 | }, 156 | { 157 | "cell_type": "code", 158 | "execution_count": null, 159 | "metadata": {}, 160 | "outputs": [], 161 | "source": [ 162 | "G = astropy.constants.G.to('AU^3 / (Msun d^2)').value" 163 | ] 164 | }, 165 | { 166 | "cell_type": "code", 167 | "execution_count": null, 168 | "metadata": {}, 169 | "outputs": [], 170 | "source": [ 171 | "t0 = astropy.time.Time('2021-07-04')" 172 | ] 173 | }, 174 | { 175 | "cell_type": "code", 176 | "execution_count": null, 177 | "metadata": {}, 178 | "outputs": [], 179 | "source": [ 180 | "def get_posvel(body, t):\n", 181 | " posvel = astropy.coordinates.get_body_barycentric_posvel(body, t)\n", 182 | " \n", 183 | " return np.hstack([posvel[0].xyz.value.T, posvel[1].xyz.value.T])" 184 | ] 185 | }, 186 | { 187 | "cell_type": "code", 188 | "execution_count": null, 189 | "metadata": {}, 190 | "outputs": [], 191 | "source": [ 192 | "get_posvel('earth', t0)" 193 | ] 194 | }, 195 | { 196 | "cell_type": "code", 197 | "execution_count": null, 198 | "metadata": {}, 199 | "outputs": [], 200 | "source": [ 201 | "np.array([get_posvel(body, t0) for body in bodies])" 202 | ] 203 | }, 204 | { 205 | "cell_type": "code", 206 | "execution_count": null, 207 | "metadata": {}, 208 | "outputs": [], 209 | "source": [ 210 | "y0 = np.array([get_posvel(body, t0) for body in bodies]).flatten()" 211 | ] 212 | }, 213 | { 214 | "cell_type": "code", 215 | "execution_count": null, 216 | "metadata": {}, 217 | "outputs": [], 218 | "source": [ 219 | "y0.shape" 220 | ] 221 | }, 222 | { 223 | "cell_type": "code", 224 | "execution_count": null, 225 | "metadata": {}, 226 | "outputs": [], 227 | "source": [ 228 | "t1 = astropy.time.Time('2031-07-04')" 229 | ] 230 | }, 231 | { 232 | "cell_type": "code", 233 | "execution_count": null, 234 | "metadata": {}, 235 | "outputs": [], 236 | "source": [ 237 | "t0.mjd, t1.mjd" 238 | ] 239 | }, 240 | { 241 | "cell_type": "code", 242 | "execution_count": null, 243 | "metadata": {}, 244 | "outputs": [], 245 | "source": [ 246 | "orbits = scipy.integrate.solve_ivp(numba.jit(ydot), [t0.mjd, t1.mjd], y0, rtol=1e-9, atol=1e-9)" 247 | ] 248 | }, 249 | { 250 | "cell_type": "code", 251 | "execution_count": null, 252 | "metadata": {}, 253 | "outputs": [], 254 | "source": [ 255 | "orbits" 256 | ] 257 | }, 258 | { 259 | "cell_type": "code", 260 | "execution_count": null, 261 | "metadata": {}, 262 | "outputs": [], 263 | "source": [ 264 | "for i in range(9):\n", 265 | " pp.plot(orbits.y[i*6,:], orbits.y[i*6+1,:], label=bodies[i])\n", 266 | "\n", 267 | "pp.legend()\n", 268 | "pp.axis('equal');" 269 | ] 270 | } 271 | ], 272 | "metadata": { 273 | "kernelspec": { 274 | "display_name": "Python 3", 275 | "language": "python", 276 | "name": "python3" 277 | }, 278 | "language_info": { 279 | "codemirror_mode": { 280 | "name": "ipython", 281 | "version": 3 282 | }, 283 | "file_extension": ".py", 284 | "mimetype": "text/x-python", 285 | "name": "python", 286 | "nbconvert_exporter": "python", 287 | "pygments_lexer": "ipython3", 288 | "version": "3.8.8" 289 | }, 290 | "toc": { 291 | "base_numbering": 1, 292 | "nav_menu": {}, 293 | "number_sections": true, 294 | "sideBar": true, 295 | "skip_h1_title": false, 296 | "title_cell": "Table of Contents", 297 | "title_sidebar": "Contents", 298 | "toc_cell": false, 299 | "toc_position": {}, 300 | "toc_section_display": true, 301 | "toc_window_display": false 302 | } 303 | }, 304 | "nbformat": 4, 305 | "nbformat_minor": 4 306 | } 307 | -------------------------------------------------------------------------------- /Ch03/03_05_morescipy.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 03_05_morescipy.ipynb - Interpolation and optimization with SciPy" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "import numpy as np\n", 17 | "import matplotlib.pyplot as pp\n", 18 | "\n", 19 | "import numba\n", 20 | "\n", 21 | "import astropy.constants\n", 22 | "import astropy.time\n", 23 | "import astropy.coordinates\n", 24 | "\n", 25 | "import scipy.integrate\n", 26 | "import scipy.interpolate\n", 27 | "import scipy.optimize" 28 | ] 29 | }, 30 | { 31 | "cell_type": "markdown", 32 | "metadata": {}, 33 | "source": [ 34 | "#### Solar System integrator from 03_04" 35 | ] 36 | }, 37 | { 38 | "cell_type": "code", 39 | "execution_count": null, 40 | "metadata": {}, 41 | "outputs": [], 42 | "source": [ 43 | "bodies = ['sun','mercury','venus','earth','mars','jupiter','saturn','uranus','neptune']\n", 44 | "\n", 45 | "massdict = {'sun': 1.0,\n", 46 | " 'mercury': 1.6601209949637026e-07,\n", 47 | " 'venus': 2.4478382857373332e-06,\n", 48 | " 'earth': 3.0034896946063695e-06,\n", 49 | " 'mars': 3.227156037857755e-07,\n", 50 | " 'jupiter': 0.0009547918983127075,\n", 51 | " 'saturn': 0.00028588567008942334,\n", 52 | " 'uranus': 4.3662495719438076e-05,\n", 53 | " 'neptune': 5.151383713179197e-05}\n", 54 | "\n", 55 | "masses = np.array([massdict[body] for body in bodies])" 56 | ] 57 | }, 58 | { 59 | "cell_type": "code", 60 | "execution_count": null, 61 | "metadata": {}, 62 | "outputs": [], 63 | "source": [ 64 | "G = astropy.constants.G.to('AU^3 / (Msun d^2)').value" 65 | ] 66 | }, 67 | { 68 | "cell_type": "code", 69 | "execution_count": null, 70 | "metadata": {}, 71 | "outputs": [], 72 | "source": [ 73 | "@numba.jit\n", 74 | "def ydot(t, y):\n", 75 | " # how many bodies? make sure the answer is an integer\n", 76 | " n = int(y.shape[0] / 6)\n", 77 | "\n", 78 | " # make an empty container for the derivatives\n", 79 | " yd = np.zeros_like(y)\n", 80 | " \n", 81 | " # for each body\n", 82 | " for i in range(n):\n", 83 | " # set x_i' = v_i (array slice assignment)\n", 84 | " yd[i*6:i*6+3] = y[i*6+3:i*6+6]\n", 85 | " \n", 86 | " # loop over all other bodies\n", 87 | " for j in range(n):\n", 88 | " if i == j:\n", 89 | " continue\n", 90 | "\n", 91 | " # add contribution of planet j to v_i'\n", 92 | " rij = y[j*6:j*6+3] - y[i*6:i*6+3]\n", 93 | " yd[i*6+3:i*6+6] += G * masses[j] * rij / np.dot(rij,rij)**1.5\n", 94 | " \n", 95 | " return yd" 96 | ] 97 | }, 98 | { 99 | "cell_type": "code", 100 | "execution_count": null, 101 | "metadata": {}, 102 | "outputs": [], 103 | "source": [ 104 | "def get_posvel(body, t):\n", 105 | " posvel = astropy.coordinates.get_body_barycentric_posvel(body, t)\n", 106 | " \n", 107 | " return np.hstack([posvel[0].xyz.value.T, posvel[1].xyz.value.T])" 108 | ] 109 | }, 110 | { 111 | "cell_type": "code", 112 | "execution_count": null, 113 | "metadata": {}, 114 | "outputs": [], 115 | "source": [ 116 | "t0, t1 = astropy.time.Time('2021-07-04'), astropy.time.Time('2031-07-04')" 117 | ] 118 | }, 119 | { 120 | "cell_type": "code", 121 | "execution_count": null, 122 | "metadata": {}, 123 | "outputs": [], 124 | "source": [ 125 | "y0 = np.array([get_posvel(body, t0) for body in bodies]).flatten()" 126 | ] 127 | }, 128 | { 129 | "cell_type": "code", 130 | "execution_count": null, 131 | "metadata": {}, 132 | "outputs": [], 133 | "source": [ 134 | "orbits = scipy.integrate.solve_ivp(ydot, [t0.mjd, t1.mjd], y0, rtol=1e-9, atol=1e-9)" 135 | ] 136 | }, 137 | { 138 | "cell_type": "markdown", 139 | "metadata": {}, 140 | "source": [ 141 | "#### Interpolating distances" 142 | ] 143 | }, 144 | { 145 | "cell_type": "code", 146 | "execution_count": null, 147 | "metadata": {}, 148 | "outputs": [], 149 | "source": [ 150 | "orbits" 151 | ] 152 | }, 153 | { 154 | "cell_type": "code", 155 | "execution_count": null, 156 | "metadata": {}, 157 | "outputs": [], 158 | "source": [ 159 | "pp.plot(np.diff(orbits.t), '.')" 160 | ] 161 | }, 162 | { 163 | "cell_type": "code", 164 | "execution_count": null, 165 | "metadata": {}, 166 | "outputs": [], 167 | "source": [ 168 | "orbint = scipy.interpolate.interp1d(orbits.t, orbits.y, kind='quadratic')" 169 | ] 170 | }, 171 | { 172 | "cell_type": "code", 173 | "execution_count": null, 174 | "metadata": {}, 175 | "outputs": [], 176 | "source": [ 177 | "orbint(t0.mjd + 365.25)" 178 | ] 179 | }, 180 | { 181 | "cell_type": "code", 182 | "execution_count": null, 183 | "metadata": {}, 184 | "outputs": [], 185 | "source": [ 186 | "ts = astropy.time.Time('2025-01-01').mjd + np.arange(0, 5*365)\n", 187 | "oneyear = orbint(ts)[3*6:4*6,:]\n", 188 | "\n", 189 | "for i in range(3):\n", 190 | " pp.plot(ts, orbint(ts)[3*6+i,:], '-')" 191 | ] 192 | }, 193 | { 194 | "cell_type": "markdown", 195 | "metadata": {}, 196 | "source": [ 197 | "#### Finding minima" 198 | ] 199 | }, 200 | { 201 | "cell_type": "code", 202 | "execution_count": null, 203 | "metadata": {}, 204 | "outputs": [], 205 | "source": [ 206 | "def get_dist(t, body1, body2, orbint):\n", 207 | " # get position of all bodies at time t\n", 208 | " y = orbint(t)\n", 209 | " \n", 210 | " # compute indices of each body\n", 211 | " i, j = bodies.index(body1), bodies.index(body2)\n", 212 | " \n", 213 | " # compute Euclidian distance\n", 214 | " return np.sqrt(np.sum((y[i*6:i*6+3] - y[j*6:j*6+3])**2, axis=0))" 215 | ] 216 | }, 217 | { 218 | "cell_type": "code", 219 | "execution_count": null, 220 | "metadata": {}, 221 | "outputs": [], 222 | "source": [ 223 | "pp.plot(ts, get_dist(ts, 'jupiter', 'sun', orbint))" 224 | ] 225 | }, 226 | { 227 | "cell_type": "code", 228 | "execution_count": null, 229 | "metadata": {}, 230 | "outputs": [], 231 | "source": [ 232 | "minimum = so.minimize(lambda t: -get_dist(t, 'jupiter', 'sun', orbint),\n", 233 | " x0=ts[900], bounds=[(ts[0],ts[-1])])" 234 | ] 235 | }, 236 | { 237 | "cell_type": "code", 238 | "execution_count": null, 239 | "metadata": {}, 240 | "outputs": [], 241 | "source": [ 242 | "minimum" 243 | ] 244 | }, 245 | { 246 | "cell_type": "code", 247 | "execution_count": null, 248 | "metadata": {}, 249 | "outputs": [], 250 | "source": [ 251 | "pp.plot(ts, get_dist(ts, 'jupiter', 'sun', orbint))\n", 252 | "pp.plot(minimum.x, -minimum.fun, 'ro')" 253 | ] 254 | }, 255 | { 256 | "cell_type": "code", 257 | "execution_count": null, 258 | "metadata": {}, 259 | "outputs": [], 260 | "source": [ 261 | "pp.plot(ts, get_dist(ts, 'mars', 'venus', orbint))" 262 | ] 263 | }, 264 | { 265 | "cell_type": "code", 266 | "execution_count": null, 267 | "metadata": {}, 268 | "outputs": [], 269 | "source": [ 270 | "minimum = so.minimize(get_dist,\n", 271 | " x0=ts[900], args=('mars','venus',orbint),\n", 272 | " bounds=[(ts[0],ts[-1])])" 273 | ] 274 | }, 275 | { 276 | "cell_type": "code", 277 | "execution_count": null, 278 | "metadata": {}, 279 | "outputs": [], 280 | "source": [ 281 | "pp.plot(ts, get_dist(ts, 'mars', 'venus', orbint))\n", 282 | "pp.plot(minimum.x, minimum.fun, 'ro')" 283 | ] 284 | }, 285 | { 286 | "cell_type": "code", 287 | "execution_count": null, 288 | "metadata": {}, 289 | "outputs": [], 290 | "source": [ 291 | "for x0 in [61000,61750,62500]:\n", 292 | " minimum = so.minimize(get_dist, x0=x0, args=('mars','venus',orbint), bounds=[(ts[0],ts[-1])])\n", 293 | " print(minimum.x, minimum.fun)" 294 | ] 295 | } 296 | ], 297 | "metadata": { 298 | "kernelspec": { 299 | "display_name": "Python 3", 300 | "language": "python", 301 | "name": "python3" 302 | }, 303 | "language_info": { 304 | "codemirror_mode": { 305 | "name": "ipython", 306 | "version": 3 307 | }, 308 | "file_extension": ".py", 309 | "mimetype": "text/x-python", 310 | "name": "python", 311 | "nbconvert_exporter": "python", 312 | "pygments_lexer": "ipython3", 313 | "version": "3.8.8" 314 | }, 315 | "toc": { 316 | "base_numbering": 1, 317 | "nav_menu": {}, 318 | "number_sections": true, 319 | "sideBar": true, 320 | "skip_h1_title": false, 321 | "title_cell": "Table of Contents", 322 | "title_sidebar": "Contents", 323 | "toc_cell": false, 324 | "toc_position": {}, 325 | "toc_section_display": true, 326 | "toc_window_display": false 327 | } 328 | }, 329 | "nbformat": 4, 330 | "nbformat_minor": 4 331 | } 332 | -------------------------------------------------------------------------------- /Ch03/03_06_debugging.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 03_06_debugging.ipynb - Debugging with ipdb" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "import math" 17 | ] 18 | }, 19 | { 20 | "cell_type": "code", 21 | "execution_count": null, 22 | "metadata": {}, 23 | "outputs": [], 24 | "source": [ 25 | "import numpy as np\n", 26 | "import scipy\n", 27 | "import scipy.integrate as si\n", 28 | "import matplotlib.pyplot as pp" 29 | ] 30 | }, 31 | { 32 | "cell_type": "code", 33 | "execution_count": null, 34 | "metadata": {}, 35 | "outputs": [], 36 | "source": [ 37 | "import astropy\n", 38 | "import astropy.time\n", 39 | "import astropy.coordinates\n", 40 | "import astropy.units\n", 41 | "import astropy.constants" 42 | ] 43 | }, 44 | { 45 | "cell_type": "code", 46 | "execution_count": null, 47 | "metadata": {}, 48 | "outputs": [], 49 | "source": [ 50 | "# IAU 2012 values from from http://maia.usno.navy.mil/NSFA/NSFA_cbe.html\n", 51 | "\n", 52 | "bodies = ['sun','mercury','venus','earth','mars','jupiter','saturn','uranus','neptune']\n", 53 | "\n", 54 | "# dictionary of masses\n", 55 | "massdict = {'sun': 1.0,\n", 56 | " 'mercury': 1.6601209949637026e-07,\n", 57 | " 'venus': 2.4478382857373332e-06,\n", 58 | " 'earth': 3.0034896946063695e-06,\n", 59 | " 'mars': 3.227156037857755e-07,\n", 60 | " 'jupiter': 0.0009547918983127075,\n", 61 | " 'saturn': 0.00028588567008942334,\n", 62 | " 'uranus': 4.3662495719438076e-05,\n", 63 | " 'neptune': 5.151383713179197e-05}\n", 64 | "\n", 65 | "# array of masses\n", 66 | "masses = np.array([massdict[body] for body in bodies])" 67 | ] 68 | }, 69 | { 70 | "cell_type": "code", 71 | "execution_count": null, 72 | "metadata": {}, 73 | "outputs": [], 74 | "source": [ 75 | "G = astropy.constants.G.to('AU^3 / (Msun d^2)')" 76 | ] 77 | }, 78 | { 79 | "cell_type": "code", 80 | "execution_count": null, 81 | "metadata": {}, 82 | "outputs": [], 83 | "source": [ 84 | "t0, t1 = astropy.time.Time('2021-07-04'), astropy.time.Time('2031-07-04')" 85 | ] 86 | }, 87 | { 88 | "cell_type": "code", 89 | "execution_count": null, 90 | "metadata": {}, 91 | "outputs": [], 92 | "source": [ 93 | "def get_posvel(body, t):\n", 94 | " posvel = astropy.coordinates.get_body_barycentric_posvel(body, t)\n", 95 | " \n", 96 | " return np.hstack([posvel[0].xyz.value.T, posvel[1].xyz.value.T])" 97 | ] 98 | }, 99 | { 100 | "cell_type": "code", 101 | "execution_count": null, 102 | "metadata": {}, 103 | "outputs": [], 104 | "source": [ 105 | "y0 = np.array([get_posvel(body, t0) for body in bodies])" 106 | ] 107 | }, 108 | { 109 | "cell_type": "code", 110 | "execution_count": null, 111 | "metadata": {}, 112 | "outputs": [], 113 | "source": [ 114 | "def ydot(t, y):\n", 115 | " # how many bodies? make sure the answer is an integer\n", 116 | " n = int(y.shape[0] / 6)\n", 117 | "\n", 118 | " # make an empty container for the derivatives\n", 119 | " yd = np.zeros_like(y)\n", 120 | " \n", 121 | " # for each body\n", 122 | " for i in range(n):\n", 123 | " # set x_i' = v_i (array slice assignment)\n", 124 | " yd[i*6:i*6+3] = y[i*6+3:i*6+6]\n", 125 | " \n", 126 | " # loop over all other bodies\n", 127 | " for j in range(n):\n", 128 | " if i == j:\n", 129 | " continue\n", 130 | "\n", 131 | " # add contribution of planet j to v_i'\n", 132 | " rij = y[j*6:j*6+3] - y[i*6:i*6+3]\n", 133 | " yd[i*6+3:i*6+6] += G * masses[j] * rij / np.dot(rij,rij)\n", 134 | " \n", 135 | " return yd" 136 | ] 137 | }, 138 | { 139 | "cell_type": "code", 140 | "execution_count": null, 141 | "metadata": {}, 142 | "outputs": [], 143 | "source": [ 144 | "ydot(t0, y0)" 145 | ] 146 | }, 147 | { 148 | "cell_type": "code", 149 | "execution_count": null, 150 | "metadata": {}, 151 | "outputs": [], 152 | "source": [ 153 | "ydot(t0, y0).shape" 154 | ] 155 | }, 156 | { 157 | "cell_type": "code", 158 | "execution_count": null, 159 | "metadata": {}, 160 | "outputs": [], 161 | "source": [ 162 | "%debug ydot(t0, y0)" 163 | ] 164 | }, 165 | { 166 | "cell_type": "code", 167 | "execution_count": null, 168 | "metadata": {}, 169 | "outputs": [], 170 | "source": [ 171 | "y0 = np.array([get_posvel(body, t0) for body in bodies]).flatten()" 172 | ] 173 | }, 174 | { 175 | "cell_type": "code", 176 | "execution_count": null, 177 | "metadata": {}, 178 | "outputs": [], 179 | "source": [ 180 | "y0.shape" 181 | ] 182 | }, 183 | { 184 | "cell_type": "code", 185 | "execution_count": null, 186 | "metadata": {}, 187 | "outputs": [], 188 | "source": [ 189 | "ydot(t0, y0)" 190 | ] 191 | }, 192 | { 193 | "cell_type": "code", 194 | "execution_count": null, 195 | "metadata": {}, 196 | "outputs": [], 197 | "source": [ 198 | "%debug" 199 | ] 200 | }, 201 | { 202 | "cell_type": "code", 203 | "execution_count": null, 204 | "metadata": {}, 205 | "outputs": [], 206 | "source": [ 207 | "G = astropy.constants.G.to('AU^3 / (Msun d^2)').value" 208 | ] 209 | }, 210 | { 211 | "cell_type": "code", 212 | "execution_count": null, 213 | "metadata": {}, 214 | "outputs": [], 215 | "source": [ 216 | "ydot(t0, y0)" 217 | ] 218 | }, 219 | { 220 | "cell_type": "code", 221 | "execution_count": null, 222 | "metadata": {}, 223 | "outputs": [], 224 | "source": [ 225 | "orbits = scipy.integrate.solve_ivp(ydot, [t0.mjd, t1.mjd], y0, rtol=1e-9, atol=1e-9)" 226 | ] 227 | }, 228 | { 229 | "cell_type": "code", 230 | "execution_count": null, 231 | "metadata": {}, 232 | "outputs": [], 233 | "source": [ 234 | "for i in range(9):\n", 235 | " pp.plot(orbits.y[i*6,:], orbits.y[i*6+1,:], label=bodies[i])\n", 236 | "\n", 237 | "pp.legend()\n", 238 | "pp.axis('equal');" 239 | ] 240 | }, 241 | { 242 | "cell_type": "code", 243 | "execution_count": null, 244 | "metadata": {}, 245 | "outputs": [], 246 | "source": [ 247 | "pp.plot(orbits.y[5*6,:], orbits.y[5*6+1,:])\n", 248 | "pp.axis('equal');" 249 | ] 250 | }, 251 | { 252 | "cell_type": "code", 253 | "execution_count": null, 254 | "metadata": {}, 255 | "outputs": [], 256 | "source": [ 257 | "def ydot(t, y):\n", 258 | " # how many bodies? make sure the answer is an integer\n", 259 | " n = int(y.shape[0] / 6)\n", 260 | "\n", 261 | " # make an empty container for the derivatives\n", 262 | " yd = np.zeros_like(y)\n", 263 | " \n", 264 | " # for each body\n", 265 | " for i in range(n):\n", 266 | " # set x_i' = v_i (array slice assignment)\n", 267 | " yd[i*6:i*6+3] = y[i*6+3:i*6+6]\n", 268 | " \n", 269 | " # loop over all other bodies\n", 270 | " for j in range(n):\n", 271 | " if i == j:\n", 272 | " continue\n", 273 | "\n", 274 | " # add contribution of planet j to v_i'\n", 275 | " rij = y[j*6:j*6+3] - y[i*6:i*6+3]\n", 276 | " yd[i*6+3:i*6+6] += G * masses[j] * rij / np.dot(rij,rij)\n", 277 | " \n", 278 | " return yd" 279 | ] 280 | }, 281 | { 282 | "cell_type": "code", 283 | "execution_count": null, 284 | "metadata": {}, 285 | "outputs": [], 286 | "source": [ 287 | "%debug ydot(t0, y0)" 288 | ] 289 | }, 290 | { 291 | "cell_type": "code", 292 | "execution_count": null, 293 | "metadata": {}, 294 | "outputs": [], 295 | "source": [ 296 | "def ydot(t, y):\n", 297 | " # how many bodies? make sure the answer is an integer\n", 298 | " n = int(y.shape[0] / 6)\n", 299 | "\n", 300 | " # make an empty container for the derivatives\n", 301 | " yd = np.zeros_like(y)\n", 302 | " \n", 303 | " # for each body\n", 304 | " for i in range(n):\n", 305 | " # set x_i' = v_i (array slice assignment)\n", 306 | " yd[i*6:i*6+3] = y[i*6+3:i*6+6]\n", 307 | " \n", 308 | " # loop over all other bodies\n", 309 | " for j in range(n):\n", 310 | " if i == j:\n", 311 | " continue\n", 312 | "\n", 313 | " # add contribution of planet j to v_i'\n", 314 | " rij = y[j*6:j*6+3] - y[i*6:i*6+3]\n", 315 | " yd[i*6+3:i*6+6] += G * masses[j] * rij / np.dot(rij,rij)**1.5\n", 316 | " \n", 317 | " return yd" 318 | ] 319 | }, 320 | { 321 | "cell_type": "code", 322 | "execution_count": null, 323 | "metadata": {}, 324 | "outputs": [], 325 | "source": [ 326 | "orbits = scipy.integrate.solve_ivp(ydot, [t0.mjd, t1.mjd], y0, rtol=1e-9, atol=1e-9)" 327 | ] 328 | }, 329 | { 330 | "cell_type": "code", 331 | "execution_count": null, 332 | "metadata": {}, 333 | "outputs": [], 334 | "source": [ 335 | "for i in range(9):\n", 336 | " pp.plot(orbits.y[i*6,:], orbits.y[i*6+1,:], label=bodies[i])\n", 337 | "\n", 338 | "pp.legend()\n", 339 | "pp.axis('equal');" 340 | ] 341 | } 342 | ], 343 | "metadata": { 344 | "kernelspec": { 345 | "display_name": "Python 3", 346 | "language": "python", 347 | "name": "python3" 348 | }, 349 | "language_info": { 350 | "codemirror_mode": { 351 | "name": "ipython", 352 | "version": 3 353 | }, 354 | "file_extension": ".py", 355 | "mimetype": "text/x-python", 356 | "name": "python", 357 | "nbconvert_exporter": "python", 358 | "pygments_lexer": "ipython3", 359 | "version": "3.8.8" 360 | }, 361 | "toc": { 362 | "base_numbering": 1, 363 | "nav_menu": {}, 364 | "number_sections": true, 365 | "sideBar": true, 366 | "skip_h1_title": false, 367 | "title_cell": "Table of Contents", 368 | "title_sidebar": "Contents", 369 | "toc_cell": false, 370 | "toc_position": {}, 371 | "toc_section_display": true, 372 | "toc_window_display": false 373 | } 374 | }, 375 | "nbformat": 4, 376 | "nbformat_minor": 4 377 | } 378 | -------------------------------------------------------------------------------- /Ch03/03_07_challenge-complete.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 03_07_challenge - Planetary conjunctions" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 1, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "import numpy as np\n", 17 | "import matplotlib.pyplot as pp\n", 18 | "\n", 19 | "import numba\n", 20 | "\n", 21 | "import astropy.constants\n", 22 | "import astropy.time\n", 23 | "import astropy.coordinates\n", 24 | "\n", 25 | "import scipy.integrate\n", 26 | "import scipy.interpolate\n", 27 | "import scipy.optimize" 28 | ] 29 | }, 30 | { 31 | "cell_type": "code", 32 | "execution_count": 2, 33 | "metadata": {}, 34 | "outputs": [], 35 | "source": [ 36 | "bodies = ['sun','mercury','venus','earth','mars','jupiter','saturn','uranus','neptune']\n", 37 | "\n", 38 | "massdict = {'sun': 1.0,\n", 39 | " 'mercury': 1.6601209949637026e-07,\n", 40 | " 'venus': 2.4478382857373332e-06,\n", 41 | " 'earth': 3.0034896946063695e-06,\n", 42 | " 'mars': 3.227156037857755e-07,\n", 43 | " 'jupiter': 0.0009547918983127075,\n", 44 | " 'saturn': 0.00028588567008942334,\n", 45 | " 'uranus': 4.3662495719438076e-05,\n", 46 | " 'neptune': 5.151383713179197e-05}\n", 47 | "\n", 48 | "masses = np.array([massdict[body] for body in bodies])" 49 | ] 50 | }, 51 | { 52 | "cell_type": "code", 53 | "execution_count": 3, 54 | "metadata": {}, 55 | "outputs": [], 56 | "source": [ 57 | "G = astropy.constants.G.to('AU^3 / (Msun d^2)').value" 58 | ] 59 | }, 60 | { 61 | "cell_type": "code", 62 | "execution_count": 4, 63 | "metadata": {}, 64 | "outputs": [], 65 | "source": [ 66 | "@numba.jit\n", 67 | "def ydot(t, y):\n", 68 | " # how many bodies? make sure the answer is an integer\n", 69 | " n = int(y.shape[0] / 6)\n", 70 | "\n", 71 | " # make an empty container for the derivatives\n", 72 | " yd = np.zeros_like(y)\n", 73 | " \n", 74 | " # for each body\n", 75 | " for i in range(n):\n", 76 | " # set x_i' = v_i (array slice assignment)\n", 77 | " yd[i*6:i*6+3] = y[i*6+3:i*6+6]\n", 78 | " \n", 79 | " # loop over all other bodies\n", 80 | " for j in range(n):\n", 81 | " if i == j:\n", 82 | " continue\n", 83 | "\n", 84 | " # add contribution of planet j to v_i'\n", 85 | " rij = y[j*6:j*6+3] - y[i*6:i*6+3]\n", 86 | " yd[i*6+3:i*6+6] += G * masses[j] * rij / np.dot(rij,rij)**1.5\n", 87 | " \n", 88 | " return yd" 89 | ] 90 | }, 91 | { 92 | "cell_type": "code", 93 | "execution_count": 5, 94 | "metadata": {}, 95 | "outputs": [], 96 | "source": [ 97 | "def get_posvel(body, t):\n", 98 | " posvel = astropy.coordinates.get_body_barycentric_posvel(body, t)\n", 99 | " \n", 100 | " return np.hstack([posvel[0].xyz.value.T, posvel[1].xyz.value.T])" 101 | ] 102 | }, 103 | { 104 | "cell_type": "code", 105 | "execution_count": 6, 106 | "metadata": {}, 107 | "outputs": [ 108 | { 109 | "name": "stderr", 110 | "output_type": "stream", 111 | "text": [ 112 | "/Users/mvallisneri/opt/anaconda3/lib/python3.8/site-packages/erfa/core.py:154: ErfaWarning: ERFA function \"dtf2d\" yielded 1 of \"dubious year (Note 6)\"\n", 113 | " warnings.warn('ERFA function \"{}\" yielded {}'.format(func_name, wmsg),\n" 114 | ] 115 | } 116 | ], 117 | "source": [ 118 | "t0, t1 = astropy.time.Time('2021-07-04'), astropy.time.Time('2031-07-04')" 119 | ] 120 | }, 121 | { 122 | "cell_type": "code", 123 | "execution_count": 7, 124 | "metadata": {}, 125 | "outputs": [], 126 | "source": [ 127 | "y0 = np.array([get_posvel(body, t0) for body in bodies]).flatten()" 128 | ] 129 | }, 130 | { 131 | "cell_type": "code", 132 | "execution_count": 8, 133 | "metadata": {}, 134 | "outputs": [], 135 | "source": [ 136 | "def get_orbits(y):\n", 137 | " return scipy.integrate.solve_ivp(ydot, [t0.mjd, t1.mjd], y, rtol=1e-9, atol=1e-9)" 138 | ] 139 | }, 140 | { 141 | "cell_type": "code", 142 | "execution_count": 9, 143 | "metadata": {}, 144 | "outputs": [], 145 | "source": [ 146 | "orbits = get_orbits(y0)" 147 | ] 148 | }, 149 | { 150 | "cell_type": "code", 151 | "execution_count": 10, 152 | "metadata": {}, 153 | "outputs": [], 154 | "source": [ 155 | "orbint = scipy.interpolate.interp1d(orbits.t, orbits.y)" 156 | ] 157 | }, 158 | { 159 | "cell_type": "code", 160 | "execution_count": null, 161 | "metadata": {}, 162 | "outputs": [], 163 | "source": [] 164 | } 165 | ], 166 | "metadata": { 167 | "kernelspec": { 168 | "display_name": "Python 3", 169 | "language": "python", 170 | "name": "python3" 171 | }, 172 | "language_info": { 173 | "codemirror_mode": { 174 | "name": "ipython", 175 | "version": 3 176 | }, 177 | "file_extension": ".py", 178 | "mimetype": "text/x-python", 179 | "name": "python", 180 | "nbconvert_exporter": "python", 181 | "pygments_lexer": "ipython3", 182 | "version": "3.8.8" 183 | }, 184 | "toc": { 185 | "base_numbering": 1, 186 | "nav_menu": {}, 187 | "number_sections": true, 188 | "sideBar": true, 189 | "skip_h1_title": false, 190 | "title_cell": "Table of Contents", 191 | "title_sidebar": "Contents", 192 | "toc_cell": false, 193 | "toc_position": {}, 194 | "toc_section_display": true, 195 | "toc_window_display": false 196 | } 197 | }, 198 | "nbformat": 4, 199 | "nbformat_minor": 4 200 | } 201 | -------------------------------------------------------------------------------- /Ch03/03_07_challenge.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 03_07_challenge - Planetary conjunctions" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "import numpy as np\n", 17 | "import matplotlib.pyplot as pp\n", 18 | "\n", 19 | "import numba\n", 20 | "\n", 21 | "import astropy.constants\n", 22 | "import astropy.time\n", 23 | "import astropy.coordinates\n", 24 | "\n", 25 | "import scipy.integrate\n", 26 | "import scipy.interpolate\n", 27 | "import scipy.optimize" 28 | ] 29 | }, 30 | { 31 | "cell_type": "code", 32 | "execution_count": null, 33 | "metadata": {}, 34 | "outputs": [], 35 | "source": [ 36 | "bodies = ['sun','mercury','venus','earth','mars','jupiter','saturn','uranus','neptune']\n", 37 | "\n", 38 | "massdict = {'sun': 1.0,\n", 39 | " 'mercury': 1.6601209949637026e-07,\n", 40 | " 'venus': 2.4478382857373332e-06,\n", 41 | " 'earth': 3.0034896946063695e-06,\n", 42 | " 'mars': 3.227156037857755e-07,\n", 43 | " 'jupiter': 0.0009547918983127075,\n", 44 | " 'saturn': 0.00028588567008942334,\n", 45 | " 'uranus': 4.3662495719438076e-05,\n", 46 | " 'neptune': 5.151383713179197e-05}\n", 47 | "\n", 48 | "masses = np.array([massdict[body] for body in bodies])" 49 | ] 50 | }, 51 | { 52 | "cell_type": "code", 53 | "execution_count": null, 54 | "metadata": {}, 55 | "outputs": [], 56 | "source": [ 57 | "G = astropy.constants.G.to('AU^3 / (Msun d^2)').value" 58 | ] 59 | }, 60 | { 61 | "cell_type": "code", 62 | "execution_count": null, 63 | "metadata": {}, 64 | "outputs": [], 65 | "source": [ 66 | "@numba.jit\n", 67 | "def ydot(t, y):\n", 68 | " # how many bodies? make sure the answer is an integer\n", 69 | " n = int(y.shape[0] / 6)\n", 70 | "\n", 71 | " # make an empty container for the derivatives\n", 72 | " yd = np.zeros_like(y)\n", 73 | " \n", 74 | " # for each body\n", 75 | " for i in range(n):\n", 76 | " # set x_i' = v_i (array slice assignment)\n", 77 | " yd[i*6:i*6+3] = y[i*6+3:i*6+6]\n", 78 | " \n", 79 | " # loop over all other bodies\n", 80 | " for j in range(n):\n", 81 | " if i == j:\n", 82 | " continue\n", 83 | "\n", 84 | " # add contribution of planet j to v_i'\n", 85 | " rij = y[j*6:j*6+3] - y[i*6:i*6+3]\n", 86 | " yd[i*6+3:i*6+6] += G * masses[j] * rij / np.dot(rij,rij)**1.5\n", 87 | " \n", 88 | " return yd" 89 | ] 90 | }, 91 | { 92 | "cell_type": "code", 93 | "execution_count": null, 94 | "metadata": {}, 95 | "outputs": [], 96 | "source": [ 97 | "def get_posvel(body, t):\n", 98 | " posvel = astropy.coordinates.get_body_barycentric_posvel(body, t)\n", 99 | " \n", 100 | " return np.hstack([posvel[0].xyz.value.T, posvel[1].xyz.value.T])" 101 | ] 102 | }, 103 | { 104 | "cell_type": "code", 105 | "execution_count": null, 106 | "metadata": {}, 107 | "outputs": [], 108 | "source": [ 109 | "t0, t1 = astropy.time.Time('2021-07-04'), astropy.time.Time('2031-07-04')" 110 | ] 111 | }, 112 | { 113 | "cell_type": "code", 114 | "execution_count": null, 115 | "metadata": {}, 116 | "outputs": [], 117 | "source": [ 118 | "y0 = np.array([get_posvel(body, t0) for body in bodies]).flatten()" 119 | ] 120 | }, 121 | { 122 | "cell_type": "code", 123 | "execution_count": null, 124 | "metadata": {}, 125 | "outputs": [], 126 | "source": [ 127 | "def get_orbits(y):\n", 128 | " return scipy.integrate.solve_ivp(ydot, [t0.mjd, t1.mjd], y, rtol=1e-9, atol=1e-9)" 129 | ] 130 | }, 131 | { 132 | "cell_type": "code", 133 | "execution_count": null, 134 | "metadata": {}, 135 | "outputs": [], 136 | "source": [ 137 | "orbits = get_orbits(y0)" 138 | ] 139 | }, 140 | { 141 | "cell_type": "code", 142 | "execution_count": null, 143 | "metadata": {}, 144 | "outputs": [], 145 | "source": [ 146 | "orbint = scipy.interpolate.interp1d(orbits.t, orbits.y)" 147 | ] 148 | }, 149 | { 150 | "cell_type": "code", 151 | "execution_count": null, 152 | "metadata": {}, 153 | "outputs": [], 154 | "source": [] 155 | } 156 | ], 157 | "metadata": { 158 | "kernelspec": { 159 | "display_name": "Python 3", 160 | "language": "python", 161 | "name": "python3" 162 | }, 163 | "language_info": { 164 | "codemirror_mode": { 165 | "name": "ipython", 166 | "version": 3 167 | }, 168 | "file_extension": ".py", 169 | "mimetype": "text/x-python", 170 | "name": "python", 171 | "nbconvert_exporter": "python", 172 | "pygments_lexer": "ipython3", 173 | "version": "3.8.8" 174 | }, 175 | "toc": { 176 | "base_numbering": 1, 177 | "nav_menu": {}, 178 | "number_sections": true, 179 | "sideBar": true, 180 | "skip_h1_title": false, 181 | "title_cell": "Table of Contents", 182 | "title_sidebar": "Contents", 183 | "toc_cell": false, 184 | "toc_position": {}, 185 | "toc_section_display": true, 186 | "toc_window_display": false 187 | } 188 | }, 189 | "nbformat": 4, 190 | "nbformat_minor": 4 191 | } 192 | -------------------------------------------------------------------------------- /Ch03/03_08_solution.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 03_08_solution - Planetary conjunctions" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "#### Solar-System integrator from this chapter" 15 | ] 16 | }, 17 | { 18 | "cell_type": "code", 19 | "execution_count": null, 20 | "metadata": {}, 21 | "outputs": [], 22 | "source": [ 23 | "import numpy as np\n", 24 | "import matplotlib.pyplot as pp\n", 25 | "\n", 26 | "import numba\n", 27 | "\n", 28 | "import astropy.constants\n", 29 | "import astropy.time\n", 30 | "import astropy.coordinates\n", 31 | "\n", 32 | "import scipy.integrate\n", 33 | "import scipy.interpolate\n", 34 | "import scipy.optimize" 35 | ] 36 | }, 37 | { 38 | "cell_type": "code", 39 | "execution_count": null, 40 | "metadata": {}, 41 | "outputs": [], 42 | "source": [ 43 | "bodies = ['sun','mercury','venus','earth','mars','jupiter','saturn','uranus','neptune']\n", 44 | "\n", 45 | "massdict = {'sun': 1.0,\n", 46 | " 'mercury': 1.6601209949637026e-07,\n", 47 | " 'venus': 2.4478382857373332e-06,\n", 48 | " 'earth': 3.0034896946063695e-06,\n", 49 | " 'mars': 3.227156037857755e-07,\n", 50 | " 'jupiter': 0.0009547918983127075,\n", 51 | " 'saturn': 0.00028588567008942334,\n", 52 | " 'uranus': 4.3662495719438076e-05,\n", 53 | " 'neptune': 5.151383713179197e-05}\n", 54 | "\n", 55 | "masses = np.array([massdict[body] for body in bodies])" 56 | ] 57 | }, 58 | { 59 | "cell_type": "code", 60 | "execution_count": null, 61 | "metadata": {}, 62 | "outputs": [], 63 | "source": [ 64 | "G = astropy.constants.G.to('AU^3 / (Msun d^2)').value" 65 | ] 66 | }, 67 | { 68 | "cell_type": "code", 69 | "execution_count": null, 70 | "metadata": {}, 71 | "outputs": [], 72 | "source": [ 73 | "@numba.jit\n", 74 | "def ydot(t, y):\n", 75 | " # how many bodies? make sure the answer is an integer\n", 76 | " n = int(y.shape[0] / 6)\n", 77 | "\n", 78 | " # make an empty container for the derivatives\n", 79 | " yd = np.zeros_like(y)\n", 80 | " \n", 81 | " # for each body\n", 82 | " for i in range(n):\n", 83 | " # set x_i' = v_i (array slice assignment)\n", 84 | " yd[i*6:i*6+3] = y[i*6+3:i*6+6]\n", 85 | " \n", 86 | " # loop over all other bodies\n", 87 | " for j in range(n):\n", 88 | " if i == j:\n", 89 | " continue\n", 90 | "\n", 91 | " # add contribution of planet j to v_i'\n", 92 | " rij = y[j*6:j*6+3] - y[i*6:i*6+3]\n", 93 | " yd[i*6+3:i*6+6] += G * masses[j] * rij / np.dot(rij,rij)**1.5\n", 94 | " \n", 95 | " return yd" 96 | ] 97 | }, 98 | { 99 | "cell_type": "code", 100 | "execution_count": null, 101 | "metadata": {}, 102 | "outputs": [], 103 | "source": [ 104 | "def get_posvel(body, t):\n", 105 | " posvel = astropy.coordinates.get_body_barycentric_posvel(body, t)\n", 106 | " \n", 107 | " return np.hstack([posvel[0].xyz.value.T, posvel[1].xyz.value.T])" 108 | ] 109 | }, 110 | { 111 | "cell_type": "code", 112 | "execution_count": null, 113 | "metadata": {}, 114 | "outputs": [], 115 | "source": [ 116 | "t0, t1 = astropy.time.Time('2021-07-04'), astropy.time.Time('2031-07-04')" 117 | ] 118 | }, 119 | { 120 | "cell_type": "code", 121 | "execution_count": null, 122 | "metadata": {}, 123 | "outputs": [], 124 | "source": [ 125 | "y0 = np.array([get_posvel(body, t0) for body in bodies]).flatten()" 126 | ] 127 | }, 128 | { 129 | "cell_type": "code", 130 | "execution_count": null, 131 | "metadata": {}, 132 | "outputs": [], 133 | "source": [ 134 | "def get_orbits(y):\n", 135 | " return scipy.integrate.solve_ivp(ydot, [t0.mjd, t1.mjd], y, rtol=1e-9, atol=1e-9)" 136 | ] 137 | }, 138 | { 139 | "cell_type": "code", 140 | "execution_count": null, 141 | "metadata": {}, 142 | "outputs": [], 143 | "source": [ 144 | "orbits = get_orbits(y0)" 145 | ] 146 | }, 147 | { 148 | "cell_type": "code", 149 | "execution_count": null, 150 | "metadata": {}, 151 | "outputs": [], 152 | "source": [ 153 | "orbint = scipy.interpolate.interp1d(orbits.t, orbits.y)" 154 | ] 155 | }, 156 | { 157 | "cell_type": "markdown", 158 | "metadata": {}, 159 | "source": [ 160 | "#### Solution" 161 | ] 162 | }, 163 | { 164 | "cell_type": "code", 165 | "execution_count": null, 166 | "metadata": {}, 167 | "outputs": [], 168 | "source": [ 169 | "def get_cos(t, body1, body2, orbint):\n", 170 | " y = orbint(t)\n", 171 | " \n", 172 | " i, j, k = bodies.index(body1), bodies.index(body2), bodies.index('earth')\n", 173 | " \n", 174 | " ri = y[i*6:i*6+3] - y[k*6:k*6+3]\n", 175 | " rj = y[j*6:j*6+3] - y[k*6:k*6+3]\n", 176 | " \n", 177 | " ijdot = np.sum(ri * rj, axis=0)\n", 178 | " inorm = np.sqrt(np.sum(ri * ri, axis=0))\n", 179 | " jnorm = np.sqrt(np.sum(rj * rj, axis=0))\n", 180 | " \n", 181 | " return ijdot / inorm / jnorm" 182 | ] 183 | }, 184 | { 185 | "cell_type": "code", 186 | "execution_count": null, 187 | "metadata": {}, 188 | "outputs": [], 189 | "source": [ 190 | "ts = np.linspace(t0.mjd, t1.mjd, 1000)" 191 | ] 192 | }, 193 | { 194 | "cell_type": "code", 195 | "execution_count": null, 196 | "metadata": {}, 197 | "outputs": [], 198 | "source": [ 199 | "pp.plot(ts, get_cos(ts, 'mars', 'saturn', orbint))\n", 200 | "pp.axhline(1,ls=':')" 201 | ] 202 | }, 203 | { 204 | "cell_type": "code", 205 | "execution_count": null, 206 | "metadata": {}, 207 | "outputs": [], 208 | "source": [ 209 | "def get_max(tinit):\n", 210 | " minimum = scipy.optimize.minimize(lambda t: -get_cos(t, 'mars', 'saturn', orbint),\n", 211 | " x0=tinit, bounds=[(t0.mjd, t1.mjd)])\n", 212 | " \n", 213 | " return int(minimum.x)" 214 | ] 215 | }, 216 | { 217 | "cell_type": "code", 218 | "execution_count": null, 219 | "metadata": {}, 220 | "outputs": [], 221 | "source": [ 222 | "print([get_max(t) for t in range(59500, 63000, 50)])" 223 | ] 224 | }, 225 | { 226 | "cell_type": "code", 227 | "execution_count": null, 228 | "metadata": {}, 229 | "outputs": [], 230 | "source": [ 231 | "times = list(set(get_max(t) for t in range(59500, 63000, 50)))" 232 | ] 233 | }, 234 | { 235 | "cell_type": "code", 236 | "execution_count": null, 237 | "metadata": {}, 238 | "outputs": [], 239 | "source": [ 240 | "times" 241 | ] 242 | }, 243 | { 244 | "cell_type": "code", 245 | "execution_count": null, 246 | "metadata": {}, 247 | "outputs": [], 248 | "source": [ 249 | "pp.plot(ts, get_cos(ts, 'mars', 'saturn', orbint))\n", 250 | "pp.plot(list(times),\n", 251 | " get_cos(list(times), 'mars', 'saturn', orbint), 'ro')" 252 | ] 253 | }, 254 | { 255 | "cell_type": "code", 256 | "execution_count": null, 257 | "metadata": {}, 258 | "outputs": [], 259 | "source": [ 260 | "conjunctions = [t for t in times if get_cos(t, 'mars', 'saturn', orbint) > 0.99]" 261 | ] 262 | }, 263 | { 264 | "cell_type": "code", 265 | "execution_count": null, 266 | "metadata": {}, 267 | "outputs": [], 268 | "source": [ 269 | "pp.plot(ts, get_cos(ts, 'mars', 'saturn', orbint))\n", 270 | "pp.plot(conjunctions, get_cos(list(conjunctions), 'mars', 'saturn', orbint), 'ro')" 271 | ] 272 | }, 273 | { 274 | "cell_type": "code", 275 | "execution_count": null, 276 | "metadata": {}, 277 | "outputs": [], 278 | "source": [ 279 | "[astropy.time.Time(t, format='mjd').iso for t in conjunctions]" 280 | ] 281 | } 282 | ], 283 | "metadata": { 284 | "kernelspec": { 285 | "display_name": "Python 3", 286 | "language": "python", 287 | "name": "python3" 288 | }, 289 | "language_info": { 290 | "codemirror_mode": { 291 | "name": "ipython", 292 | "version": 3 293 | }, 294 | "file_extension": ".py", 295 | "mimetype": "text/x-python", 296 | "name": "python", 297 | "nbconvert_exporter": "python", 298 | "pygments_lexer": "ipython3", 299 | "version": "3.8.8" 300 | }, 301 | "toc": { 302 | "base_numbering": 1, 303 | "nav_menu": {}, 304 | "number_sections": true, 305 | "sideBar": true, 306 | "skip_h1_title": false, 307 | "title_cell": "Table of Contents", 308 | "title_sidebar": "Contents", 309 | "toc_cell": false, 310 | "toc_position": {}, 311 | "toc_section_display": true, 312 | "toc_window_display": false 313 | } 314 | }, 315 | "nbformat": 4, 316 | "nbformat_minor": 4 317 | } 318 | -------------------------------------------------------------------------------- /Ch04/04_02_web.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 04_02_web.ipynb - Web resources with requests and JSON" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "import json\n", 17 | "import os\n", 18 | "\n", 19 | "import requests" 20 | ] 21 | }, 22 | { 23 | "cell_type": "code", 24 | "execution_count": null, 25 | "metadata": {}, 26 | "outputs": [], 27 | "source": [ 28 | "r = requests.get('https://www.gw-openscience.org/eventapi/json/GWTC-1-confident/GW150914/v3')" 29 | ] 30 | }, 31 | { 32 | "cell_type": "code", 33 | "execution_count": null, 34 | "metadata": {}, 35 | "outputs": [], 36 | "source": [ 37 | "r" 38 | ] 39 | }, 40 | { 41 | "cell_type": "code", 42 | "execution_count": null, 43 | "metadata": {}, 44 | "outputs": [], 45 | "source": [ 46 | "# if requests.get fails for network problems\n", 47 | "# you can use the cached version in the exercise files:\n", 48 | "# import pickle\n", 49 | "# r = pickle.load(open('cache/GW150914-v3.pickle', 'rb'))" 50 | ] 51 | }, 52 | { 53 | "cell_type": "code", 54 | "execution_count": null, 55 | "metadata": {}, 56 | "outputs": [], 57 | "source": [ 58 | "r.ok" 59 | ] 60 | }, 61 | { 62 | "cell_type": "code", 63 | "execution_count": null, 64 | "metadata": {}, 65 | "outputs": [], 66 | "source": [ 67 | "r.content" 68 | ] 69 | }, 70 | { 71 | "cell_type": "code", 72 | "execution_count": null, 73 | "metadata": {}, 74 | "outputs": [], 75 | "source": [ 76 | "print(r.text)" 77 | ] 78 | }, 79 | { 80 | "cell_type": "code", 81 | "execution_count": null, 82 | "metadata": {}, 83 | "outputs": [], 84 | "source": [ 85 | "jsondict = json.loads(r.text)" 86 | ] 87 | }, 88 | { 89 | "cell_type": "code", 90 | "execution_count": null, 91 | "metadata": {}, 92 | "outputs": [], 93 | "source": [ 94 | "jsondict['events']['GW150914-v3']" 95 | ] 96 | }, 97 | { 98 | "cell_type": "code", 99 | "execution_count": null, 100 | "metadata": {}, 101 | "outputs": [], 102 | "source": [ 103 | "jsondict['events']['GW150914-v3']['mass_1_source'], jsondict['events']['GW150914-v3']['mass_2_source']" 104 | ] 105 | }, 106 | { 107 | "cell_type": "code", 108 | "execution_count": null, 109 | "metadata": {}, 110 | "outputs": [], 111 | "source": [ 112 | "jsondict['events']['GW150914-v3']['strain']" 113 | ] 114 | }, 115 | { 116 | "cell_type": "code", 117 | "execution_count": null, 118 | "metadata": {}, 119 | "outputs": [], 120 | "source": [ 121 | "hdffiles = [file['url'] for file in jsondict['events']['GW150914-v3']['strain']\n", 122 | " if file['duration'] == 32 and file['sampling_rate'] == 4096\n", 123 | " and file['format'] == 'hdf5']" 124 | ] 125 | }, 126 | { 127 | "cell_type": "code", 128 | "execution_count": null, 129 | "metadata": {}, 130 | "outputs": [], 131 | "source": [ 132 | "hdffiles" 133 | ] 134 | }, 135 | { 136 | "cell_type": "code", 137 | "execution_count": null, 138 | "metadata": {}, 139 | "outputs": [], 140 | "source": [ 141 | "def dump(url, filename):\n", 142 | " r = requests.get(url)\n", 143 | " \n", 144 | " with open(filename, 'wb') as outfile:\n", 145 | " outfile.write(r.content)" 146 | ] 147 | }, 148 | { 149 | "cell_type": "code", 150 | "execution_count": null, 151 | "metadata": {}, 152 | "outputs": [], 153 | "source": [ 154 | "for hdffile in hdffiles:\n", 155 | " dump(hdffile, os.path.basename(hdffile))" 156 | ] 157 | }, 158 | { 159 | "cell_type": "code", 160 | "execution_count": null, 161 | "metadata": {}, 162 | "outputs": [], 163 | "source": [ 164 | "# in case of network trouble, copies of these files can be found in the folder \"cache\"" 165 | ] 166 | }, 167 | { 168 | "cell_type": "code", 169 | "execution_count": null, 170 | "metadata": {}, 171 | "outputs": [], 172 | "source": [ 173 | "r = requests.get('https://www.gw-openscience.org/eventapi/json/query/show',\n", 174 | " params={'min-mass-1-source': 50, 'min-mass-2-source': 30})" 175 | ] 176 | }, 177 | { 178 | "cell_type": "code", 179 | "execution_count": null, 180 | "metadata": {}, 181 | "outputs": [], 182 | "source": [ 183 | "json.loads(r.text)" 184 | ] 185 | } 186 | ], 187 | "metadata": { 188 | "kernelspec": { 189 | "display_name": "Python 3", 190 | "language": "python", 191 | "name": "python3" 192 | }, 193 | "language_info": { 194 | "codemirror_mode": { 195 | "name": "ipython", 196 | "version": 3 197 | }, 198 | "file_extension": ".py", 199 | "mimetype": "text/x-python", 200 | "name": "python", 201 | "nbconvert_exporter": "python", 202 | "pygments_lexer": "ipython3", 203 | "version": "3.8.8" 204 | }, 205 | "toc": { 206 | "base_numbering": 1, 207 | "nav_menu": {}, 208 | "number_sections": true, 209 | "sideBar": true, 210 | "skip_h1_title": false, 211 | "title_cell": "Table of Contents", 212 | "title_sidebar": "Contents", 213 | "toc_cell": false, 214 | "toc_position": {}, 215 | "toc_section_display": true, 216 | "toc_window_display": false 217 | } 218 | }, 219 | "nbformat": 4, 220 | "nbformat_minor": 4 221 | } 222 | -------------------------------------------------------------------------------- /Ch04/04_03_pandas.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 04_03_pandas.ipynb - Data tables with Pandas" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "import requests\n", 17 | "\n", 18 | "import numpy as np\n", 19 | "import matplotlib.pyplot as pp\n", 20 | "import pandas as pd\n", 21 | "import astropy.units" 22 | ] 23 | }, 24 | { 25 | "cell_type": "code", 26 | "execution_count": null, 27 | "metadata": {}, 28 | "outputs": [], 29 | "source": [ 30 | "# utility function from the last video\n", 31 | "\n", 32 | "def dump(url, filename):\n", 33 | " r = requests.get(url)\n", 34 | " \n", 35 | " with open(filename, 'wb') as outfile:\n", 36 | " outfile.write(r.content)" 37 | ] 38 | }, 39 | { 40 | "cell_type": "code", 41 | "execution_count": null, 42 | "metadata": {}, 43 | "outputs": [], 44 | "source": [ 45 | "# in case of network problems, you can use the file cache/gwtc-20210726.csv\n", 46 | "dump('https://www.gw-openscience.org/eventapi/csv/GWTC', 'gwtc.csv')" 47 | ] 48 | }, 49 | { 50 | "cell_type": "code", 51 | "execution_count": null, 52 | "metadata": {}, 53 | "outputs": [], 54 | "source": [ 55 | "gwtc = pd.read_csv('gwtc.csv')" 56 | ] 57 | }, 58 | { 59 | "cell_type": "code", 60 | "execution_count": null, 61 | "metadata": {}, 62 | "outputs": [], 63 | "source": [ 64 | "gwtc" 65 | ] 66 | }, 67 | { 68 | "cell_type": "code", 69 | "execution_count": null, 70 | "metadata": {}, 71 | "outputs": [], 72 | "source": [ 73 | "gwtc.head()" 74 | ] 75 | }, 76 | { 77 | "cell_type": "code", 78 | "execution_count": null, 79 | "metadata": {}, 80 | "outputs": [], 81 | "source": [ 82 | "gwtc.info()" 83 | ] 84 | }, 85 | { 86 | "cell_type": "code", 87 | "execution_count": null, 88 | "metadata": {}, 89 | "outputs": [], 90 | "source": [ 91 | "gwtc.describe()" 92 | ] 93 | }, 94 | { 95 | "cell_type": "code", 96 | "execution_count": null, 97 | "metadata": {}, 98 | "outputs": [], 99 | "source": [ 100 | "gwtc_i = gwtc.set_index('id').sort_index()" 101 | ] 102 | }, 103 | { 104 | "cell_type": "code", 105 | "execution_count": null, 106 | "metadata": {}, 107 | "outputs": [], 108 | "source": [ 109 | "gwtc_i.head()" 110 | ] 111 | }, 112 | { 113 | "cell_type": "code", 114 | "execution_count": null, 115 | "metadata": {}, 116 | "outputs": [], 117 | "source": [ 118 | "gwtc_i.loc['GW150914-v3']" 119 | ] 120 | }, 121 | { 122 | "cell_type": "code", 123 | "execution_count": null, 124 | "metadata": {}, 125 | "outputs": [], 126 | "source": [ 127 | "gwtc_i.loc['GW150914-v3':'GW151226-v2']" 128 | ] 129 | }, 130 | { 131 | "cell_type": "code", 132 | "execution_count": null, 133 | "metadata": {}, 134 | "outputs": [], 135 | "source": [ 136 | "gwtc_i.luminosity_distance" 137 | ] 138 | }, 139 | { 140 | "cell_type": "code", 141 | "execution_count": null, 142 | "metadata": {}, 143 | "outputs": [], 144 | "source": [ 145 | "(gwtc_i.luminosity_distance.max() * astropy.units.Mpc).to('lightyear')" 146 | ] 147 | }, 148 | { 149 | "cell_type": "code", 150 | "execution_count": null, 151 | "metadata": { 152 | "scrolled": true 153 | }, 154 | "outputs": [], 155 | "source": [ 156 | "gwtc_i['total_mass_source']" 157 | ] 158 | }, 159 | { 160 | "cell_type": "code", 161 | "execution_count": null, 162 | "metadata": {}, 163 | "outputs": [], 164 | "source": [ 165 | "# gwtc_i['total_mass_source'] = gwtc_i['mass_1_source'] + gwtc_i['mass_2_source']" 166 | ] 167 | }, 168 | { 169 | "cell_type": "code", 170 | "execution_count": null, 171 | "metadata": {}, 172 | "outputs": [], 173 | "source": [ 174 | "missing = np.isnan(gwtc_i.total_mass_source)" 175 | ] 176 | }, 177 | { 178 | "cell_type": "code", 179 | "execution_count": null, 180 | "metadata": { 181 | "scrolled": true 182 | }, 183 | "outputs": [], 184 | "source": [ 185 | "missing" 186 | ] 187 | }, 188 | { 189 | "cell_type": "code", 190 | "execution_count": null, 191 | "metadata": {}, 192 | "outputs": [], 193 | "source": [ 194 | "gwtc_i.loc[missing, 'total_mass_source'] = (gwtc_i.loc[missing, 'mass_1_source'] +\n", 195 | " gwtc_i.loc[missing, 'mass_2_source'])" 196 | ] 197 | }, 198 | { 199 | "cell_type": "code", 200 | "execution_count": null, 201 | "metadata": { 202 | "scrolled": true 203 | }, 204 | "outputs": [], 205 | "source": [ 206 | "gwtc_i['total_mass_source']" 207 | ] 208 | }, 209 | { 210 | "cell_type": "code", 211 | "execution_count": null, 212 | "metadata": {}, 213 | "outputs": [], 214 | "source": [ 215 | "pp.plot(gwtc_i.total_mass_source, gwtc_i.luminosity_distance, '.')\n", 216 | "pp.xlabel('total mass (Msun)')\n", 217 | "pp.ylabel('luminosity distance (Mpc)')" 218 | ] 219 | }, 220 | { 221 | "cell_type": "code", 222 | "execution_count": null, 223 | "metadata": {}, 224 | "outputs": [], 225 | "source": [ 226 | "gwtc_i.plot.scatter('total_mass_source', 'luminosity_distance', s=50,\n", 227 | " figsize=(9,6))" 228 | ] 229 | }, 230 | { 231 | "cell_type": "code", 232 | "execution_count": null, 233 | "metadata": {}, 234 | "outputs": [], 235 | "source": [ 236 | "gwtc_i.plot.scatter('total_mass_source', 'luminosity_distance',\n", 237 | " s=gwtc['network_matched_filter_snr'] * 15, # some trial-and-error to set sizes just right\n", 238 | " linewidth=1, edgecolors='w', # a white contour helps tell spots apart\n", 239 | " c=gwtc['redshift'], colormap='plasma', # set colors using colormap \n", 240 | " sharex=False, # make sure x label does not disappear (thanks, stackoverflow.com)\n", 241 | " figsize=(10,6))" 242 | ] 243 | }, 244 | { 245 | "cell_type": "code", 246 | "execution_count": null, 247 | "metadata": {}, 248 | "outputs": [], 249 | "source": [ 250 | "gwtc_i.plot.scatter('mass_1_source', 'mass_2_source',\n", 251 | " s=gwtc['total_mass_source']*3,\n", 252 | " linewidth=1, edgecolors='w',\n", 253 | " c=gwtc['redshift'], colormap='plasma',\n", 254 | " sharex=False, figsize=(10,6))\n", 255 | "\n", 256 | "pp.plot([0,100],[0,100],'k:')\n", 257 | "pp.plot([0,100],[0,50],'k:')\n", 258 | "pp.plot([0,100],[0,20],'k:')\n", 259 | "\n", 260 | "pp.axis([0,100,0,100]);" 261 | ] 262 | } 263 | ], 264 | "metadata": { 265 | "kernelspec": { 266 | "display_name": "Python 3", 267 | "language": "python", 268 | "name": "python3" 269 | }, 270 | "language_info": { 271 | "codemirror_mode": { 272 | "name": "ipython", 273 | "version": 3 274 | }, 275 | "file_extension": ".py", 276 | "mimetype": "text/x-python", 277 | "name": "python", 278 | "nbconvert_exporter": "python", 279 | "pygments_lexer": "ipython3", 280 | "version": "3.8.8" 281 | }, 282 | "toc": { 283 | "base_numbering": 1, 284 | "nav_menu": {}, 285 | "number_sections": true, 286 | "sideBar": true, 287 | "skip_h1_title": false, 288 | "title_cell": "Table of Contents", 289 | "title_sidebar": "Contents", 290 | "toc_cell": false, 291 | "toc_position": {}, 292 | "toc_section_display": true, 293 | "toc_window_display": false 294 | } 295 | }, 296 | "nbformat": 4, 297 | "nbformat_minor": 4 298 | } 299 | -------------------------------------------------------------------------------- /Ch04/04_04_hdf5.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 04_04_hdf5.ipynb - Scientific datasets with HDF5 " 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "import numpy as np\n", 17 | "import scipy.interpolate\n", 18 | "import matplotlib.pyplot as pp\n", 19 | "import matplotlib.mlab as mlab\n", 20 | "\n", 21 | "import h5py" 22 | ] 23 | }, 24 | { 25 | "cell_type": "code", 26 | "execution_count": null, 27 | "metadata": {}, 28 | "outputs": [], 29 | "source": [ 30 | "# if you don't have the hdf5 files from 04_02_web, \n", 31 | "# you can find them in the folder cache\n", 32 | "h1file = h5py.File('H-H1_GWOSC_4KHZ_R1-1126259447-32.hdf5', 'r')" 33 | ] 34 | }, 35 | { 36 | "cell_type": "code", 37 | "execution_count": null, 38 | "metadata": {}, 39 | "outputs": [], 40 | "source": [ 41 | "h1file" 42 | ] 43 | }, 44 | { 45 | "cell_type": "code", 46 | "execution_count": null, 47 | "metadata": {}, 48 | "outputs": [], 49 | "source": [ 50 | "h1file.visititems(print)" 51 | ] 52 | }, 53 | { 54 | "cell_type": "code", 55 | "execution_count": null, 56 | "metadata": {}, 57 | "outputs": [], 58 | "source": [ 59 | "h1file.keys()" 60 | ] 61 | }, 62 | { 63 | "cell_type": "code", 64 | "execution_count": null, 65 | "metadata": {}, 66 | "outputs": [], 67 | "source": [ 68 | "h1file['meta']['Description'][()]" 69 | ] 70 | }, 71 | { 72 | "cell_type": "code", 73 | "execution_count": null, 74 | "metadata": {}, 75 | "outputs": [], 76 | "source": [ 77 | "h1file['meta/UTCstart'][()]" 78 | ] 79 | }, 80 | { 81 | "cell_type": "code", 82 | "execution_count": null, 83 | "metadata": {}, 84 | "outputs": [], 85 | "source": [ 86 | "h1file['meta/GPSstart'][()]" 87 | ] 88 | }, 89 | { 90 | "cell_type": "code", 91 | "execution_count": null, 92 | "metadata": {}, 93 | "outputs": [], 94 | "source": [ 95 | "h1strain = h1file['strain/Strain']" 96 | ] 97 | }, 98 | { 99 | "cell_type": "code", 100 | "execution_count": null, 101 | "metadata": {}, 102 | "outputs": [], 103 | "source": [ 104 | "h1strain" 105 | ] 106 | }, 107 | { 108 | "cell_type": "code", 109 | "execution_count": null, 110 | "metadata": {}, 111 | "outputs": [], 112 | "source": [ 113 | "h1strain[:10]" 114 | ] 115 | }, 116 | { 117 | "cell_type": "code", 118 | "execution_count": null, 119 | "metadata": {}, 120 | "outputs": [], 121 | "source": [ 122 | "h1attrs = h1file['strain/Strain'].attrs" 123 | ] 124 | }, 125 | { 126 | "cell_type": "code", 127 | "execution_count": null, 128 | "metadata": {}, 129 | "outputs": [], 130 | "source": [ 131 | "h1attrs" 132 | ] 133 | }, 134 | { 135 | "cell_type": "code", 136 | "execution_count": null, 137 | "metadata": {}, 138 | "outputs": [], 139 | "source": [ 140 | "dict(h1attrs)" 141 | ] 142 | }, 143 | { 144 | "cell_type": "code", 145 | "execution_count": null, 146 | "metadata": {}, 147 | "outputs": [], 148 | "source": [ 149 | "gpstime = h1attrs['Xstart'] + h1attrs['Xspacing'] * np.arange(h1attrs['Npoints'])" 150 | ] 151 | }, 152 | { 153 | "cell_type": "code", 154 | "execution_count": null, 155 | "metadata": {}, 156 | "outputs": [], 157 | "source": [ 158 | "pp.plot(gpstime, h1strain)" 159 | ] 160 | }, 161 | { 162 | "cell_type": "code", 163 | "execution_count": null, 164 | "metadata": {}, 165 | "outputs": [], 166 | "source": [ 167 | "tevent = 1126259462.4" 168 | ] 169 | }, 170 | { 171 | "cell_type": "code", 172 | "execution_count": null, 173 | "metadata": {}, 174 | "outputs": [], 175 | "source": [ 176 | "around = (gpstime > tevent - 0.1) & (gpstime < tevent + 0.1)" 177 | ] 178 | }, 179 | { 180 | "cell_type": "code", 181 | "execution_count": null, 182 | "metadata": {}, 183 | "outputs": [], 184 | "source": [ 185 | "pp.plot(gpstime[around] - tevent, h1strain[around])" 186 | ] 187 | }, 188 | { 189 | "cell_type": "code", 190 | "execution_count": null, 191 | "metadata": {}, 192 | "outputs": [], 193 | "source": [ 194 | "psd, freqs = mlab.psd(h1strain,\n", 195 | " NFFT=4096*4, # use four seconds of data to compute the spectrum\n", 196 | " Fs=4096) # this is the sampling rate of the data in Hz\n", 197 | "\n", 198 | "pp.loglog(freqs, np.sqrt(psd)) # plot the sqrt of spectrum (power spectral density)\n", 199 | "\n", 200 | "pp.xlabel('f [Hz]'); pp.ylabel('PSD [1/sqrt(Hz)]')\n", 201 | "pp.axis(xmin=5, xmax=1024, ymin=1e-24, ymax=1e-18);" 202 | ] 203 | }, 204 | { 205 | "cell_type": "code", 206 | "execution_count": null, 207 | "metadata": {}, 208 | "outputs": [], 209 | "source": [ 210 | "def whiten(strain, sampling=4096, bandpass=[20,350]):\n", 211 | " # compute the spectrum\n", 212 | " psd, psd_freqs = mlab.psd(strain, NFFT=sampling*4, Fs=sampling)\n", 213 | "\n", 214 | " # max out the spectrum outside the bandpass\n", 215 | " psd[(psd_freqs < bandpass[0]) | (psd_freqs > bandpass[1])] = np.max(psd)\n", 216 | " \n", 217 | " dt = 1/sampling\n", 218 | "\n", 219 | " # compute the real FFT and the corresponding frequencies\n", 220 | " strain_fft = np.fft.rfft(strain)\n", 221 | " fft_freqs = np.fft.rfftfreq(len(strain), dt)\n", 222 | "\n", 223 | " # interpolate the spectrum to the FFT frequencies\n", 224 | " psd_fft = scipy.interpolate.interp1d(psd_freqs, psd)(fft_freqs)\n", 225 | " \n", 226 | " # whiten and transform back to real space\n", 227 | " whitened = np.fft.irfft(strain_fft / np.sqrt(psd_fft) * np.sqrt(2*dt))\n", 228 | " \n", 229 | " return whitened" 230 | ] 231 | }, 232 | { 233 | "cell_type": "code", 234 | "execution_count": null, 235 | "metadata": {}, 236 | "outputs": [], 237 | "source": [ 238 | "pp.figure(figsize=(12,3))\n", 239 | "pp.plot(gpstime[around] - tevent, whiten(h1strain)[around])" 240 | ] 241 | }, 242 | { 243 | "cell_type": "code", 244 | "execution_count": null, 245 | "metadata": {}, 246 | "outputs": [], 247 | "source": [ 248 | "l1file = h5py.File('L-L1_GWOSC_4KHZ_R1-1126259447-32.hdf5', 'r')" 249 | ] 250 | }, 251 | { 252 | "cell_type": "code", 253 | "execution_count": null, 254 | "metadata": {}, 255 | "outputs": [], 256 | "source": [ 257 | "l1strain = l1file['strain/Strain']" 258 | ] 259 | }, 260 | { 261 | "cell_type": "code", 262 | "execution_count": null, 263 | "metadata": {}, 264 | "outputs": [], 265 | "source": [ 266 | "pp.figure(figsize=(12,3))\n", 267 | "pp.plot(gpstime[around] - tevent, whiten(h1strain)[around])\n", 268 | "pp.plot(gpstime[around] - tevent, whiten(l1strain)[around])" 269 | ] 270 | }, 271 | { 272 | "cell_type": "code", 273 | "execution_count": null, 274 | "metadata": {}, 275 | "outputs": [], 276 | "source": [ 277 | "pp.figure(figsize=(12,3))\n", 278 | "pp.plot(gpstime[around] - tevent, whiten(h1strain)[around])\n", 279 | "pp.plot(gpstime[around] - tevent + 0.007, -whiten(l1strain)[around])" 280 | ] 281 | }, 282 | { 283 | "cell_type": "code", 284 | "execution_count": null, 285 | "metadata": {}, 286 | "outputs": [], 287 | "source": [] 288 | } 289 | ], 290 | "metadata": { 291 | "kernelspec": { 292 | "display_name": "Python 3", 293 | "language": "python", 294 | "name": "python3" 295 | }, 296 | "language_info": { 297 | "codemirror_mode": { 298 | "name": "ipython", 299 | "version": 3 300 | }, 301 | "file_extension": ".py", 302 | "mimetype": "text/x-python", 303 | "name": "python", 304 | "nbconvert_exporter": "python", 305 | "pygments_lexer": "ipython3", 306 | "version": "3.8.8" 307 | }, 308 | "toc": { 309 | "base_numbering": 1, 310 | "nav_menu": {}, 311 | "number_sections": true, 312 | "sideBar": true, 313 | "skip_h1_title": false, 314 | "title_cell": "Table of Contents", 315 | "title_sidebar": "Contents", 316 | "toc_cell": false, 317 | "toc_position": {}, 318 | "toc_section_display": true, 319 | "toc_window_display": false 320 | } 321 | }, 322 | "nbformat": 4, 323 | "nbformat_minor": 4 324 | } 325 | -------------------------------------------------------------------------------- /Ch04/04_05_scripting-complete.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 04_05_scripting.ipynb - Automation with Python scripts" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 1, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "import os\n", 17 | "import subprocess\n", 18 | "import glob\n", 19 | "\n", 20 | "import matplotlib.pyplot as pp" 21 | ] 22 | }, 23 | { 24 | "cell_type": "code", 25 | "execution_count": 2, 26 | "metadata": {}, 27 | "outputs": [], 28 | "source": [ 29 | "events = ['GW170817-v3', 'GW190521_074359-v1', 'GW190814-v2']" 30 | ] 31 | }, 32 | { 33 | "cell_type": "code", 34 | "execution_count": 3, 35 | "metadata": {}, 36 | "outputs": [], 37 | "source": [ 38 | "for event in events:\n", 39 | " p1 = subprocess.run(['python', 'hdfdownload.py', event], capture_output=True)\n", 40 | " p2 = subprocess.run(['python', 'plotsignal.py', event], capture_output=True)" 41 | ] 42 | }, 43 | { 44 | "cell_type": "code", 45 | "execution_count": 4, 46 | "metadata": {}, 47 | "outputs": [ 48 | { 49 | "data": { 50 | "text/plain": [ 51 | "0" 52 | ] 53 | }, 54 | "execution_count": 4, 55 | "metadata": {}, 56 | "output_type": "execute_result" 57 | } 58 | ], 59 | "source": [ 60 | "p2.returncode" 61 | ] 62 | }, 63 | { 64 | "cell_type": "code", 65 | "execution_count": 5, 66 | "metadata": {}, 67 | "outputs": [ 68 | { 69 | "name": "stdout", 70 | "output_type": "stream", 71 | "text": [ 72 | "\n" 73 | ] 74 | } 75 | ], 76 | "source": [ 77 | "print(p1.stderr.decode('ascii'))" 78 | ] 79 | }, 80 | { 81 | "cell_type": "code", 82 | "execution_count": 6, 83 | "metadata": {}, 84 | "outputs": [ 85 | { 86 | "name": "stdout", 87 | "output_type": "stream", 88 | "text": [ 89 | "Downloading https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190814/v2 to ./GW190814-v2.json.\n", 90 | "Downloading https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190814/v2/H-H1_GWOSC_4KHZ_R1-1249852241-32.hdf5 to ./H1-GW190814-v2.hdf5.\n", 91 | "Downloading https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190814/v2/L-L1_GWOSC_4KHZ_R1-1249852241-32.hdf5 to ./L1-GW190814-v2.hdf5.\n", 92 | "\n" 93 | ] 94 | } 95 | ], 96 | "source": [ 97 | "print(p1.stdout.decode('ascii'))" 98 | ] 99 | }, 100 | { 101 | "cell_type": "code", 102 | "execution_count": 7, 103 | "metadata": {}, 104 | "outputs": [], 105 | "source": [ 106 | "pngs = glob.glob('*.png')" 107 | ] 108 | }, 109 | { 110 | "cell_type": "code", 111 | "execution_count": 8, 112 | "metadata": {}, 113 | "outputs": [ 114 | { 115 | "data": { 116 | "text/plain": [ 117 | "['GW190521_074359-v1.png', 'GW170817-v3.png', 'GW190814-v2.png']" 118 | ] 119 | }, 120 | "execution_count": 8, 121 | "metadata": {}, 122 | "output_type": "execute_result" 123 | } 124 | ], 125 | "source": [ 126 | "pngs" 127 | ] 128 | }, 129 | { 130 | "cell_type": "markdown", 131 | "metadata": {}, 132 | "source": [ 133 | "#### The grand finale!" 134 | ] 135 | }, 136 | { 137 | "cell_type": "code", 138 | "execution_count": null, 139 | "metadata": {}, 140 | "outputs": [], 141 | "source": [ 142 | "for png in pngs:\n", 143 | " pp.figure(figsize=(9,6))\n", 144 | " pp.imshow(pp.imread(png))\n", 145 | " pp.show()" 146 | ] 147 | } 148 | ], 149 | "metadata": { 150 | "kernelspec": { 151 | "display_name": "Python 3", 152 | "language": "python", 153 | "name": "python3" 154 | }, 155 | "language_info": { 156 | "codemirror_mode": { 157 | "name": "ipython", 158 | "version": 3 159 | }, 160 | "file_extension": ".py", 161 | "mimetype": "text/x-python", 162 | "name": "python", 163 | "nbconvert_exporter": "python", 164 | "pygments_lexer": "ipython3", 165 | "version": "3.8.8" 166 | }, 167 | "toc": { 168 | "base_numbering": 1, 169 | "nav_menu": {}, 170 | "number_sections": true, 171 | "sideBar": true, 172 | "skip_h1_title": false, 173 | "title_cell": "Table of Contents", 174 | "title_sidebar": "Contents", 175 | "toc_cell": false, 176 | "toc_position": {}, 177 | "toc_section_display": true, 178 | "toc_window_display": false 179 | } 180 | }, 181 | "nbformat": 4, 182 | "nbformat_minor": 4 183 | } 184 | -------------------------------------------------------------------------------- /Ch04/04_05_scripting.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 04_05_scripting.ipynb - Automation with Python scripts" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "import os\n", 17 | "import subprocess\n", 18 | "import glob\n", 19 | "\n", 20 | "import matplotlib.pyplot as pp" 21 | ] 22 | }, 23 | { 24 | "cell_type": "code", 25 | "execution_count": null, 26 | "metadata": {}, 27 | "outputs": [], 28 | "source": [ 29 | "events = ['GW170817-v3', 'GW190521_074359-v1', 'GW190814-v2']" 30 | ] 31 | }, 32 | { 33 | "cell_type": "code", 34 | "execution_count": null, 35 | "metadata": {}, 36 | "outputs": [], 37 | "source": [ 38 | "for event in events:\n", 39 | " p1 = subprocess.run(['python', 'hdfdownload.py', event], capture_output=True)\n", 40 | " p2 = subprocess.run(['python', 'plotsignal.py', event], capture_output=True)" 41 | ] 42 | }, 43 | { 44 | "cell_type": "code", 45 | "execution_count": null, 46 | "metadata": {}, 47 | "outputs": [], 48 | "source": [ 49 | "p2.returncode" 50 | ] 51 | }, 52 | { 53 | "cell_type": "code", 54 | "execution_count": null, 55 | "metadata": {}, 56 | "outputs": [], 57 | "source": [ 58 | "print(p1.stderr.decode('ascii'))" 59 | ] 60 | }, 61 | { 62 | "cell_type": "code", 63 | "execution_count": null, 64 | "metadata": {}, 65 | "outputs": [], 66 | "source": [ 67 | "print(p1.stdout.decode('ascii'))" 68 | ] 69 | }, 70 | { 71 | "cell_type": "code", 72 | "execution_count": null, 73 | "metadata": {}, 74 | "outputs": [], 75 | "source": [ 76 | "pngs = glob.glob('*.png')" 77 | ] 78 | }, 79 | { 80 | "cell_type": "code", 81 | "execution_count": null, 82 | "metadata": {}, 83 | "outputs": [], 84 | "source": [ 85 | "pngs" 86 | ] 87 | }, 88 | { 89 | "cell_type": "markdown", 90 | "metadata": {}, 91 | "source": [ 92 | "#### The grand finale!" 93 | ] 94 | }, 95 | { 96 | "cell_type": "code", 97 | "execution_count": null, 98 | "metadata": {}, 99 | "outputs": [], 100 | "source": [ 101 | "for png in pngs:\n", 102 | " pp.figure(figsize=(9,6))\n", 103 | " pp.imshow(pp.imread(png))\n", 104 | " pp.show()" 105 | ] 106 | } 107 | ], 108 | "metadata": { 109 | "kernelspec": { 110 | "display_name": "Python 3", 111 | "language": "python", 112 | "name": "python3" 113 | }, 114 | "language_info": { 115 | "codemirror_mode": { 116 | "name": "ipython", 117 | "version": 3 118 | }, 119 | "file_extension": ".py", 120 | "mimetype": "text/x-python", 121 | "name": "python", 122 | "nbconvert_exporter": "python", 123 | "pygments_lexer": "ipython3", 124 | "version": "3.8.8" 125 | }, 126 | "toc": { 127 | "base_numbering": 1, 128 | "nav_menu": {}, 129 | "number_sections": true, 130 | "sideBar": true, 131 | "skip_h1_title": false, 132 | "title_cell": "Table of Contents", 133 | "title_sidebar": "Contents", 134 | "toc_cell": false, 135 | "toc_position": {}, 136 | "toc_section_display": true, 137 | "toc_window_display": false 138 | } 139 | }, 140 | "nbformat": 4, 141 | "nbformat_minor": 4 142 | } 143 | -------------------------------------------------------------------------------- /Ch04/04_06_snakemake.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 04_06_snakemake.ipynb - Scientific workflows with Snakemake" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "# conda install -c bioconda -c conda-forge snakemake-minimal" 17 | ] 18 | }, 19 | { 20 | "cell_type": "code", 21 | "execution_count": null, 22 | "metadata": {}, 23 | "outputs": [], 24 | "source": [ 25 | "%%file Snakefile\n", 26 | "\n", 27 | "events = ['GW170817-v3', 'GW190521_074359-v1', 'GW190814-v2', 'GW190412-v3',\n", 28 | " 'GW190828_063405-v1', 'GW170814-v3', 'GW170608-v3', 'GW190408_181802-v1',\n", 29 | " 'GW190521-v3']\n", 30 | "\n", 31 | "rule stack:\n", 32 | " input:\n", 33 | " expand(\"events/{id}.png\", id=events)\n", 34 | " output:\n", 35 | " \"events/allevents.png\"\n", 36 | " run:\n", 37 | " from PIL import Image\n", 38 | " import numpy as np\n", 39 | " \n", 40 | " # load all images to numpy arrays\n", 41 | " images = [np.array(Image.open(imagefile)) for imagefile in input]\n", 42 | " # stack the arrays vertically\n", 43 | " stacked = np.vstack(images)\n", 44 | " # convert stacked array to PIL image, then save \n", 45 | " Image.fromarray(stacked).save(output[0])\n", 46 | "\n", 47 | "rule plot:\n", 48 | " input:\n", 49 | " \"events/{id}.json\"\n", 50 | " output:\n", 51 | " \"events/{id}.png\"\n", 52 | " shell:\n", 53 | " \"python plotsignal.py {wildcards.id} -C events\"\n", 54 | " \n", 55 | "rule download:\n", 56 | " output:\n", 57 | " \"events/{id}.json\"\n", 58 | " shell:\n", 59 | " \"python hdfdownload.py {wildcards.id} -C events\"" 60 | ] 61 | }, 62 | { 63 | "cell_type": "code", 64 | "execution_count": null, 65 | "metadata": {}, 66 | "outputs": [], 67 | "source": [ 68 | "!snakemake -j 1 events/GW150914-v3.json" 69 | ] 70 | }, 71 | { 72 | "cell_type": "code", 73 | "execution_count": null, 74 | "metadata": {}, 75 | "outputs": [], 76 | "source": [ 77 | "!snakemake -j 1 events/GW170817-v3.png" 78 | ] 79 | }, 80 | { 81 | "cell_type": "code", 82 | "execution_count": null, 83 | "metadata": {}, 84 | "outputs": [], 85 | "source": [ 86 | "!snakemake -n" 87 | ] 88 | }, 89 | { 90 | "cell_type": "code", 91 | "execution_count": null, 92 | "metadata": {}, 93 | "outputs": [], 94 | "source": [ 95 | "!snakemake -j 4" 96 | ] 97 | }, 98 | { 99 | "cell_type": "code", 100 | "execution_count": null, 101 | "metadata": {}, 102 | "outputs": [], 103 | "source": [ 104 | "# on Windows !start events/allevents.png\n", 105 | "!open events/allevents.png" 106 | ] 107 | } 108 | ], 109 | "metadata": { 110 | "kernelspec": { 111 | "display_name": "Python 3", 112 | "language": "python", 113 | "name": "python3" 114 | }, 115 | "language_info": { 116 | "codemirror_mode": { 117 | "name": "ipython", 118 | "version": 3 119 | }, 120 | "file_extension": ".py", 121 | "mimetype": "text/x-python", 122 | "name": "python", 123 | "nbconvert_exporter": "python", 124 | "pygments_lexer": "ipython3", 125 | "version": "3.8.8" 126 | }, 127 | "toc": { 128 | "base_numbering": 1, 129 | "nav_menu": {}, 130 | "number_sections": true, 131 | "sideBar": true, 132 | "skip_h1_title": false, 133 | "title_cell": "Table of Contents", 134 | "title_sidebar": "Contents", 135 | "toc_cell": false, 136 | "toc_position": {}, 137 | "toc_section_display": true, 138 | "toc_window_display": false 139 | } 140 | }, 141 | "nbformat": 4, 142 | "nbformat_minor": 4 143 | } 144 | -------------------------------------------------------------------------------- /Ch04/04_07_challenge-complete.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 04_07_challenge.ipynb - Perfect numbers" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 1, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "import sympy" 17 | ] 18 | }, 19 | { 20 | "cell_type": "code", 21 | "execution_count": 2, 22 | "metadata": {}, 23 | "outputs": [ 24 | { 25 | "data": { 26 | "text/plain": [ 27 | "[1, 2, 4, 8, 16, 31, 62, 124, 248, 496]" 28 | ] 29 | }, 30 | "execution_count": 2, 31 | "metadata": {}, 32 | "output_type": "execute_result" 33 | } 34 | ], 35 | "source": [ 36 | "sympy.divisors(496)" 37 | ] 38 | }, 39 | { 40 | "cell_type": "code", 41 | "execution_count": 3, 42 | "metadata": {}, 43 | "outputs": [ 44 | { 45 | "data": { 46 | "text/plain": [ 47 | "496" 48 | ] 49 | }, 50 | "execution_count": 3, 51 | "metadata": {}, 52 | "output_type": "execute_result" 53 | } 54 | ], 55 | "source": [ 56 | "sum(sympy.divisors(496)[:-1])" 57 | ] 58 | }, 59 | { 60 | "cell_type": "code", 61 | "execution_count": 4, 62 | "metadata": {}, 63 | "outputs": [ 64 | { 65 | "data": { 66 | "text/plain": [ 67 | "[1, 2, 4, 8, 16, 32, 64]" 68 | ] 69 | }, 70 | "execution_count": 4, 71 | "metadata": {}, 72 | "output_type": "execute_result" 73 | } 74 | ], 75 | "source": [ 76 | "[2**k for k in range(7)]" 77 | ] 78 | }, 79 | { 80 | "cell_type": "code", 81 | "execution_count": 5, 82 | "metadata": {}, 83 | "outputs": [ 84 | { 85 | "data": { 86 | "text/plain": [ 87 | "127" 88 | ] 89 | }, 90 | "execution_count": 5, 91 | "metadata": {}, 92 | "output_type": "execute_result" 93 | } 94 | ], 95 | "source": [ 96 | "sum(2**k for k in range(7))" 97 | ] 98 | }, 99 | { 100 | "cell_type": "code", 101 | "execution_count": 6, 102 | "metadata": {}, 103 | "outputs": [ 104 | { 105 | "data": { 106 | "text/plain": [ 107 | "True" 108 | ] 109 | }, 110 | "execution_count": 6, 111 | "metadata": {}, 112 | "output_type": "execute_result" 113 | } 114 | ], 115 | "source": [ 116 | "sympy.isprime(127)" 117 | ] 118 | }, 119 | { 120 | "cell_type": "code", 121 | "execution_count": 7, 122 | "metadata": {}, 123 | "outputs": [ 124 | { 125 | "data": { 126 | "text/plain": [ 127 | "8128" 128 | ] 129 | }, 130 | "execution_count": 7, 131 | "metadata": {}, 132 | "output_type": "execute_result" 133 | } 134 | ], 135 | "source": [ 136 | "sum(2**k for k in range(7)) * 64" 137 | ] 138 | }, 139 | { 140 | "cell_type": "code", 141 | "execution_count": 8, 142 | "metadata": {}, 143 | "outputs": [ 144 | { 145 | "data": { 146 | "text/plain": [ 147 | "8128" 148 | ] 149 | }, 150 | "execution_count": 8, 151 | "metadata": {}, 152 | "output_type": "execute_result" 153 | } 154 | ], 155 | "source": [ 156 | "sum(sympy.divisors(8128)[:-1])" 157 | ] 158 | }, 159 | { 160 | "cell_type": "code", 161 | "execution_count": 9, 162 | "metadata": {}, 163 | "outputs": [ 164 | { 165 | "name": "stdout", 166 | "output_type": "stream", 167 | "text": [ 168 | "2 6\n", 169 | "3 28\n", 170 | "5 496\n", 171 | "7 8128\n" 172 | ] 173 | } 174 | ], 175 | "source": [ 176 | "for n in range(10):\n", 177 | " s = sum(2**k for k in range(n))\n", 178 | " \n", 179 | " if sympy.isprime(s):\n", 180 | " print(n, s * 2**(n-1))" 181 | ] 182 | }, 183 | { 184 | "cell_type": "code", 185 | "execution_count": null, 186 | "metadata": {}, 187 | "outputs": [], 188 | "source": [] 189 | } 190 | ], 191 | "metadata": { 192 | "kernelspec": { 193 | "display_name": "Python 3", 194 | "language": "python", 195 | "name": "python3" 196 | }, 197 | "language_info": { 198 | "codemirror_mode": { 199 | "name": "ipython", 200 | "version": 3 201 | }, 202 | "file_extension": ".py", 203 | "mimetype": "text/x-python", 204 | "name": "python", 205 | "nbconvert_exporter": "python", 206 | "pygments_lexer": "ipython3", 207 | "version": "3.8.8" 208 | }, 209 | "toc": { 210 | "base_numbering": 1, 211 | "nav_menu": {}, 212 | "number_sections": true, 213 | "sideBar": true, 214 | "skip_h1_title": false, 215 | "title_cell": "Table of Contents", 216 | "title_sidebar": "Contents", 217 | "toc_cell": false, 218 | "toc_position": {}, 219 | "toc_section_display": true, 220 | "toc_window_display": false 221 | } 222 | }, 223 | "nbformat": 4, 224 | "nbformat_minor": 4 225 | } 226 | -------------------------------------------------------------------------------- /Ch04/04_07_challenge.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 04_07_challenge.ipynb - Perfect numbers" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "import sympy" 17 | ] 18 | }, 19 | { 20 | "cell_type": "code", 21 | "execution_count": null, 22 | "metadata": {}, 23 | "outputs": [], 24 | "source": [ 25 | "sympy.divisors(496)" 26 | ] 27 | }, 28 | { 29 | "cell_type": "code", 30 | "execution_count": null, 31 | "metadata": {}, 32 | "outputs": [], 33 | "source": [ 34 | "sum(sympy.divisors(496)[:-1])" 35 | ] 36 | }, 37 | { 38 | "cell_type": "code", 39 | "execution_count": null, 40 | "metadata": {}, 41 | "outputs": [], 42 | "source": [ 43 | "[2**k for k in range(7)]" 44 | ] 45 | }, 46 | { 47 | "cell_type": "code", 48 | "execution_count": null, 49 | "metadata": {}, 50 | "outputs": [], 51 | "source": [ 52 | "sum(2**k for k in range(7))" 53 | ] 54 | }, 55 | { 56 | "cell_type": "code", 57 | "execution_count": null, 58 | "metadata": {}, 59 | "outputs": [], 60 | "source": [ 61 | "sympy.isprime(127)" 62 | ] 63 | }, 64 | { 65 | "cell_type": "code", 66 | "execution_count": null, 67 | "metadata": {}, 68 | "outputs": [], 69 | "source": [ 70 | "sum(2**k for k in range(7)) * 64" 71 | ] 72 | }, 73 | { 74 | "cell_type": "code", 75 | "execution_count": null, 76 | "metadata": {}, 77 | "outputs": [], 78 | "source": [ 79 | "sum(sympy.divisors(8128)[:-1])" 80 | ] 81 | }, 82 | { 83 | "cell_type": "code", 84 | "execution_count": null, 85 | "metadata": {}, 86 | "outputs": [], 87 | "source": [ 88 | "for n in range(10):\n", 89 | " s = sum(2**k for k in range(n))\n", 90 | " \n", 91 | " if sympy.isprime(s):\n", 92 | " print(n, s * 2**(n-1))" 93 | ] 94 | }, 95 | { 96 | "cell_type": "code", 97 | "execution_count": null, 98 | "metadata": {}, 99 | "outputs": [], 100 | "source": [] 101 | } 102 | ], 103 | "metadata": { 104 | "kernelspec": { 105 | "display_name": "Python 3", 106 | "language": "python", 107 | "name": "python3" 108 | }, 109 | "language_info": { 110 | "codemirror_mode": { 111 | "name": "ipython", 112 | "version": 3 113 | }, 114 | "file_extension": ".py", 115 | "mimetype": "text/x-python", 116 | "name": "python", 117 | "nbconvert_exporter": "python", 118 | "pygments_lexer": "ipython3", 119 | "version": "3.8.8" 120 | }, 121 | "toc": { 122 | "base_numbering": 1, 123 | "nav_menu": {}, 124 | "number_sections": true, 125 | "sideBar": true, 126 | "skip_h1_title": false, 127 | "title_cell": "Table of Contents", 128 | "title_sidebar": "Contents", 129 | "toc_cell": false, 130 | "toc_position": {}, 131 | "toc_section_display": true, 132 | "toc_window_display": false 133 | } 134 | }, 135 | "nbformat": 4, 136 | "nbformat_minor": 4 137 | } 138 | -------------------------------------------------------------------------------- /Ch04/04_08_solution.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 04_07_challenge.ipynb - Perfect numbers" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "%%file snakefile\n", 17 | "\n", 18 | "rule sum:\n", 19 | " output:\n", 20 | " \"work/{n}_sum.txt\"\n", 21 | " run:\n", 22 | " with open(output[0], 'w') as outfile:\n", 23 | " outfile.write(str(sum(2**k for k in range(int(wildcards.n)))))\n", 24 | " \n", 25 | "rule product:\n", 26 | " input:\n", 27 | " \"work/{n}_sum.txt\"\n", 28 | " output:\n", 29 | " \"work/{n}_product.txt\"\n", 30 | " run:\n", 31 | " import sympy\n", 32 | " \n", 33 | " s = int(open(input[0], 'r').read())\n", 34 | " \n", 35 | " with open(output[0], 'w') as outfile:\n", 36 | " if sympy.isprime(s):\n", 37 | " outfile.write(str(s * 2**(int(wildcards.n) - 1)))\n", 38 | " else:\n", 39 | " outfile.write('0')\n", 40 | " \n", 41 | "rule find:\n", 42 | " input:\n", 43 | " expand(\"work/{n}_product.txt\", n=range(1,21))\n", 44 | " output:\n", 45 | " \"work/perfect.txt\"\n", 46 | " run:\n", 47 | " with open(output[0], 'w') as outfile:\n", 48 | " for inputfile in input:\n", 49 | " p = int(open(inputfile, 'r').read())\n", 50 | " \n", 51 | " if p != 0:\n", 52 | " outfile.write(f'{p}\\n')\n" 53 | ] 54 | }, 55 | { 56 | "cell_type": "code", 57 | "execution_count": null, 58 | "metadata": {}, 59 | "outputs": [], 60 | "source": [ 61 | "!mkdir work" 62 | ] 63 | }, 64 | { 65 | "cell_type": "code", 66 | "execution_count": null, 67 | "metadata": {}, 68 | "outputs": [], 69 | "source": [ 70 | "!snakemake -j 4 work/perfect.txt" 71 | ] 72 | }, 73 | { 74 | "cell_type": "code", 75 | "execution_count": null, 76 | "metadata": {}, 77 | "outputs": [], 78 | "source": [ 79 | "!cat work/perfect.txt\n", 80 | "# !type work\\perfect.txt on Windows" 81 | ] 82 | } 83 | ], 84 | "metadata": { 85 | "kernelspec": { 86 | "display_name": "Python 3", 87 | "language": "python", 88 | "name": "python3" 89 | }, 90 | "language_info": { 91 | "codemirror_mode": { 92 | "name": "ipython", 93 | "version": 3 94 | }, 95 | "file_extension": ".py", 96 | "mimetype": "text/x-python", 97 | "name": "python", 98 | "nbconvert_exporter": "python", 99 | "pygments_lexer": "ipython3", 100 | "version": "3.8.8" 101 | }, 102 | "toc": { 103 | "base_numbering": 1, 104 | "nav_menu": {}, 105 | "number_sections": true, 106 | "sideBar": true, 107 | "skip_h1_title": false, 108 | "title_cell": "Table of Contents", 109 | "title_sidebar": "Contents", 110 | "toc_cell": false, 111 | "toc_position": {}, 112 | "toc_section_display": true, 113 | "toc_window_display": false 114 | } 115 | }, 116 | "nbformat": 4, 117 | "nbformat_minor": 4 118 | } 119 | -------------------------------------------------------------------------------- /Ch04/cache/GW150914-v3.pickle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkedInLearning/python-for-engineers-and-scientists-2425360/bf844b890dd42913910ed81abe2ddd2846801117/Ch04/cache/GW150914-v3.pickle -------------------------------------------------------------------------------- /Ch04/cache/H-H1_GWOSC_4KHZ_R1-1126259447-32.hdf5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkedInLearning/python-for-engineers-and-scientists-2425360/bf844b890dd42913910ed81abe2ddd2846801117/Ch04/cache/H-H1_GWOSC_4KHZ_R1-1126259447-32.hdf5 -------------------------------------------------------------------------------- /Ch04/cache/L-L1_GWOSC_4KHZ_R1-1126259447-32.hdf5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkedInLearning/python-for-engineers-and-scientists-2425360/bf844b890dd42913910ed81abe2ddd2846801117/Ch04/cache/L-L1_GWOSC_4KHZ_R1-1126259447-32.hdf5 -------------------------------------------------------------------------------- /Ch04/cache/gwtc-20210726.csv: -------------------------------------------------------------------------------- 1 | id,commonName,version,catalog.shortName,GPS,reference,jsonurl,mass_1_source,mass_1_source_lower,mass_1_source_upper,mass_2_source,mass_2_source_lower,mass_2_source_upper,network_matched_filter_snr,network_matched_filter_snr_lower,network_matched_filter_snr_upper,luminosity_distance,luminosity_distance_lower,luminosity_distance_upper,chi_eff,chi_eff_lower,chi_eff_upper,total_mass_source,total_mass_source_lower,total_mass_source_upper,chirp_mass_source,chirp_mass_source_lower,chirp_mass_source_upper,chirp_mass,chirp_mass_lower,chirp_mass_upper,redshift,redshift_lower,redshift_upper,far,far_lower,far_upper,final_mass_source,final_mass_source_lower,final_mass_source_upper 2 | GW150914-v3,GW150914,3,GWTC-1-confident,1126259462.4,https://doi.org/10.7935/82H3-HH23,https://www.gw-openscience.org/eventapi/json/GWTC-1-confident/GW150914/v3,35.6,-3.1,4.7,30.6,-4.4,3.0,24.4,,,440.0,-170.0,150.0,-0.01,-0.13,0.12,,,,28.6,-1.5,1.7,,,,0.09,-0.03,0.03,1e-07,,,63.1,-3.0,3.4 3 | GW151012-v3,GW151012,3,GWTC-1-confident,1128678900.4,https://doi.org/10.7935/82H3-HH23,https://www.gw-openscience.org/eventapi/json/GWTC-1-confident/GW151012/v3,23.2,-5.5,14.9,13.6,-4.8,4.1,10.0,,,1080.0,-490.0,550.0,0.05,-0.2,0.31,,,,15.2,-1.2,2.1,,,,0.21,-0.09,0.09,0.00792,,,35.6,-3.8,10.8 4 | GW151226-v2,GW151226,2,GWTC-1-confident,1135136350.6,https://doi.org/10.7935/82H3-HH23,https://www.gw-openscience.org/eventapi/json/GWTC-1-confident/GW151226/v2,13.7,-3.2,8.8,7.7,-2.5,2.2,13.1,,,450.0,-190.0,180.0,0.18,-0.12,0.2,,,,8.9,-0.3,0.3,,,,0.09,-0.04,0.04,1e-07,,,20.5,-1.5,6.4 5 | GW170104-v2,GW170104,2,GWTC-1-confident,1167559936.6,https://doi.org/10.7935/82H3-HH23,https://www.gw-openscience.org/eventapi/json/GWTC-1-confident/GW170104/v2,30.8,-5.6,7.3,20.0,-4.6,4.9,13.0,,,990.0,-430.0,440.0,-0.04,-0.21,0.17,,,,21.4,-1.8,2.2,,,,0.2,-0.08,0.08,1e-07,,,48.9,-4.0,5.1 6 | GW170608-v3,GW170608,3,GWTC-1-confident,1180922494.5,https://doi.org/10.7935/82H3-HH23,https://www.gw-openscience.org/eventapi/json/GWTC-1-confident/GW170608/v3,11.0,-1.7,5.5,7.6,-2.2,1.4,14.9,,,320.0,-110.0,120.0,0.03,-0.07,0.19,,,,7.9,-0.2,0.2,,,,0.07,-0.02,0.02,1e-07,,,17.8,-0.7,3.4 7 | GW170729-v1,GW170729,1,GWTC-1-confident,1185389807.3,https://doi.org/10.7935/82H3-HH23,https://www.gw-openscience.org/eventapi/json/GWTC-1-confident/GW170729/v1,50.2,-10.2,16.2,34.0,-10.1,9.1,10.2,,,2840.0,-1360.0,1400.0,0.37,-0.25,0.21,,,,35.4,-4.8,6.5,,,,0.49,-0.21,0.19,0.02,,,79.5,-10.2,14.7 8 | GW170809-v1,GW170809,1,GWTC-1-confident,1186302519.8,https://doi.org/10.7935/82H3-HH23,https://www.gw-openscience.org/eventapi/json/GWTC-1-confident/GW170809/v1,35.0,-5.9,8.3,23.8,-5.2,5.1,12.4,,,1030.0,-390.0,320.0,0.08,-0.17,0.17,,,,24.9,-1.7,2.1,,,,0.2,-0.07,0.05,1e-07,,,56.3,-3.8,5.2 9 | GW170814-v3,GW170814,3,GWTC-1-confident,1186741861.5,https://doi.org/10.7935/82H3-HH23,https://www.gw-openscience.org/eventapi/json/GWTC-1-confident/GW170814/v3,30.6,-3.0,5.6,25.2,-4.0,2.8,15.9,,,600.0,-220.0,150.0,0.07,-0.12,0.12,,,,24.1,-1.1,1.4,,,,0.12,-0.04,0.03,1e-07,,,53.2,-2.4,3.2 10 | GW170817-v3,GW170817,3,GWTC-1-confident,1187008882.4,https://doi.org/10.7935/82H3-HH23,https://www.gw-openscience.org/eventapi/json/GWTC-1-confident/GW170817/v3,1.46,-0.1,0.12,1.27,-0.09,0.09,33.0,,,40.0,-15.0,7.0,0.0,-0.01,0.02,,,,1.186,-0.001,0.001,,,,0.01,-0.0,0.0,1e-07,,,2.8,, 11 | GW170818-v1,GW170818,1,GWTC-1-confident,1187058327.1,https://doi.org/10.7935/82H3-HH23,https://www.gw-openscience.org/eventapi/json/GWTC-1-confident/GW170818/v1,35.4,-4.7,7.5,26.7,-5.2,4.3,11.3,,,1060.0,-380.0,420.0,-0.09,-0.21,0.18,,,,26.5,-1.7,2.1,,,,0.21,-0.07,0.07,4.2000000000000004e-05,,,59.4,-3.8,4.9 12 | GW170823-v1,GW170823,1,GWTC-1-confident,1187529256.5,https://doi.org/10.7935/82H3-HH23,https://www.gw-openscience.org/eventapi/json/GWTC-1-confident/GW170823/v1,39.5,-6.7,11.2,29.0,-7.8,6.7,11.5,,,1940.0,-900.0,970.0,0.09,-0.26,0.22,,,,29.2,-3.6,4.6,,,,0.35,-0.15,0.15,1e-07,,,65.4,-7.4,10.1 13 | GW190408_181802-v1,GW190408_181802,1,GWTC-2,1238782700.3,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190408_181802/v1,24.6,-3.4,5.1,18.4,-3.6,3.3,14.67360038139546,,,1550.0,-600.0,400.0,-0.03,-0.19,0.14,43.0,-3.0,4.2,18.3,-1.2,1.9,23.7,-1.7,1.4,0.29,-0.1,0.06,1e-05,,,41.1,-2.8,3.9 14 | GW190412-v3,GW190412,3,GWTC-2,1239082262.2,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190412/v3,30.1,-5.1,4.7,8.3,-0.9,1.6,18.86182683162956,,,740.0,-170.0,140.0,0.25,-0.11,0.08,38.4,-3.7,3.8,13.3,-0.3,0.4,15.2,-0.2,0.2,0.15,-0.03,0.03,1e-05,,,37.3,-3.8,3.9 15 | GW190413_052954-v1,GW190413_052954,1,GWTC-2,1239168612.5,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190413_052954/v1,34.7,-8.1,12.6,23.7,-6.7,7.3,8.555396161858269,,,3550.0,-1660.0,2270.0,-0.01,-0.34,0.29,58.6,-9.7,13.3,24.6,-4.1,5.5,39.4,-6.6,7.7,0.59,-0.24,0.29,0.07168326663702794,,,56.0,-9.2,12.5 16 | GW190413_134308-v1,GW190413_134308,1,GWTC-2,1239198206.7,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190413_134308/v1,47.5,-10.7,13.5,31.8,-10.8,11.7,9.030693020279005,,,4450.0,-2120.0,2480.0,-0.03,-0.29,0.25,78.8,-11.9,17.4,33.0,-5.4,8.2,57.0,-9.8,8.6,0.71,-0.3,0.31,0.043657319879159086,,,75.5,-11.4,16.4 17 | GW190421_213856-v1,GW190421_213856,1,GWTC-2,1239917954.3,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190421_213856/v1,41.3,-6.9,10.4,31.9,-8.8,8.0,10.55069569549375,,,2880.0,-1380.0,1370.0,-0.06,-0.27,0.22,72.9,-9.2,13.4,31.2,-4.2,5.9,46.6,-6.0,6.6,0.49,-0.21,0.19,0.0007738314255311893,,,69.7,-8.7,12.5 18 | GW190424_180648-v1,GW190424_180648,1,GWTC-2,1240164426.1,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190424_180648/v1,40.5,-7.3,11.1,31.8,-7.7,7.6,10.03894424438477,,,2200.0,-1160.0,1580.0,0.13,-0.22,0.22,72.6,-10.7,13.3,31.0,-4.6,5.8,43.4,-4.8,6.0,0.39,-0.19,0.23,0.7822864941910456,,,68.9,-10.1,12.4 19 | GW190425-v2,GW190425,2,GWTC-2,1240215503.0,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190425/v2,2.0,-0.3,0.6,1.4,-0.3,0.3,13.02922972476558,,,160.0,-70.0,70.0,0.06,-0.05,0.11,3.4,-0.1,0.3,1.44,-0.02,0.02,1.49,-0.0006,0.0008,0.03,-0.02,0.01,0.000751854698112682,,,,, 20 | GW190426_152155-v1,GW190426_152155,1,GWTC-2,1240327333.3,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190426_152155/v1,5.7,-2.3,3.9,1.5,-0.5,0.8,10.12041364677255,,,370.0,-160.0,180.0,-0.03,-0.3,0.32,7.2,-1.5,3.5,2.41,-0.08,0.08,2.6,-0.01,0.01,0.08,-0.03,0.04,1.443741335492165,,,,, 21 | GW190503_185404-v1,GW190503_185404,1,GWTC-2,1240944862.3,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190503_185404/v1,43.3,-8.1,9.2,28.4,-8.0,7.7,12.09959960690361,,,1450.0,-630.0,690.0,-0.03,-0.26,0.2,71.7,-8.3,9.4,30.2,-4.2,4.2,38.6,-6.0,5.3,0.27,-0.11,0.11,1e-05,,,68.6,-7.7,8.8 22 | GW190512_180714-v1,GW190512_180714,1,GWTC-2,1241719652.4,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190512_180714/v1,23.3,-5.8,5.3,12.6,-2.5,3.6,12.26449406234808,,,1430.0,-550.0,550.0,0.03,-0.13,0.12,35.9,-3.5,3.8,14.6,-1.0,1.3,18.6,-0.8,0.9,0.27,-0.1,0.09,1e-05,,,34.5,-3.5,3.8 23 | GW190513_205428-v1,GW190513_205428,1,GWTC-2,1241816086.8,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190513_205428/v1,35.7,-9.2,9.5,18.0,-4.1,7.7,12.28987773592599,,,2060.0,-800.0,880.0,0.11,-0.17,0.28,53.9,-5.9,8.6,21.6,-1.9,3.8,29.5,-2.5,5.6,0.37,-0.13,0.13,1e-05,,,51.6,-5.8,8.2 24 | GW190514_065416-v1,GW190514_065416,1,GWTC-2,1241852074.8,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190514_065416/v1,39.0,-8.2,14.7,28.4,-8.8,9.3,8.304493549646196,,,4130.0,-2170.0,2650.0,-0.19,-0.32,0.29,67.2,-10.8,18.7,28.5,-4.8,7.9,48.1,-7.7,7.5,0.67,-0.31,0.33,0.5266876793595081,,,64.5,-10.4,17.9 25 | GW190517_055101-v1,GW190517_055101,1,GWTC-2,1242107479.8,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190517_055101/v1,37.4,-7.6,11.7,25.3,-7.3,7.0,10.24122163775042,,,1860.0,-840.0,1620.0,0.52,-0.19,0.19,63.5,-9.6,9.6,26.6,-4.0,4.0,35.9,-3.4,4.0,0.34,-0.14,0.24,5.720513515363399e-05,,,59.3,-8.9,9.1 26 | GW190519_153544-v1,GW190519_153544,1,GWTC-2,1242315362.4,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190519_153544/v1,66.0,-12.0,10.7,40.5,-11.1,11.0,12.04985270704691,,,2530.0,-920.0,1830.0,0.31,-0.22,0.2,106.6,-14.8,13.5,44.5,-7.1,6.4,65.1,-10.3,7.7,0.44,-0.14,0.25,1e-05,,,101.0,-13.8,12.4 27 | GW190521-v3,GW190521,3,GWTC-2,1242442967.4,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190521/v3,95.3,-18.9,28.7,69.0,-23.1,22.7,14.376046048896756,,,3920.0,-1950.0,2190.0,0.03,-0.39,0.32,163.9,-23.5,39.2,69.2,-10.6,17.0,114.8,-17.6,15.2,0.64,-0.28,0.28,0.0002039635028,,,156.3,-22.4,36.8 28 | GW190521_074359-v1,GW190521_074359,1,GWTC-2,1242459857.5,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190521_074359/v1,42.2,-4.8,5.9,32.8,-6.4,5.4,24.38410871911596,,,1240.0,-570.0,400.0,0.09,-0.13,0.1,74.7,-4.8,7.0,32.1,-2.5,3.2,39.8,-3.0,2.2,0.24,-0.1,0.07,1e-05,,,71.0,-4.4,6.5 29 | GW190527_092055-v1,GW190527_092055,1,GWTC-2,1242984073.8,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190527_092055/v1,36.5,-9.0,16.4,22.6,-8.1,10.5,8.867476217742222,,,2490.0,-1240.0,2480.0,0.11,-0.28,0.28,59.1,-9.8,21.3,24.3,-4.2,9.1,34.9,-5.5,21.7,0.44,-0.2,0.34,0.062270351314133505,,,56.4,-9.3,20.2 30 | GW190602_175927-v1,GW190602_175927,1,GWTC-2,1243533585.1,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190602_175927/v1,69.1,-13.0,15.7,47.8,-17.4,14.3,12.13087548611321,,,2690.0,-1120.0,1790.0,0.07,-0.24,0.25,116.3,-15.6,19.0,49.1,-8.5,9.1,72.9,-13.7,10.8,0.47,-0.17,0.25,1.1478437256536947e-05,,,110.9,-14.9,17.7 31 | GW190620_030421-v1,GW190620_030421,1,GWTC-2,1245035079.3,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190620_030421/v1,57.1,-12.7,16.0,35.5,-12.3,12.2,10.91846314686192,,,2810.0,-1310.0,1680.0,0.33,-0.25,0.22,92.1,-13.1,18.5,38.3,-6.5,8.3,57.5,-11.2,9.0,0.49,-0.2,0.23,0.0029209383726319974,,,87.2,-12.1,16.8 32 | GW190630_185205-v1,GW190630_185205,1,GWTC-2,1245955943.2,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190630_185205/v1,35.1,-5.6,6.9,23.7,-5.1,5.2,15.64051208963232,,,890.0,-370.0,560.0,0.1,-0.13,0.12,59.1,-4.8,4.6,24.9,-2.1,2.1,29.4,-1.5,1.6,0.18,-0.07,0.1,1e-05,,,56.4,-4.6,4.4 33 | GW190701_203306-v1,GW190701_203306,1,GWTC-2,1246048404.6,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190701_203306/v1,53.9,-8.0,11.8,40.8,-12.0,8.7,11.58996006414267,,,2060.0,-730.0,760.0,-0.07,-0.29,0.23,94.3,-9.5,12.1,40.3,-4.9,5.4,55.5,-8.1,7.3,0.37,-0.12,0.11,0.010861368605368522,,,90.2,-8.9,11.3 34 | GW190706_222641-v1,GW190706_222641,1,GWTC-2,1246487219.3,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190706_222641/v1,67.0,-16.2,14.6,38.2,-13.3,14.6,12.34834506062684,,,4420.0,-1930.0,2590.0,0.28,-0.29,0.26,104.1,-13.9,20.2,42.7,-7.0,10.0,75.1,-17.5,11.0,0.71,-0.27,0.32,1e-05,,,99.0,-13.5,18.3 35 | GW190707_093326-v1,GW190707_093326,1,GWTC-2,1246527224.2,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190707_093326/v1,11.6,-1.7,3.3,8.4,-1.7,1.4,12.97817936002082,,,770.0,-370.0,380.0,-0.05,-0.08,0.1,20.1,-1.3,1.9,8.5,-0.5,0.6,9.89,-0.09,0.1,0.16,-0.07,0.07,1e-05,,,19.2,-1.3,1.9 36 | GW190708_232457-v1,GW190708_232457,1,GWTC-2,1246663515.4,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190708_232457/v1,17.6,-2.3,4.7,13.2,-2.7,2.0,13.07130069939341,,,880.0,-390.0,330.0,0.02,-0.08,0.1,30.9,-1.8,2.5,13.2,-0.6,0.9,15.5,-0.2,0.3,0.18,-0.07,0.06,2.8252506364808675e-05,,,29.5,-1.8,2.5 37 | GW190719_215514-v1,GW190719_215514,1,GWTC-2,1247608532.9,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190719_215514/v1,36.5,-10.3,18.0,20.8,-7.2,9.0,7.993907515410997,,,3940.0,-2000.0,2590.0,0.32,-0.31,0.29,57.8,-10.7,18.3,23.5,-4.0,6.5,38.7,-6.6,9.2,0.64,-0.29,0.33,1.559222128828275,,,54.9,-10.2,17.3 38 | GW190720_000836-v1,GW190720_000836,1,GWTC-2,1247616534.7,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190720_000836/v1,13.4,-3.0,6.7,7.8,-2.2,2.3,11.6960978153441,,,790.0,-320.0,690.0,0.18,-0.12,0.14,21.5,-2.3,4.3,8.9,-0.8,0.5,10.4,-0.1,0.2,0.16,-0.06,0.12,1e-05,,,20.4,-2.2,4.5 39 | GW190727_060333-v1,GW190727_060333,1,GWTC-2,1248242632.0,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190727_060333/v1,38.0,-6.2,9.5,29.4,-8.4,7.1,12.29941092425987,,,3300.0,-1500.0,1540.0,0.11,-0.25,0.26,67.1,-8.0,11.7,28.6,-3.7,5.3,44.7,-5.7,5.3,0.55,-0.22,0.21,1e-05,,,63.8,-7.5,10.9 40 | GW190728_064510-v1,GW190728_064510,1,GWTC-2,1248331528.5,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190728_064510/v1,12.3,-2.2,7.2,8.1,-2.6,1.7,13.64274847591606,,,870.0,-370.0,260.0,0.12,-0.07,0.2,20.6,-1.3,4.5,8.6,-0.3,0.5,10.1,-0.08,0.09,0.18,-0.07,0.05,1e-05,,,19.6,-1.3,4.7 41 | GW190731_140936-v1,GW190731_140936,1,GWTC-2,1248617394.6,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190731_140936/v1,41.5,-9.0,12.2,28.8,-9.5,9.7,8.460146466288636,,,3300.0,-1720.0,2390.0,0.06,-0.24,0.24,70.1,-11.3,15.8,29.5,-5.2,7.1,46.6,-8.2,6.8,0.55,-0.26,0.31,0.20584212311867794,,,67.0,-10.8,14.6 42 | GW190803_022701-v1,GW190803_022701,1,GWTC-2,1248834439.9,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190803_022701/v1,37.3,-7.0,10.6,27.3,-8.2,7.8,8.614396126273874,,,3270.0,-1580.0,1950.0,-0.03,-0.27,0.24,64.5,-9.0,12.6,27.3,-4.1,5.7,42.7,-6.1,6.3,0.55,-0.24,0.26,0.026934317250435554,,,61.7,-8.5,11.8 43 | GW190814-v2,GW190814,2,GWTC-2,1249852257.0,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190814/v2,23.2,-1.0,1.1,2.59,-0.09,0.08,22.17523325999954,,,240.0,-50.0,40.0,0.0,-0.06,0.06,25.8,-0.9,1.0,6.09,-0.06,0.06,6.41,-0.02,0.02,0.05,-0.01,0.009,1e-05,,,25.6,-0.9,1.1 44 | GW190828_063405-v1,GW190828_063405,1,GWTC-2,1251009263.8,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190828_063405/v1,32.1,-4.0,5.8,26.2,-4.8,4.6,16.0359229190588,,,2130.0,-930.0,660.0,0.19,-0.16,0.15,58.0,-4.8,7.7,25.0,-2.1,3.4,34.5,-2.8,2.9,0.38,-0.15,0.1,1e-05,,,54.9,-4.3,7.2 45 | GW190828_065509-v1,GW190828_065509,1,GWTC-2,1251010527.9,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190828_065509/v1,24.1,-7.2,7.0,10.2,-2.1,3.6,11.12790886853085,,,1600.0,-600.0,620.0,0.08,-0.16,0.16,34.4,-4.4,5.4,13.3,-1.0,1.2,17.4,-0.7,0.6,0.3,-0.1,0.1,1e-05,,,33.1,-4.5,5.5 46 | GW190909_114149-v1,GW190909_114149,1,GWTC-2,1252064527.7,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190909_114149/v1,45.8,-13.3,52.7,28.3,-12.7,13.4,8.543047309881066,,,3770.0,-2220.0,3270.0,-0.06,-0.36,0.37,75.0,-17.6,55.9,30.9,-7.5,17.2,49.8,-12.4,32.2,0.62,-0.33,0.41,1.1112276612026477,,,72.0,-16.8,54.9 47 | GW190910_112807-v1,GW190910_112807,1,GWTC-2,1252150105.3,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190910_112807/v1,43.9,-6.1,7.6,35.6,-7.2,6.3,13.41737344451953,,,1460.0,-580.0,1030.0,0.02,-0.18,0.18,79.6,-9.1,9.3,34.3,-4.1,4.1,43.9,-3.6,4.6,0.28,-0.1,0.16,1.8852694587530696e-05,,,75.8,-8.6,8.5 48 | GW190915_235702-v1,GW190915_235702,1,GWTC-2,1252627040.7,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190915_235702/v1,35.3,-6.4,9.5,24.4,-6.1,5.6,13.07209167194663,,,1620.0,-610.0,710.0,0.02,-0.25,0.2,59.9,-6.4,7.5,25.3,-2.7,3.2,33.1,-3.9,3.3,0.3,-0.1,0.11,1e-05,,,57.2,-6.0,7.1 49 | GW190924_021846-v1,GW190924_021846,1,GWTC-2,1253326744.8,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190924_021846/v1,8.9,-2.0,7.0,5.0,-1.9,1.4,13.15903752184739,,,570.0,-220.0,220.0,0.03,-0.09,0.3,13.9,-1.0,5.1,5.8,-0.2,0.2,6.44,-0.03,0.04,0.12,-0.04,0.04,1e-05,,,13.3,-1.0,5.2 50 | GW190929_012149-v1,GW190929_012149,1,GWTC-2,1253755327.5,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190929_012149/v1,80.8,-33.2,33.0,24.1,-10.6,19.3,9.875628916044713,,,2130.0,-1050.0,3650.0,0.01,-0.33,0.34,104.3,-25.2,34.9,35.8,-8.2,14.9,52.2,-15.4,19.9,0.38,-0.17,0.49,0.020161443585491597,,,101.5,-25.3,33.6 51 | GW190930_133541-v1,GW190930_133541,1,GWTC-2,1253885759.2,/GWTC-2/,https://www.gw-openscience.org/eventapi/json/GWTC-2/GW190930_133541/v1,12.3,-2.3,12.4,7.8,-3.3,1.7,9.837638319153829,,,760.0,-320.0,360.0,0.14,-0.15,0.31,20.3,-1.5,8.9,8.5,-0.5,0.5,9.8,-0.2,0.2,0.15,-0.06,0.06,0.03309219802659227,,,19.4,-1.5,9.2 52 | -------------------------------------------------------------------------------- /Ch04/events/.gitignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkedInLearning/python-for-engineers-and-scientists-2425360/bf844b890dd42913910ed81abe2ddd2846801117/Ch04/events/.gitignore -------------------------------------------------------------------------------- /Ch04/hdfdownload.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import argparse 4 | import json 5 | import os 6 | 7 | import requests 8 | 9 | 10 | def get_and_save(url, filename, folder='.'): 11 | """Utility function to query a URL, dump its content to file, and return the request object.""" 12 | 13 | target = os.path.join(args.C, filename) 14 | print(f"Downloading {url} to {target}.") 15 | 16 | r = requests.get(url) 17 | with open(target, 'wb') as outfile: 18 | outfile.write(r.content) 19 | 20 | return r 21 | 22 | 23 | parser = argparse.ArgumentParser(description='Download JSON and 4Hz HDF files for GWOSC event id.') 24 | 25 | parser.add_argument('id', metavar='id', help='GWOSC id (e.g., GW150914-v3)') 26 | parser.add_argument('-C', metavar='dir', default='.', help='output folder') 27 | 28 | args = parser.parse_args() 29 | 30 | 31 | # get the JSON catalog file (unless we have it already), parse it 32 | try: 33 | catalog = json.load(open(os.path.join(args.C, 'catalog.json'), 'rb')) 34 | except FileNotFoundError: 35 | r1 = get_and_save('https://www.gw-openscience.org/eventapi/json/allevents', 36 | 'catalog.json', args.C) 37 | catalog = json.loads(r1.text) 38 | 39 | # get the JSON event file for the requested ID, write it to disk, and parse it 40 | jsonurl = catalog['events'][args.id]['jsonurl'] 41 | r2 = get_and_save(jsonurl, args.id + '.json', args.C) 42 | jsondict = json.loads(r2.text) 43 | 44 | # identify HDF strain files, get them, write them to disk 45 | for file in jsondict['events'][args.id]['strain']: 46 | if (file['duration'] == 32 and file['sampling_rate'] == 4096 47 | and file['format'] == 'hdf5' 48 | and file['detector'] in ['H1','L1']): 49 | get_and_save(file['url'], f'{file["detector"]}-{args.id}.hdf5', args.C) 50 | -------------------------------------------------------------------------------- /Ch04/plotsignal.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import argparse 4 | import json 5 | import os 6 | 7 | import numpy as np 8 | import scipy.interpolate 9 | import matplotlib.mlab as mlab 10 | import matplotlib.pyplot as pp 11 | 12 | import h5py 13 | 14 | 15 | def whiten(strain, sampling=4096, bandpass=[20,350]): 16 | # compute the spectrum 17 | psd, psd_freqs = mlab.psd(strain, NFFT=sampling*4, Fs=sampling) 18 | 19 | # max out the spectrum outside the bandpass 20 | psd[(psd_freqs < bandpass[0]) | (psd_freqs > bandpass[1])] = np.max(psd) 21 | 22 | dt = 1/sampling 23 | 24 | # compute the real FFT and the corresponding frequencies 25 | strain_fft = np.fft.rfft(strain) 26 | fft_freqs = np.fft.rfftfreq(len(strain), dt) 27 | 28 | # interpolate the spectrum to the FFT frequencies 29 | psd_fft = scipy.interpolate.interp1d(psd_freqs, psd)(fft_freqs) 30 | 31 | # whiten and transform back to real space 32 | whitened = np.fft.irfft(strain_fft / np.sqrt(psd_fft) * np.sqrt(2*dt)) 33 | 34 | return whitened 35 | 36 | 37 | parser = argparse.ArgumentParser(description='Download JSON and 4Hz HDF files for GWOSC event id.') 38 | 39 | parser.add_argument('id', metavar='id', help='GWOSC id (e.g., GW150914-v3)') 40 | parser.add_argument('-C', metavar='dir', default='.', help='input/output folder') 41 | 42 | args = parser.parse_args() 43 | 44 | 45 | # load the JSON event file again 46 | jsondict = json.load(open(os.path.join(args.C, args.id + '.json'), 'rb')) 47 | eventdict = jsondict['events'][args.id] 48 | 49 | # load the HDF strain files 50 | h1file = h5py.File(os.path.join(args.C, f'H1-{args.id}.hdf5'), 'r') 51 | l1file = h5py.File(os.path.join(args.C, f'L1-{args.id}.hdf5'), 'r') 52 | 53 | # get the strain datasets 54 | h1strain = h1file['strain/Strain'] 55 | l1strain = l1file['strain/Strain'] 56 | 57 | # build the time axis from the H1 Strain dataset attributes 58 | h1attrs = h1strain.attrs 59 | gpstime = h1attrs['Xstart'] + h1attrs['Xspacing'] * np.arange(h1attrs['Npoints']) 60 | 61 | # define a window around the event 62 | tevent = eventdict['GPS'] 63 | around = (gpstime > tevent - 0.1) & (gpstime < tevent + 0.1) 64 | 65 | # plot the time series together, reversing L1; add a descriptive title 66 | pp.figure(figsize=(12,3)) 67 | pp.plot(gpstime[around] - tevent, whiten(h1strain)[around]) 68 | pp.plot(gpstime[around] - tevent, -whiten(l1strain)[around]) 69 | pp.title(f"{args.id}: {eventdict['mass_1_source']} + {eventdict['mass_2_source']} Msun") 70 | 71 | # save to a PNG image file 72 | pp.savefig(os.path.join(args.C, args.id + '.png')) 73 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | LinkedIn Learning Exercise Files License Agreement 2 | ================================================== 3 | 4 | This License Agreement (the "Agreement") is a binding legal agreement 5 | between you (as an individual or entity, as applicable) and LinkedIn 6 | Corporation (“LinkedIn”). By downloading or using the LinkedIn Learning 7 | exercise files in this repository (“Licensed Materials”), you agree to 8 | be bound by the terms of this Agreement. If you do not agree to these 9 | terms, do not download or use the Licensed Materials. 10 | 11 | 1. License. 12 | - a. Subject to the terms of this Agreement, LinkedIn hereby grants LinkedIn 13 | members during their LinkedIn Learning subscription a non-exclusive, 14 | non-transferable copyright license, for internal use only, to 1) make a 15 | reasonable number of copies of the Licensed Materials, and 2) make 16 | derivative works of the Licensed Materials for the sole purpose of 17 | practicing skills taught in LinkedIn Learning courses. 18 | - b. Distribution. Unless otherwise noted in the Licensed Materials, subject 19 | to the terms of this Agreement, LinkedIn hereby grants LinkedIn members 20 | with a LinkedIn Learning subscription a non-exclusive, non-transferable 21 | copyright license to distribute the Licensed Materials, except the 22 | Licensed Materials may not be included in any product or service (or 23 | otherwise used) to instruct or educate others. 24 | 25 | 2. Restrictions and Intellectual Property. 26 | - a. You may not to use, modify, copy, make derivative works of, publish, 27 | distribute, rent, lease, sell, sublicense, assign or otherwise transfer the 28 | Licensed Materials, except as expressly set forth above in Section 1. 29 | - b. Linkedin (and its licensors) retains its intellectual property rights 30 | in the Licensed Materials. Except as expressly set forth in Section 1, 31 | LinkedIn grants no licenses. 32 | - c. You indemnify LinkedIn and its licensors and affiliates for i) any 33 | alleged infringement or misappropriation of any intellectual property rights 34 | of any third party based on modifications you make to the Licensed Materials, 35 | ii) any claims arising from your use or distribution of all or part of the 36 | Licensed Materials and iii) a breach of this Agreement. You will defend, hold 37 | harmless, and indemnify LinkedIn and its affiliates (and our and their 38 | respective employees, shareholders, and directors) from any claim or action 39 | brought by a third party, including all damages, liabilities, costs and 40 | expenses, including reasonable attorneys’ fees, to the extent resulting from, 41 | alleged to have resulted from, or in connection with: (a) your breach of your 42 | obligations herein; or (b) your use or distribution of any Licensed Materials. 43 | 44 | 3. Open source. This code may include open source software, which may be 45 | subject to other license terms as provided in the files. 46 | 47 | 4. Warranty Disclaimer. LINKEDIN PROVIDES THE LICENSED MATERIALS ON AN “AS IS” 48 | AND “AS AVAILABLE” BASIS. LINKEDIN MAKES NO REPRESENTATION OR WARRANTY, 49 | WHETHER EXPRESS OR IMPLIED, ABOUT THE LICENSED MATERIALS, INCLUDING ANY 50 | REPRESENTATION THAT THE LICENSED MATERIALS WILL BE FREE OF ERRORS, BUGS OR 51 | INTERRUPTIONS, OR THAT THE LICENSED MATERIALS ARE ACCURATE, COMPLETE OR 52 | OTHERWISE VALID. TO THE FULLEST EXTENT PERMITTED BY LAW, LINKEDIN AND ITS 53 | AFFILIATES DISCLAIM ANY IMPLIED OR STATUTORY WARRANTY OR CONDITION, INCLUDING 54 | ANY IMPLIED WARRANTY OR CONDITION OF MERCHANTABILITY OR FITNESS FOR A 55 | PARTICULAR PURPOSE, AVAILABILITY, SECURITY, TITLE AND/OR NON-INFRINGEMENT. 56 | YOUR USE OF THE LICENSED MATERIALS IS AT YOUR OWN DISCRETION AND RISK, AND 57 | YOU WILL BE SOLELY RESPONSIBLE FOR ANY DAMAGE THAT RESULTS FROM USE OF THE 58 | LICENSED MATERIALS TO YOUR COMPUTER SYSTEM OR LOSS OF DATA. NO ADVICE OR 59 | INFORMATION, WHETHER ORAL OR WRITTEN, OBTAINED BY YOU FROM US OR THROUGH OR 60 | FROM THE LICENSED MATERIALS WILL CREATE ANY WARRANTY OR CONDITION NOT 61 | EXPRESSLY STATED IN THESE TERMS. 62 | 63 | 5. Limitation of Liability. LINKEDIN SHALL NOT BE LIABLE FOR ANY INDIRECT, 64 | INCIDENTAL, SPECIAL, PUNITIVE, CONSEQUENTIAL OR EXEMPLARY DAMAGES, INCLUDING 65 | BUT NOT LIMITED TO, DAMAGES FOR LOSS OF PROFITS, GOODWILL, USE, DATA OR OTHER 66 | INTANGIBLE LOSSES . IN NO EVENT WILL LINKEDIN'S AGGREGATE LIABILITY TO YOU 67 | EXCEED $100. THIS LIMITATION OF LIABILITY SHALL: 68 | - i. APPLY REGARDLESS OF WHETHER (A) YOU BASE YOUR CLAIM ON CONTRACT, TORT, 69 | STATUTE, OR ANY OTHER LEGAL THEORY, (B) WE KNEW OR SHOULD HAVE KNOWN ABOUT 70 | THE POSSIBILITY OF SUCH DAMAGES, OR (C) THE LIMITED REMEDIES PROVIDED IN THIS 71 | SECTION FAIL OF THEIR ESSENTIAL PURPOSE; AND 72 | - ii. NOT APPLY TO ANY DAMAGE THAT LINKEDIN MAY CAUSE YOU INTENTIONALLY OR 73 | KNOWINGLY IN VIOLATION OF THESE TERMS OR APPLICABLE LAW, OR AS OTHERWISE 74 | MANDATED BY APPLICABLE LAW THAT CANNOT BE DISCLAIMED IN THESE TERMS. 75 | 76 | 6. Termination. This Agreement automatically terminates upon your breach of 77 | this Agreement or termination of your LinkedIn Learning subscription. On 78 | termination, all licenses granted under this Agreement will terminate 79 | immediately and you will delete the Licensed Materials. Sections 2-7 of this 80 | Agreement survive any termination of this Agreement. LinkedIn may discontinue 81 | the availability of some or all of the Licensed Materials at any time for any 82 | reason. 83 | 84 | 7. Miscellaneous. This Agreement will be governed by and construed in 85 | accordance with the laws of the State of California without regard to conflict 86 | of laws principles. The exclusive forum for any disputes arising out of or 87 | relating to this Agreement shall be an appropriate federal or state court 88 | sitting in the County of Santa Clara, State of California. If LinkedIn does 89 | not act to enforce a breach of this Agreement, that does not mean that 90 | LinkedIn has waived its right to enforce this Agreement. The Agreement does 91 | not create a partnership, agency relationship, or joint venture between the 92 | parties. Neither party has the power or authority to bind the other or to 93 | create any obligation or responsibility on behalf of the other. You may not, 94 | without LinkedIn’s prior written consent, assign or delegate any rights or 95 | obligations under these terms, including in connection with a change of 96 | control. Any purported assignment and delegation shall be ineffective. The 97 | Agreement shall bind and inure to the benefit of the parties, their respective 98 | successors and permitted assigns. If any provision of the Agreement is 99 | unenforceable, that provision will be modified to render it enforceable to the 100 | extent possible to give effect to the parties’ intentions and the remaining 101 | provisions will not be affected. This Agreement is the only agreement between 102 | you and LinkedIn regarding the Licensed Materials, and supersedes all prior 103 | agreements relating to the Licensed Materials. 104 | 105 | Last Updated: March 2019 106 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Copyright 2021 LinkedIn Corporation 2 | All Rights Reserved. 3 | 4 | Licensed under the LinkedIn Learning Exercise File License (the "License"). 5 | See LICENSE in the project root for license information. 6 | 7 | Please note, this project may automatically load third party code from external 8 | repositories (for example, NPM modules, Composer packages, or other dependencies). 9 | If so, such third party code may be subject to other license terms than as set 10 | forth above. In addition, such third party code may also depend on and load 11 | multiple tiers of dependencies. Please review the applicable licenses of the 12 | additional dependencies. 13 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python for Engineers and Scientists 2 | This is the repository for the LinkedIn Learning course Python for Engineers and Scientists. The full course is available from [LinkedIn Learning][lil-course-url]. 3 | 4 | ![Python for Engineers and Scientists][lil-thumbnail-url] 5 | 6 | This course offers scientists and engineers (ranging from students of those disciplines to experienced professionals) a dedicated, empowering introduction to Python for scientific and engineering applications. Theoretical astrophysicist and Python enthusiast Michele Vallisneri explains how Python can help you become a better engineer or physicist by making your work more efficient, accurate, and agile. Michele walks you through installing Python for macOS, Windows, and Linux, as well as setting up Jupyter notebooks. He explains how you can make Python fast using NumPy arrays, the SciPy library, Numba, and Cython. Michele then tackles ways to ensure your code is correct with tools for symbolic computation, differential equations, interpolation, and more. He finishes up with ideas to make your computational life easier with Python, including JSON, pandas, HDF5, automation with Python scripts, and scientific workflows with Snakemake. 7 | 8 | ## Instructions 9 | This repository has branches for each of the videos in the course. You can use the branch pop up menu in github to switch to a specific branch and take a look at the course at that stage, or you can add `/tree/BRANCH_NAME` to the URL to go to the branch you want to access. 10 | 11 | ## Branches 12 | The branches are structured to correspond to the videos in the course. The naming convention is `CHAPTER#_MOVIE#`. As an example, the branch named `02_03` corresponds to the second chapter and the third video in that chapter. 13 | Some branches will have a beginning and an end state. These are marked with the letters `b` for "beginning" and `e` for "end". The `b` branch contains the code as it is at the beginning of the movie. The `e` branch contains the code as it is at the end of the movie. The `main` branch holds the final state of the code when in the course. 14 | 15 | When switching from one exercise files branch to the next after making changes to the files, you may get a message like this: 16 | 17 | error: Your local changes to the following files would be overwritten by checkout: [files] 18 | Please commit your changes or stash them before you switch branches. 19 | Aborting 20 | 21 | To resolve this issue: 22 | 23 | Add changes to git using this command: git add . 24 | Commit changes using this command: git commit -m "some message" 25 | 26 | _See the readme file in the main branch for updated instructions and information._ 27 | ## Instructions 28 | This repository has folders for each of the main chapters in the course, named `Ch02`, `Ch03`, and `Ch04`. Most videos in each chapter have a corresponding Jupyter notebook, named `CHAPTER#_MOVIE#_TOPIC.ipynb`. The notebooks have a beginning and an end state; the end-state notebooks are marked as `CHAPTER#_MOVIE#_TOPIC-complete.ipynb`. 29 | 30 | ## Installing 31 | 1. To use these exercise files, you must have the following installed: 32 | - Python 3.8; NumPy, SciPy, SymPy, AstroPy, Pandas, Matplotlib, Cython, Numba, Requests, Pillow (PIL), Snakemake, Jupyter; C/C++ compilers; Fortran compiler (optional) and Python fortran-magic. 33 | 2. Clone this repository into your local machine using the terminal (Mac), CMD (Windows), or a GUI tool like SourceTree. 34 | 35 | 36 | ### Instructor 37 | 38 | Michele Vallisneri 39 | 40 | Senior Research Scientist, NASA Jet Propulsion Laboratory 41 | 42 | 43 | 44 | Check out my other courses on [LinkedIn Learning](https://www.linkedin.com/learning/instructors/michele-vallisneri). 45 | 46 | [lil-course-url]: https://www.linkedin.com/learning/python-for-engineers-and-scientists 47 | [lil-thumbnail-url]: https://cdn.lynda.com/course/2425360/2425360-1632161420283-16x9.jpg 48 | 49 | 50 | 51 | 52 | --------------------------------------------------------------------------------