├── 1-GettingStarted ├── .ipynb_checkpoints │ ├── 1-Getting Started-checkpoint.ipynb │ └── Untitled-checkpoint.ipynb ├── 1-GettingStarted.html ├── 1-GettingStarted.ipynb ├── 1-GettingStarted.py ├── smartfunctions.py └── smartscript.py ├── 10-ErrorHandling ├── 10-ErrorHandling.html ├── 10-ErrorHandling.ipynb └── data1.txt ├── 11-Namespaces ├── 1-GettingStarted │ └── 1-GettingStarted │ │ ├── .ipynb_checkpoints │ │ ├── 1-Getting Started-checkpoint.ipynb │ │ ├── 1-GettingStarted-checkpoint.ipynb │ │ └── Untitled-checkpoint.ipynb │ │ ├── 1-GettingStarted.html │ │ ├── 1-GettingStarted.ipynb │ │ ├── __pycache__ │ │ └── smartfunctions.cpython-35.pyc │ │ └── smartfunctions.py ├── 11-Namespaces.html └── 11-Namespaces.ipynb ├── 12-InputOutput ├── 12-InputOutput.ipynb ├── datafile.dat ├── tem.dat ├── test.jpg └── test_small.jpg ├── 13-Testing ├── 13-Testing.ipynb ├── TestIdentity.py ├── TestQR.py ├── TestString.py ├── Testing_all.py ├── Tests_several.py ├── bisection.py ├── find_elements.py └── find_in_file.py ├── 14-comprehensive-example ├── 14-Comprehensive-example.html ├── 14-Comprehensive-example.ipynb ├── cluster1.pdf ├── cluster1.png ├── ivp_example.pdf ├── ivp_example.png ├── spectral_4class.pdf └── spectral_4class.png ├── 15-symbolicmanipulations ├── 15-SymbolicComputations.html └── 15-SymbolicComputations.ipynb ├── 2-VariablesandBasicTypes ├── .ipynb_checkpoints │ └── 2-VariablesandBasicTypes-checkpoint.ipynb ├── 2-VariablesandBasicTypes.html ├── 2-VariablesandBasicTypes.ipynb └── 2-VariablesandBasicTypes.py ├── 3-Container ├── .ipynb_checkpoints │ └── 3-Container Types-checkpoint.ipynb ├── 3-Container Types.ipynb ├── 3-Container+Types.html └── 3-Container+Types.py ├── 4-LinearAlgebra ├── .ipynb_checkpoints │ └── 4-LinearAlgebra-checkpoint.ipynb ├── 4-LinearAlgebra.html ├── 4-LinearAlgebra.ipynb └── 4-LinearAlgebra.py ├── 5-AdvancedArrayConcepts ├── .ipynb_checkpoints │ └── 5-AdvancedArrayConcepts-checkpoint.ipynb ├── 5-AdvancedArrayConcepts.html ├── 5-AdvancedArrayConcepts.ipynb └── 5-AdvancedArrayConcepts.py ├── 6-plotting ├── .ipynb_checkpoints │ └── 6-Plotting-checkpoint.ipynb ├── 6-Plotting.html ├── 6-Plotting.ipynb ├── amp_mod_sin0.pdf ├── amp_mod_sin1.pdf ├── amp_mod_sin2.pdf ├── amp_mod_sin2a.png ├── amp_mod_sin3.pdf ├── amp_mod_sin4.pdf ├── circle_evolution.swf ├── figobjects.py ├── mandelbrod.py ├── sin03.png ├── test.pdf └── test.svg ├── 7-Functions ├── .ipynb_checkpoints │ └── 7-Functions-checkpoint.ipynb ├── 7-Functions.html └── 7-Functions.ipynb ├── 8-Classes ├── .ipynb_checkpoints │ └── 8-Classes-checkpoint.ipynb ├── 8-Classes.html └── 8-Classes.ipynb ├── 9-iterators ├── .ipynb_checkpoints │ ├── 9-Iterators-checkpoint.ipynb │ ├── Chapter 9 Iterators-checkpoint.ipynb │ ├── Untitled-checkpoint.ipynb │ └── Untitled1-checkpoint.ipynb ├── 9-Iterators.html ├── 9-Iterators.ipynb ├── Euler.py └── seqacceleration.py ├── LICENSE └── README.md /1-GettingStarted/1-GettingStarted.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 1-Getting Started\n", 8 | "\n", 9 | "Always run this statement first, when working with this book:" 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": null, 15 | "metadata": { 16 | "collapsed": true 17 | }, 18 | "outputs": [], 19 | "source": [ 20 | "from scipy import *\n", 21 | "\n", 22 | "from IPython.core.interactiveshell import InteractiveShell\n", 23 | "InteractiveShell.ast_node_interactivity = \"all\"" 24 | ] 25 | }, 26 | { 27 | "cell_type": "markdown", 28 | "metadata": {}, 29 | "source": [ 30 | "## Numbers" 31 | ] 32 | }, 33 | { 34 | "cell_type": "code", 35 | "execution_count": null, 36 | "metadata": { 37 | "collapsed": false 38 | }, 39 | "outputs": [], 40 | "source": [ 41 | "2 ** (2 + 2)\n", 42 | "1j ** 2 # A complex number\n", 43 | "1. + 3.0j # Another complex number" 44 | ] 45 | }, 46 | { 47 | "cell_type": "markdown", 48 | "metadata": {}, 49 | "source": [ 50 | "## Strings" 51 | ] 52 | }, 53 | { 54 | "cell_type": "code", 55 | "execution_count": null, 56 | "metadata": { 57 | "collapsed": false, 58 | "scrolled": true 59 | }, 60 | "outputs": [], 61 | "source": [ 62 | "'valid string'\n", 63 | "\n", 64 | "\"string with double quotes\"\n", 65 | "\n", 66 | "\"you shouldn't forget comments\"\n", 67 | "\n", 68 | "'these are double quotes: \"..\" '" 69 | ] 70 | }, 71 | { 72 | "cell_type": "code", 73 | "execution_count": null, 74 | "metadata": { 75 | "collapsed": false 76 | }, 77 | "outputs": [], 78 | "source": [ 79 | "\"\"\"This is\n", 80 | " a long,\n", 81 | " long string\"\"\"" 82 | ] 83 | }, 84 | { 85 | "cell_type": "markdown", 86 | "metadata": {}, 87 | "source": [ 88 | "## Variables" 89 | ] 90 | }, 91 | { 92 | "cell_type": "code", 93 | "execution_count": null, 94 | "metadata": { 95 | "collapsed": false 96 | }, 97 | "outputs": [], 98 | "source": [ 99 | "x = [3, 4] # a list object is created\n", 100 | "y = x # this object now has two labels: x and y\n", 101 | "del x # we delete one of the labels\n", 102 | "del y # both labels are removed: the object is deleted" 103 | ] 104 | }, 105 | { 106 | "cell_type": "code", 107 | "execution_count": null, 108 | "metadata": { 109 | "collapsed": false 110 | }, 111 | "outputs": [], 112 | "source": [ 113 | "\n", 114 | "x = [3, 4] # a list object is created\n", 115 | "print(x)" 116 | ] 117 | }, 118 | { 119 | "cell_type": "markdown", 120 | "metadata": {}, 121 | "source": [ 122 | "## Lists" 123 | ] 124 | }, 125 | { 126 | "cell_type": "code", 127 | "execution_count": null, 128 | "metadata": { 129 | "collapsed": false 130 | }, 131 | "outputs": [], 132 | "source": [ 133 | "L1 = [5, 6]\n", 134 | "\n", 135 | "L1[0] # 5\n", 136 | "\n", 137 | "L1[1] # 6\n", 138 | "\n", 139 | "L1[2] # raises IndexError" 140 | ] 141 | }, 142 | { 143 | "cell_type": "code", 144 | "execution_count": null, 145 | "metadata": { 146 | "collapsed": false 147 | }, 148 | "outputs": [], 149 | "source": [ 150 | "L2 = ['a', 1, [3, 4]]\n", 151 | "\n", 152 | "L2[0] # 'a'\n", 153 | "\n", 154 | "L2[2][0] # 3\n", 155 | "\n", 156 | "L2[-1] # last element: [3,4]\n", 157 | "\n", 158 | "L2[-2] # second to last: 1" 159 | ] 160 | }, 161 | { 162 | "cell_type": "code", 163 | "execution_count": null, 164 | "metadata": { 165 | "collapsed": false 166 | }, 167 | "outputs": [], 168 | "source": [ 169 | "print(list(range(5)))" 170 | ] 171 | }, 172 | { 173 | "cell_type": "code", 174 | "execution_count": null, 175 | "metadata": { 176 | "collapsed": false 177 | }, 178 | "outputs": [], 179 | "source": [ 180 | "len(['a', 1, 2, 34])" 181 | ] 182 | }, 183 | { 184 | "cell_type": "code", 185 | "execution_count": null, 186 | "metadata": { 187 | "collapsed": false 188 | }, 189 | "outputs": [], 190 | "source": [ 191 | "L = ['a', 'b', 'c']\n", 192 | "L[-1] # 'c'\n", 193 | "\n", 194 | "L.append('d')\n", 195 | "L # L is now ['a', 'b', 'c', 'd']\n", 196 | "\n", 197 | "L[-1] # 'd'" 198 | ] 199 | }, 200 | { 201 | "cell_type": "markdown", 202 | "metadata": {}, 203 | "source": [ 204 | "### Operations on Lists" 205 | ] 206 | }, 207 | { 208 | "cell_type": "code", 209 | "execution_count": null, 210 | "metadata": { 211 | "collapsed": false 212 | }, 213 | "outputs": [], 214 | "source": [ 215 | "L1 = [1, 2]\n", 216 | "L2 = [3, 4]\n", 217 | "L = L1 + L2 # [1, 2, 3, 4]\n", 218 | "L" 219 | ] 220 | }, 221 | { 222 | "cell_type": "code", 223 | "execution_count": null, 224 | "metadata": { 225 | "collapsed": false 226 | }, 227 | "outputs": [], 228 | "source": [ 229 | "L = [1, 2]\n", 230 | "3 * L # [1, 2, 1, 2, 1, 2]" 231 | ] 232 | }, 233 | { 234 | "cell_type": "markdown", 235 | "metadata": {}, 236 | "source": [ 237 | "## Boolean Expressions" 238 | ] 239 | }, 240 | { 241 | "cell_type": "code", 242 | "execution_count": null, 243 | "metadata": { 244 | "collapsed": false 245 | }, 246 | "outputs": [], 247 | "source": [ 248 | "2 >= 4 # False\n", 249 | "2 < 3 < 4 # True\n", 250 | "2 < 3 and 3 < 2 # False\n", 251 | "2 != 3 < 4 or False # True\n", 252 | "2 <= 2 and 2 >= 2 # True\n", 253 | "not 2 == 3 # True\n", 254 | "not False or True and False # True!" 255 | ] 256 | }, 257 | { 258 | "cell_type": "markdown", 259 | "metadata": {}, 260 | "source": [ 261 | "## Repeating statements by loops" 262 | ] 263 | }, 264 | { 265 | "cell_type": "code", 266 | "execution_count": null, 267 | "metadata": { 268 | "collapsed": false 269 | }, 270 | "outputs": [], 271 | "source": [ 272 | "L = [1, 2, 10]\n", 273 | "for s in L:\n", 274 | " print(s * 2) # output: 2 4 20" 275 | ] 276 | }, 277 | { 278 | "cell_type": "markdown", 279 | "metadata": {}, 280 | "source": [ 281 | "### Repeating a task" 282 | ] 283 | }, 284 | { 285 | "cell_type": "code", 286 | "execution_count": null, 287 | "metadata": { 288 | "collapsed": false 289 | }, 290 | "outputs": [], 291 | "source": [ 292 | "n = 30\n", 293 | "k=0\n", 294 | "for iteration in range(n):\n", 295 | " k+= iteration #do_something(this gets executed n times)\n", 296 | "k" 297 | ] 298 | }, 299 | { 300 | "cell_type": "markdown", 301 | "metadata": {}, 302 | "source": [ 303 | "### Break and else" 304 | ] 305 | }, 306 | { 307 | "cell_type": "code", 308 | "execution_count": null, 309 | "metadata": { 310 | "collapsed": false, 311 | "scrolled": false 312 | }, 313 | "outputs": [], 314 | "source": [ 315 | "threshold=30\n", 316 | "x_values=range(20)\n", 317 | "\n", 318 | "for x in x_values:\n", 319 | " if x > threshold:\n", 320 | " break\n", 321 | "print(x)" 322 | ] 323 | }, 324 | { 325 | "cell_type": "code", 326 | "execution_count": null, 327 | "metadata": { 328 | "collapsed": false 329 | }, 330 | "outputs": [], 331 | "source": [ 332 | "for x in x_values:\n", 333 | " if x > threshold:\n", 334 | " break\n", 335 | "else:\n", 336 | " print(\"all the x are below the threshold\")" 337 | ] 338 | }, 339 | { 340 | "cell_type": "markdown", 341 | "metadata": {}, 342 | "source": [ 343 | "## Conditional Statements" 344 | ] 345 | }, 346 | { 347 | "cell_type": "code", 348 | "execution_count": null, 349 | "metadata": { 350 | "collapsed": false 351 | }, 352 | "outputs": [], 353 | "source": [ 354 | "# The absolute value\n", 355 | "x=-25\n", 356 | "\n", 357 | "if x >= 0:\n", 358 | " print(x)\n", 359 | "else:\n", 360 | " print(-x)" 361 | ] 362 | }, 363 | { 364 | "cell_type": "markdown", 365 | "metadata": {}, 366 | "source": [ 367 | "## Encapsulating code by functions\n", 368 | " \n", 369 | "Example:\n", 370 | "$$x \\mapsto f(x) := 2x + 1$$" 371 | ] 372 | }, 373 | { 374 | "cell_type": "code", 375 | "execution_count": null, 376 | "metadata": { 377 | "collapsed": false 378 | }, 379 | "outputs": [], 380 | "source": [ 381 | "def f(x):\n", 382 | " return 2*x + 1\n" 383 | ] 384 | }, 385 | { 386 | "cell_type": "markdown", 387 | "metadata": {}, 388 | "source": [ 389 | "Calling this function:" 390 | ] 391 | }, 392 | { 393 | "cell_type": "code", 394 | "execution_count": null, 395 | "metadata": { 396 | "collapsed": false 397 | }, 398 | "outputs": [], 399 | "source": [ 400 | "f(2) # 5\n", 401 | "\n", 402 | "f(1) # 3" 403 | ] 404 | }, 405 | { 406 | "cell_type": "markdown", 407 | "metadata": {}, 408 | "source": [ 409 | "## Scripts and modules" 410 | ] 411 | }, 412 | { 413 | "cell_type": "code", 414 | "execution_count": null, 415 | "metadata": { 416 | "collapsed": false 417 | }, 418 | "outputs": [], 419 | "source": [ 420 | "def f(x):\n", 421 | " return 2*x + 1\n", 422 | "\n", 423 | "z = []\n", 424 | "for x in range(10):\n", 425 | " if f(x) > pi:\n", 426 | " z.append(x)\n", 427 | " else:\n", 428 | " z.append(-1)\n", 429 | "print(z)" 430 | ] 431 | }, 432 | { 433 | "cell_type": "code", 434 | "execution_count": null, 435 | "metadata": { 436 | "collapsed": false 437 | }, 438 | "outputs": [], 439 | "source": [ 440 | "exec(open('smartscript.py').read())\n", 441 | "%run smartscript" 442 | ] 443 | }, 444 | { 445 | "cell_type": "markdown", 446 | "metadata": {}, 447 | "source": [ 448 | "## Simple modules - collecting Functions\n", 449 | "\n", 450 | "For the next example to work, you need a file `smartfunctions.py`in the same folder as this notebook: " 451 | ] 452 | }, 453 | { 454 | "cell_type": "code", 455 | "execution_count": null, 456 | "metadata": { 457 | "collapsed": true 458 | }, 459 | "outputs": [], 460 | "source": [ 461 | "def f(x):\n", 462 | " return 2*x + 1\n", 463 | "def g(x):\n", 464 | " return x**2 + 4*x - 5\n", 465 | "def h(x):\n", 466 | " return 1/f(x)" 467 | ] 468 | }, 469 | { 470 | "cell_type": "markdown", 471 | "metadata": {}, 472 | "source": [ 473 | "### Using modules and namespaces" 474 | ] 475 | }, 476 | { 477 | "cell_type": "code", 478 | "execution_count": null, 479 | "metadata": { 480 | "collapsed": false 481 | }, 482 | "outputs": [], 483 | "source": [ 484 | "import smartfunctions\n", 485 | "print(smartfunctions.f(2))\n", 486 | "\n", 487 | "from smartfunctions import g #import just this one function\n", 488 | "print(g(1))\n", 489 | "\n", 490 | "from smartfunctions import * #import all\n", 491 | "print(h(2)*f(2))\n" 492 | ] 493 | }, 494 | { 495 | "cell_type": "markdown", 496 | "metadata": {}, 497 | "source": [ 498 | "## Interpreter" 499 | ] 500 | }, 501 | { 502 | "cell_type": "code", 503 | "execution_count": null, 504 | "metadata": { 505 | "collapsed": true 506 | }, 507 | "outputs": [], 508 | "source": [ 509 | "def f(x):\n", 510 | " return y**2\n", 511 | "a = 3 # here both a and f are defined" 512 | ] 513 | }, 514 | { 515 | "cell_type": "code", 516 | "execution_count": null, 517 | "metadata": { 518 | "collapsed": false 519 | }, 520 | "outputs": [], 521 | "source": [ 522 | "f(2) # error, y is not defined" 523 | ] 524 | } 525 | ], 526 | "metadata": { 527 | "anaconda-cloud": {}, 528 | "kernelspec": { 529 | "display_name": "Python 3", 530 | "language": "python", 531 | "name": "python3" 532 | }, 533 | "language_info": { 534 | "codemirror_mode": { 535 | "name": "ipython", 536 | "version": 3 537 | }, 538 | "file_extension": ".py", 539 | "mimetype": "text/x-python", 540 | "name": "python", 541 | "nbconvert_exporter": "python", 542 | "pygments_lexer": "ipython3", 543 | "version": "3.5.2" 544 | } 545 | }, 546 | "nbformat": 4, 547 | "nbformat_minor": 0 548 | } 549 | -------------------------------------------------------------------------------- /1-GettingStarted/1-GettingStarted.py: -------------------------------------------------------------------------------- 1 | 2 | # coding: utf-8 3 | 4 | # # 1-Getting Started 5 | # 6 | # Always run this statement first, when working with this book: 7 | 8 | # In[1]: 9 | 10 | from scipy import * 11 | 12 | from IPython.core.interactiveshell import InteractiveShell 13 | InteractiveShell.ast_node_interactivity = "all" 14 | 15 | 16 | # ## Numbers 17 | 18 | # In[2]: 19 | 20 | 2 ** (2 + 2) 21 | 1j ** 2 # A complex number 22 | 1. + 3.0j # Another complex number 23 | 24 | 25 | # ## Strings 26 | 27 | # In[3]: 28 | 29 | 'valid string' 30 | 31 | "string with double quotes" 32 | 33 | "you shouldn't forget comments" 34 | 35 | 'these are double quotes: ".." ' 36 | 37 | 38 | # In[4]: 39 | 40 | """This is 41 | a long, 42 | long string""" 43 | 44 | 45 | # ## Variables 46 | 47 | # In[5]: 48 | 49 | x = [3, 4] # a list object is created 50 | y = x # this object now has two labels: x and y 51 | del x # we delete one of the labels 52 | del y # both labels are removed: the object is deleted 53 | 54 | 55 | # In[6]: 56 | 57 | 58 | x = [3, 4] # a list object is created 59 | print(x) 60 | 61 | 62 | # ## Lists 63 | 64 | # In[7]: 65 | 66 | L1 = [5, 6] 67 | 68 | L1[0] # 5 69 | 70 | L1[1] # 6 71 | 72 | L1[2] # raises IndexError 73 | 74 | 75 | # In[8]: 76 | 77 | L2 = ['a', 1, [3, 4]] 78 | 79 | L2[0] # 'a' 80 | 81 | L2[2][0] # 3 82 | 83 | L2[-1] # last element: [3,4] 84 | 85 | L2[-2] # second to last: 1 86 | 87 | 88 | # In[9]: 89 | 90 | print(list(range(5))) 91 | 92 | 93 | # In[10]: 94 | 95 | len(['a', 1, 2, 34]) 96 | 97 | 98 | # In[11]: 99 | 100 | L = ['a', 'b', 'c'] 101 | L[-1] # 'c' 102 | 103 | L.append('d') 104 | L # L is now ['a', 'b', 'c', 'd'] 105 | 106 | L[-1] # 'd' 107 | 108 | 109 | # ### Operations on Lists 110 | 111 | # In[12]: 112 | 113 | L1 = [1, 2] 114 | L2 = [3, 4] 115 | L = L1 + L2 # [1, 2, 3, 4] 116 | L 117 | 118 | 119 | # In[13]: 120 | 121 | L = [1, 2] 122 | 3 * L # [1, 2, 1, 2, 1, 2] 123 | 124 | 125 | # ## Boolean Expressions 126 | 127 | # In[14]: 128 | 129 | 2 >= 4 # False 130 | 2 < 3 < 4 # True 131 | 2 < 3 and 3 < 2 # False 132 | 2 != 3 < 4 or False # True 133 | 2 <= 2 and 2 >= 2 # True 134 | not 2 == 3 # True 135 | not False or True and False # True! 136 | 137 | 138 | # ## Repeating statements by loops 139 | 140 | # In[15]: 141 | 142 | L = [1, 2, 10] 143 | for s in L: 144 | print(s * 2) # output: 2 4 20 145 | 146 | 147 | # ### Repeating a task 148 | 149 | # In[16]: 150 | 151 | n = 30 152 | k=0 153 | for iteration in range(n): 154 | k+= iteration #do_something(this gets executed n times) 155 | k 156 | 157 | 158 | # ### Break and else 159 | 160 | # In[17]: 161 | 162 | threshold=30 163 | x_values=range(20) 164 | 165 | for x in x_values: 166 | if x > threshold: 167 | break 168 | print(x) 169 | 170 | 171 | # In[18]: 172 | 173 | for x in x_values: 174 | if x > threshold: 175 | break 176 | else: 177 | print("all the x are below the threshold") 178 | 179 | 180 | # ## Conditional Statements 181 | 182 | # In[19]: 183 | 184 | # The absolute value 185 | x=-25 186 | 187 | if x >= 0: 188 | print(x) 189 | else: 190 | print(-x) 191 | 192 | 193 | # ## Encapsulating code by functions 194 | # 195 | # Example: 196 | # $$x \mapsto f(x) := 2x + 1$$ 197 | 198 | # In[20]: 199 | 200 | def f(x): 201 | return 2*x + 1 202 | 203 | 204 | # Calling this function: 205 | 206 | # In[21]: 207 | 208 | f(2) # 5 209 | 210 | f(1) # 3 211 | 212 | 213 | # ## Scripts and modules 214 | 215 | # In[22]: 216 | 217 | def f(x): 218 | return 2*x + 1 219 | 220 | z = [] 221 | for x in range(10): 222 | if f(x) > pi: 223 | z.append(x) 224 | else: 225 | z.append(-1) 226 | print(z) 227 | 228 | 229 | # In[23]: 230 | 231 | exec(open('smartscript.py').read()) 232 | get_ipython().magic('run smartscript') 233 | 234 | 235 | # ## Simple modules - collecting Functions 236 | # 237 | # For the next example to work, you need a file `smartfunctions.py`in the same folder as this notebook: 238 | 239 | # In[24]: 240 | 241 | def f(x): 242 | return 2*x + 1 243 | def g(x): 244 | return x**2 + 4*x - 5 245 | def h(x): 246 | return 1/f(x) 247 | 248 | 249 | # ### Using modules and namespaces 250 | 251 | # In[25]: 252 | 253 | import smartfunctions 254 | print(smartfunctions.f(2)) 255 | 256 | from smartfunctions import g #import just this one function 257 | print(g(1)) 258 | 259 | from smartfunctions import * #import all 260 | print(h(2)*f(2)) 261 | 262 | 263 | # ## Interpreter 264 | 265 | # In[26]: 266 | 267 | def f(x): 268 | return y**2 269 | a = 3 # here both a and f are defined 270 | 271 | 272 | # In[27]: 273 | 274 | f(2) # error, y is not defined 275 | 276 | -------------------------------------------------------------------------------- /1-GettingStarted/smartfunctions.py: -------------------------------------------------------------------------------- 1 | def f(x): 2 | return 2*x + 1 3 | def g(x): 4 | return x**2 + 4*x - 5 5 | def h(x): 6 | return 1/f(x) 7 | -------------------------------------------------------------------------------- /1-GettingStarted/smartscript.py: -------------------------------------------------------------------------------- 1 | from scipy import * 2 | 3 | def f(x): 4 | return 2*x + 1 5 | 6 | z = [] 7 | for x in range(10): 8 | if f(x) > pi: 9 | z.append(x) 10 | else: 11 | z.append(-1) 12 | print(z) 13 | -------------------------------------------------------------------------------- /10-ErrorHandling/10-ErrorHandling.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 10 - Error Handling" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": { 14 | "collapsed": true 15 | }, 16 | "outputs": [], 17 | "source": [ 18 | "from scipy import *" 19 | ] 20 | }, 21 | { 22 | "cell_type": "markdown", 23 | "metadata": {}, 24 | "source": [ 25 | "## What are exceptions?" 26 | ] 27 | }, 28 | { 29 | "cell_type": "code", 30 | "execution_count": null, 31 | "metadata": { 32 | "collapsed": false 33 | }, 34 | "outputs": [], 35 | "source": [ 36 | "def f(x):\n", 37 | " return 1/x\n", 38 | "f(0) # returns a ZeroDivisionError" 39 | ] 40 | }, 41 | { 42 | "cell_type": "code", 43 | "execution_count": null, 44 | "metadata": { 45 | "collapsed": false 46 | }, 47 | "outputs": [], 48 | "source": [ 49 | "a = arange(8.0)\n", 50 | "a[3]='string'" 51 | ] 52 | }, 53 | { 54 | "cell_type": "markdown", 55 | "metadata": {}, 56 | "source": [ 57 | "## Basic Principles\n", 58 | "### Raising Exceptions\n", 59 | "\n", 60 | "Example: file does not exist " 61 | ] 62 | }, 63 | { 64 | "cell_type": "markdown", 65 | "metadata": { 66 | "collapsed": false 67 | }, 68 | "source": [ 69 | "try:\n", 70 | " f = open('data.txt', 'r')\n", 71 | " data = f.readline()\n", 72 | " value = float(data)\n", 73 | "except OSError as oe:\n", 74 | " print(\"{}: {}\".format(oe.strerror, oe.filename))\n", 75 | "except ValueError:\n", 76 | " print(\"Could not convert data to float.\")" 77 | ] 78 | }, 79 | { 80 | "cell_type": "markdown", 81 | "metadata": { 82 | "collapsed": true 83 | }, 84 | "source": [ 85 | "Example file exists" 86 | ] 87 | }, 88 | { 89 | "cell_type": "code", 90 | "execution_count": null, 91 | "metadata": { 92 | "collapsed": false 93 | }, 94 | "outputs": [], 95 | "source": [ 96 | "try:\n", 97 | " f = open('data1.txt', 'r')\n", 98 | " data = f.readline()\n", 99 | " value = float(data)\n", 100 | "except OSError as oe:\n", 101 | " print(\"{}: {}\".format(oe.strerror, oe.filename))\n", 102 | "except ValueError:\n", 103 | " print(\"Could not convert data to float.\")" 104 | ] 105 | }, 106 | { 107 | "cell_type": "markdown", 108 | "metadata": {}, 109 | "source": [ 110 | "Example: Permission denied" 111 | ] 112 | }, 113 | { 114 | "cell_type": "code", 115 | "execution_count": null, 116 | "metadata": { 117 | "collapsed": false 118 | }, 119 | "outputs": [], 120 | "source": [ 121 | "try:\n", 122 | " f = open('data2.txt', 'r')\n", 123 | " data = f.readline()\n", 124 | " value = float(data)\n", 125 | "except OSError as oe:\n", 126 | " print(\"{}: {}\".format(oe.strerror, oe.filename))\n", 127 | "except ValueError:\n", 128 | " print(\"Could not convert data to float.\")" 129 | ] 130 | }, 131 | { 132 | "cell_type": "code", 133 | "execution_count": null, 134 | "metadata": { 135 | "collapsed": true 136 | }, 137 | "outputs": [], 138 | "source": [ 139 | "try:\n", 140 | " f = open('data1.txt', 'w')\n", 141 | " # some function that does something with the file\n", 142 | " f.write('some text')\n", 143 | "except:\n", 144 | " print('Some message')\n", 145 | "finally:\n", 146 | " f.close() " 147 | ] 148 | }, 149 | { 150 | "cell_type": "markdown", 151 | "metadata": {}, 152 | "source": [ 153 | "### User-defined Exceptions" 154 | ] 155 | }, 156 | { 157 | "cell_type": "code", 158 | "execution_count": null, 159 | "metadata": { 160 | "collapsed": false 161 | }, 162 | "outputs": [], 163 | "source": [ 164 | "class MyError(Exception):\n", 165 | " def __init__(self, expr):\n", 166 | " self.expr = expr\n", 167 | " def __str__(self):\n", 168 | " return str(self.expr)\n", 169 | "\n", 170 | "\n", 171 | "try:\n", 172 | " x = random.rand()\n", 173 | " if x < 0.5: \n", 174 | " raise MyError(x)\n", 175 | "except MyError as e:\n", 176 | " print(\"Random number too small\", e.expr)\n", 177 | "else:\n", 178 | " print(x)" 179 | ] 180 | }, 181 | { 182 | "cell_type": "markdown", 183 | "metadata": {}, 184 | "source": [ 185 | "### Context Managers -- the `with` statement" 186 | ] 187 | }, 188 | { 189 | "cell_type": "code", 190 | "execution_count": null, 191 | "metadata": { 192 | "collapsed": false 193 | }, 194 | "outputs": [], 195 | "source": [ 196 | "with open('data1.txt', 'w') as f:\n", 197 | " f.write('another.text')" 198 | ] 199 | }, 200 | { 201 | "cell_type": "code", 202 | "execution_count": null, 203 | "metadata": { 204 | "collapsed": false 205 | }, 206 | "outputs": [], 207 | "source": [ 208 | "f.closed" 209 | ] 210 | }, 211 | { 212 | "cell_type": "code", 213 | "execution_count": null, 214 | "metadata": { 215 | "collapsed": false 216 | }, 217 | "outputs": [], 218 | "source": [ 219 | "import numpy as np\n", 220 | "\n", 221 | "with np.errstate(invalid='ignore'):\n", 222 | " print(np.sqrt(-1)) # prints 'nan'\n", 223 | "\n", 224 | "with errstate(invalid='warn'):\n", 225 | " print(np.sqrt(-1)) # prints 'nan' and 'RuntimeWarning: invalid value encountered in sqrt'\n", 226 | "\n", 227 | "with errstate(invalid='raise'):\n", 228 | " print(np.sqrt(-1)) # prints nothing and raises FloatingPointError" 229 | ] 230 | }, 231 | { 232 | "cell_type": "markdown", 233 | "metadata": {}, 234 | "source": [ 235 | "## Debugging" 236 | ] 237 | }, 238 | { 239 | "cell_type": "code", 240 | "execution_count": null, 241 | "metadata": { 242 | "collapsed": false 243 | }, 244 | "outputs": [], 245 | "source": [ 246 | "import pdb \n", 247 | "\n", 248 | "def complex_to_polar(z):\n", 249 | " pdb.set_trace()\n", 250 | " r = sqrt(z.real ** 2 + z.imag ** 2)\n", 251 | " phi = arctan2(z.imag, z.real)\n", 252 | " return (r,phi)\n", 253 | "\n", 254 | "z = 3 + 5j\n", 255 | "r,phi = complex_to_polar(z)\n", 256 | "\n", 257 | "print(r,phi)" 258 | ] 259 | } 260 | ], 261 | "metadata": { 262 | "anaconda-cloud": {}, 263 | "kernelspec": { 264 | "display_name": "Python [conda root]", 265 | "language": "python", 266 | "name": "conda-root-py" 267 | }, 268 | "language_info": { 269 | "codemirror_mode": { 270 | "name": "ipython", 271 | "version": 3 272 | }, 273 | "file_extension": ".py", 274 | "mimetype": "text/x-python", 275 | "name": "python", 276 | "nbconvert_exporter": "python", 277 | "pygments_lexer": "ipython3", 278 | "version": "3.5.2" 279 | } 280 | }, 281 | "nbformat": 4, 282 | "nbformat_minor": 1 283 | } 284 | -------------------------------------------------------------------------------- /10-ErrorHandling/data1.txt: -------------------------------------------------------------------------------- 1 | another.text -------------------------------------------------------------------------------- /11-Namespaces/1-GettingStarted/1-GettingStarted/__pycache__/smartfunctions.cpython-35.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Scientific-Computing-with-Python-3/1333ac3fe4f90cb9f157682bf2d3a80824528032/11-Namespaces/1-GettingStarted/1-GettingStarted/__pycache__/smartfunctions.cpython-35.pyc -------------------------------------------------------------------------------- /11-Namespaces/1-GettingStarted/1-GettingStarted/smartfunctions.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Scientific-Computing-with-Python-3/1333ac3fe4f90cb9f157682bf2d3a80824528032/11-Namespaces/1-GettingStarted/1-GettingStarted/smartfunctions.py -------------------------------------------------------------------------------- /11-Namespaces/11-Namespaces.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 11-Namespaces, Scopes and Modules" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "## Namespace" 15 | ] 16 | }, 17 | { 18 | "cell_type": "code", 19 | "execution_count": 1, 20 | "metadata": { 21 | "collapsed": false 22 | }, 23 | "outputs": [ 24 | { 25 | "data": { 26 | "text/plain": [ 27 | "" 28 | ] 29 | }, 30 | "execution_count": 1, 31 | "metadata": {}, 32 | "output_type": "execute_result" 33 | } 34 | ], 35 | "source": [ 36 | "import math\n", 37 | "import scipy\n", 38 | "math.sin" 39 | ] 40 | }, 41 | { 42 | "cell_type": "code", 43 | "execution_count": 2, 44 | "metadata": { 45 | "collapsed": false 46 | }, 47 | "outputs": [ 48 | { 49 | "data": { 50 | "text/plain": [ 51 | "" 52 | ] 53 | }, 54 | "execution_count": 2, 55 | "metadata": {}, 56 | "output_type": "execute_result" 57 | } 58 | ], 59 | "source": [ 60 | "scipy.sin" 61 | ] 62 | }, 63 | { 64 | "cell_type": "code", 65 | "execution_count": 3, 66 | "metadata": { 67 | "collapsed": false 68 | }, 69 | "outputs": [ 70 | { 71 | "data": { 72 | "text/plain": [ 73 | "" 74 | ] 75 | }, 76 | "execution_count": 3, 77 | "metadata": {}, 78 | "output_type": "execute_result" 79 | } 80 | ], 81 | "source": [ 82 | "math.sin" 83 | ] 84 | }, 85 | { 86 | "cell_type": "code", 87 | "execution_count": 4, 88 | "metadata": { 89 | "collapsed": false 90 | }, 91 | "outputs": [ 92 | { 93 | "data": { 94 | "text/plain": [ 95 | "'This module is always available. It provides access to the\\nmathematical functions defined by the C standard.'" 96 | ] 97 | }, 98 | "execution_count": 4, 99 | "metadata": {}, 100 | "output_type": "execute_result" 101 | } 102 | ], 103 | "source": [ 104 | "math.__name__ # returns math\n", 105 | "math.__doc__ # returns 'This module is always ...'" 106 | ] 107 | }, 108 | { 109 | "cell_type": "code", 110 | "execution_count": 5, 111 | "metadata": { 112 | "collapsed": false 113 | }, 114 | "outputs": [ 115 | { 116 | "data": { 117 | "text/plain": [ 118 | "True" 119 | ] 120 | }, 121 | "execution_count": 5, 122 | "metadata": {}, 123 | "output_type": "execute_result" 124 | } 125 | ], 126 | "source": [ 127 | "'float' in dir(__builtins__) # returns True" 128 | ] 129 | }, 130 | { 131 | "cell_type": "code", 132 | "execution_count": 6, 133 | "metadata": { 134 | "collapsed": false 135 | }, 136 | "outputs": [ 137 | { 138 | "data": { 139 | "text/plain": [ 140 | "True" 141 | ] 142 | }, 143 | "execution_count": 6, 144 | "metadata": {}, 145 | "output_type": "execute_result" 146 | } 147 | ], 148 | "source": [ 149 | "float is __builtins__.float # returns True" 150 | ] 151 | }, 152 | { 153 | "cell_type": "markdown", 154 | "metadata": {}, 155 | "source": [ 156 | "## Scope of a Variable" 157 | ] 158 | }, 159 | { 160 | "cell_type": "code", 161 | "execution_count": 1, 162 | "metadata": { 163 | "collapsed": true 164 | }, 165 | "outputs": [], 166 | "source": [ 167 | "e = 3\n", 168 | "def my_function(in1):\n", 169 | " a = 2 * e\n", 170 | " b = 3\n", 171 | " in1 = 5\n", 172 | " def other_function():\n", 173 | " c = a\n", 174 | " d = e\n", 175 | " return dir()\n", 176 | " print(\"\"\"\n", 177 | " my_function's namespace: {} \n", 178 | " other_function's namespace: {}\n", 179 | " \"\"\".format(dir(),other_function()))\n", 180 | " return a" 181 | ] 182 | }, 183 | { 184 | "cell_type": "code", 185 | "execution_count": 2, 186 | "metadata": { 187 | "collapsed": false 188 | }, 189 | "outputs": [ 190 | { 191 | "name": "stdout", 192 | "output_type": "stream", 193 | "text": [ 194 | "\n", 195 | " my_function's namespace: ['a', 'b', 'in1', 'other_function'] \n", 196 | " other_function's namespace: ['a', 'c', 'd']\n", 197 | " \n" 198 | ] 199 | }, 200 | { 201 | "data": { 202 | "text/plain": [ 203 | "6" 204 | ] 205 | }, 206 | "execution_count": 2, 207 | "metadata": {}, 208 | "output_type": "execute_result" 209 | } 210 | ], 211 | "source": [ 212 | "my_function(3)" 213 | ] 214 | }, 215 | { 216 | "cell_type": "code", 217 | "execution_count": 3, 218 | "metadata": { 219 | "collapsed": true 220 | }, 221 | "outputs": [], 222 | "source": [ 223 | "e = 3\n", 224 | "def my_function():\n", 225 | " e = 4\n", 226 | " a = 2\n", 227 | " print(\"my_function's namespace: {}\".format(dir()))" 228 | ] 229 | }, 230 | { 231 | "cell_type": "code", 232 | "execution_count": 4, 233 | "metadata": { 234 | "collapsed": false 235 | }, 236 | "outputs": [ 237 | { 238 | "name": "stdout", 239 | "output_type": "stream", 240 | "text": [ 241 | "my_function's namespace: ['a', 'e']\n" 242 | ] 243 | }, 244 | { 245 | "data": { 246 | "text/plain": [ 247 | "3" 248 | ] 249 | }, 250 | "execution_count": 4, 251 | "metadata": {}, 252 | "output_type": "execute_result" 253 | } 254 | ], 255 | "source": [ 256 | "e = 3\n", 257 | "my_function() \n", 258 | "e # has the value 3" 259 | ] 260 | }, 261 | { 262 | "cell_type": "code", 263 | "execution_count": 22, 264 | "metadata": { 265 | "collapsed": true 266 | }, 267 | "outputs": [], 268 | "source": [ 269 | "def fun():\n", 270 | " def fun1():\n", 271 | " global a\n", 272 | " a = 3\n", 273 | " def fun2():\n", 274 | " global b\n", 275 | " b = 2\n", 276 | " print(a)\n", 277 | " fun1() \n", 278 | " fun2() # prints a\n", 279 | " print(b)" 280 | ] 281 | }, 282 | { 283 | "cell_type": "code", 284 | "execution_count": 23, 285 | "metadata": { 286 | "collapsed": false 287 | }, 288 | "outputs": [ 289 | { 290 | "name": "stdout", 291 | "output_type": "stream", 292 | "text": [ 293 | "3\n", 294 | "2\n" 295 | ] 296 | } 297 | ], 298 | "source": [ 299 | "fun()" 300 | ] 301 | }, 302 | { 303 | "cell_type": "markdown", 304 | "metadata": {}, 305 | "source": [ 306 | "## Modules" 307 | ] 308 | }, 309 | { 310 | "cell_type": "code", 311 | "execution_count": 24, 312 | "metadata": { 313 | "collapsed": true 314 | }, 315 | "outputs": [], 316 | "source": [ 317 | "from numpy import *" 318 | ] 319 | }, 320 | { 321 | "cell_type": "code", 322 | "execution_count": 25, 323 | "metadata": { 324 | "collapsed": true 325 | }, 326 | "outputs": [], 327 | "source": [ 328 | "import numpy" 329 | ] 330 | }, 331 | { 332 | "cell_type": "code", 333 | "execution_count": 26, 334 | "metadata": { 335 | "collapsed": false 336 | }, 337 | "outputs": [ 338 | { 339 | "data": { 340 | "text/plain": [ 341 | "array([1, 2])" 342 | ] 343 | }, 344 | "execution_count": 26, 345 | "metadata": {}, 346 | "output_type": "execute_result" 347 | } 348 | ], 349 | "source": [ 350 | "numpy.array([1,2]) " 351 | ] 352 | }, 353 | { 354 | "cell_type": "code", 355 | "execution_count": 27, 356 | "metadata": { 357 | "collapsed": false 358 | }, 359 | "outputs": [ 360 | { 361 | "name": "stdout", 362 | "output_type": "stream", 363 | "text": [ 364 | "[ 0.+0.j 1.+0.j]\n" 365 | ] 366 | } 367 | ], 368 | "source": [ 369 | "import scipy.linalg as sl\n", 370 | "A=array([[1,2],[3,4]])\n", 371 | "(eig,eigvec)=sl.eig(A) # eig and sl.eig are different objects\n", 372 | "B=array([[1,0],[3,0]])\n", 373 | "(c,d)=sl.eig(B)\n", 374 | "print(c)" 375 | ] 376 | } 377 | ], 378 | "metadata": { 379 | "anaconda-cloud": {}, 380 | "kernelspec": { 381 | "display_name": "Python [conda root]", 382 | "language": "python", 383 | "name": "conda-root-py" 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.5.2" 396 | } 397 | }, 398 | "nbformat": 4, 399 | "nbformat_minor": 1 400 | } 401 | -------------------------------------------------------------------------------- /12-InputOutput/12-InputOutput.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 12- InputOutput" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 27, 13 | "metadata": { 14 | "collapsed": true 15 | }, 16 | "outputs": [], 17 | "source": [ 18 | "from scipy import *" 19 | ] 20 | }, 21 | { 22 | "cell_type": "markdown", 23 | "metadata": {}, 24 | "source": [ 25 | "## File handling\n", 26 | "### Interacting with files" 27 | ] 28 | }, 29 | { 30 | "cell_type": "code", 31 | "execution_count": 8, 32 | "metadata": { 33 | "collapsed": true 34 | }, 35 | "outputs": [], 36 | "source": [ 37 | "myfile = open('measurement.dat','r')" 38 | ] 39 | }, 40 | { 41 | "cell_type": "code", 42 | "execution_count": 9, 43 | "metadata": { 44 | "collapsed": false 45 | }, 46 | "outputs": [ 47 | { 48 | "name": "stdout", 49 | "output_type": "stream", 50 | "text": [ 51 | "this is a file\n", 52 | "\n" 53 | ] 54 | } 55 | ], 56 | "source": [ 57 | "print(myfile.read())" 58 | ] 59 | }, 60 | { 61 | "cell_type": "code", 62 | "execution_count": 10, 63 | "metadata": { 64 | "collapsed": true 65 | }, 66 | "outputs": [], 67 | "source": [ 68 | "myfile.close() # closes the file object" 69 | ] 70 | }, 71 | { 72 | "cell_type": "code", 73 | "execution_count": 12, 74 | "metadata": { 75 | "collapsed": false 76 | }, 77 | "outputs": [ 78 | { 79 | "name": "stdout", 80 | "output_type": "stream", 81 | "text": [ 82 | "this is a file\n", 83 | "\n" 84 | ] 85 | } 86 | ], 87 | "source": [ 88 | "with open('measurement.dat','r') as myfile: \n", 89 | " print(myfile.read())" 90 | ] 91 | }, 92 | { 93 | "cell_type": "code", 94 | "execution_count": 18, 95 | "metadata": { 96 | "collapsed": false 97 | }, 98 | "outputs": [ 99 | { 100 | "ename": "ZeroDivisionError", 101 | "evalue": "division by zero", 102 | "output_type": "error", 103 | "traceback": [ 104 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 105 | "\u001b[1;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", 106 | "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 2\u001b[0m \u001b[0mmyfile\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mopen\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mname\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;34m'w'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 3\u001b[0m \u001b[0mmyfile\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mwrite\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'some data'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 4\u001b[1;33m \u001b[0ma\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;36m1\u001b[0m\u001b[1;33m/\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 5\u001b[0m \u001b[0mmyfile\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mwrite\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'other data'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 6\u001b[0m \u001b[0mmyfile\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mclose\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", 107 | "\u001b[1;31mZeroDivisionError\u001b[0m: division by zero" 108 | ] 109 | } 110 | ], 111 | "source": [ 112 | "name='someotherfile.dat'\n", 113 | "myfile = open(name,'w')\n", 114 | "myfile.write('some data')\n", 115 | "a = 1/0\n", 116 | "myfile.write('other data')\n", 117 | "myfile.close()" 118 | ] 119 | }, 120 | { 121 | "cell_type": "code", 122 | "execution_count": 19, 123 | "metadata": { 124 | "collapsed": false 125 | }, 126 | "outputs": [ 127 | { 128 | "data": { 129 | "text/plain": [ 130 | "False" 131 | ] 132 | }, 133 | "execution_count": 19, 134 | "metadata": {}, 135 | "output_type": "execute_result" 136 | } 137 | ], 138 | "source": [ 139 | "myfile.closed" 140 | ] 141 | }, 142 | { 143 | "cell_type": "code", 144 | "execution_count": 20, 145 | "metadata": { 146 | "collapsed": false 147 | }, 148 | "outputs": [ 149 | { 150 | "ename": "ZeroDivisionError", 151 | "evalue": "division by zero", 152 | "output_type": "error", 153 | "traceback": [ 154 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 155 | "\u001b[1;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", 156 | "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;32mwith\u001b[0m \u001b[0mopen\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mname\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;34m'w'\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;32mas\u001b[0m \u001b[0mmyfile\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 2\u001b[0m \u001b[0mmyfile\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mwrite\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'some data'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 3\u001b[1;33m \u001b[0ma\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;36m1\u001b[0m\u001b[1;33m/\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 4\u001b[0m \u001b[0mmyfile\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mwrite\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'other data'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", 157 | "\u001b[1;31mZeroDivisionError\u001b[0m: division by zero" 158 | ] 159 | } 160 | ], 161 | "source": [ 162 | "with open(name,'w') as myfile:\n", 163 | " myfile.write('some data')\n", 164 | " a = 1/0\n", 165 | " myfile.write('other data')" 166 | ] 167 | }, 168 | { 169 | "cell_type": "code", 170 | "execution_count": 21, 171 | "metadata": { 172 | "collapsed": false 173 | }, 174 | "outputs": [ 175 | { 176 | "data": { 177 | "text/plain": [ 178 | "True" 179 | ] 180 | }, 181 | "execution_count": 21, 182 | "metadata": {}, 183 | "output_type": "execute_result" 184 | } 185 | ], 186 | "source": [ 187 | "myfile.closed" 188 | ] 189 | }, 190 | { 191 | "cell_type": "markdown", 192 | "metadata": {}, 193 | "source": [ 194 | "### Files are iterable" 195 | ] 196 | }, 197 | { 198 | "cell_type": "code", 199 | "execution_count": 23, 200 | "metadata": { 201 | "collapsed": false 202 | }, 203 | "outputs": [ 204 | { 205 | "name": "stdout", 206 | "output_type": "stream", 207 | "text": [ 208 | "time 11:00 sec temperature -12\n", 209 | " C\n", 210 | "time 12:00 sec temperature -08\n", 211 | " C\n", 212 | "time 13:00 sec temperature -05\n", 213 | " C\n", 214 | "time 17:00 sec temperature -07\n", 215 | " C\n", 216 | "time 22:00 sec temperature -10\n", 217 | " C\n" 218 | ] 219 | } 220 | ], 221 | "source": [ 222 | "with open('tem.dat','r') as myfile:\n", 223 | " for line in myfile:\n", 224 | " data = line.split(';')\n", 225 | " print('time {} sec temperature {} C'.format(data[0],data[1]))" 226 | ] 227 | }, 228 | { 229 | "cell_type": "code", 230 | "execution_count": 25, 231 | "metadata": { 232 | "collapsed": false 233 | }, 234 | "outputs": [ 235 | { 236 | "name": "stdout", 237 | "output_type": "stream", 238 | "text": [ 239 | "['11:00;-12\\n', '12:00;-08\\n', '13:00;-05\\n', '17:00;-07\\n', '22:00;-10\\n']\n" 240 | ] 241 | } 242 | ], 243 | "source": [ 244 | "with open('tem.dat','r') as myfile:\n", 245 | " data=list(myfile)\n", 246 | "print(data)" 247 | ] 248 | }, 249 | { 250 | "cell_type": "markdown", 251 | "metadata": {}, 252 | "source": [ 253 | "## NumPy methods" 254 | ] 255 | }, 256 | { 257 | "cell_type": "code", 258 | "execution_count": 28, 259 | "metadata": { 260 | "collapsed": true 261 | }, 262 | "outputs": [], 263 | "source": [ 264 | "x = range(100) # 100 integers\n", 265 | "savetxt('test.txt',x,delimiter=',') # use comma instead of space\n", 266 | "savetxt('test.txt',x,fmt='%d') # integer format instead of float with e" 267 | ] 268 | }, 269 | { 270 | "cell_type": "code", 271 | "execution_count": 31, 272 | "metadata": { 273 | "collapsed": true 274 | }, 275 | "outputs": [], 276 | "source": [ 277 | "filename = 'test.txt'\n", 278 | "data = loadtxt(filename)" 279 | ] 280 | }, 281 | { 282 | "cell_type": "code", 283 | "execution_count": 30, 284 | "metadata": { 285 | "collapsed": false 286 | }, 287 | "outputs": [ 288 | { 289 | "data": { 290 | "text/plain": [ 291 | "array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.,\n", 292 | " 11., 12., 13., 14., 15., 16., 17., 18., 19., 20., 21.,\n", 293 | " 22., 23., 24., 25., 26., 27., 28., 29., 30., 31., 32.,\n", 294 | " 33., 34., 35., 36., 37., 38., 39., 40., 41., 42., 43.,\n", 295 | " 44., 45., 46., 47., 48., 49., 50., 51., 52., 53., 54.,\n", 296 | " 55., 56., 57., 58., 59., 60., 61., 62., 63., 64., 65.,\n", 297 | " 66., 67., 68., 69., 70., 71., 72., 73., 74., 75., 76.,\n", 298 | " 77., 78., 79., 80., 81., 82., 83., 84., 85., 86., 87.,\n", 299 | " 88., 89., 90., 91., 92., 93., 94., 95., 96., 97., 98.,\n", 300 | " 99.])" 301 | ] 302 | }, 303 | "execution_count": 30, 304 | "metadata": {}, 305 | "output_type": "execute_result" 306 | } 307 | ], 308 | "source": [ 309 | "data" 310 | ] 311 | }, 312 | { 313 | "cell_type": "markdown", 314 | "metadata": {}, 315 | "source": [ 316 | "## Pickling" 317 | ] 318 | }, 319 | { 320 | "cell_type": "code", 321 | "execution_count": 34, 322 | "metadata": { 323 | "collapsed": false 324 | }, 325 | "outputs": [ 326 | { 327 | "name": "stdout", 328 | "output_type": "stream", 329 | "text": [ 330 | "0.447901625284 hello world\n" 331 | ] 332 | } 333 | ], 334 | "source": [ 335 | "import pickle\n", 336 | "with open('file.dat','wb') as myfile:\n", 337 | " a = random.rand(20,20)\n", 338 | " b = 'hello world'\n", 339 | " pickle.dump(a,myfile) # first call: first object\n", 340 | " pickle.dump(b,myfile) # second call: second object\n", 341 | "\n", 342 | "\n", 343 | "\n", 344 | "with open('file.dat','rb') as myfile:\n", 345 | " numbers = pickle.load(myfile) # restores the array\n", 346 | " text = pickle.load(myfile) # restores the string\n", 347 | "\n", 348 | " print(numbers[-1,1], text)" 349 | ] 350 | }, 351 | { 352 | "cell_type": "code", 353 | "execution_count": 35, 354 | "metadata": { 355 | "collapsed": false 356 | }, 357 | "outputs": [ 358 | { 359 | "data": { 360 | "text/plain": [ 361 | "b'\\x80\\x03}q\\x00(X\\x01\\x00\\x00\\x00aq\\x01K\\x01X\\x01\\x00\\x00\\x00bq\\x02K\\x02u.'" 362 | ] 363 | }, 364 | "execution_count": 35, 365 | "metadata": {}, 366 | "output_type": "execute_result" 367 | } 368 | ], 369 | "source": [ 370 | "a = [1,2,3,4]\n", 371 | "pickle.dumps(a) # returns '(lp0\\nI1\\naI2\\naI3\\naI4\\na.'\n", 372 | "b = {'a':1,'b':2}\n", 373 | "pickle.dumps(b) # returns \"(dp0\\nS'a'\\np1\\nI1\\nsS'b'\\np2\\nI2\\ns.\"" 374 | ] 375 | }, 376 | { 377 | "cell_type": "markdown", 378 | "metadata": {}, 379 | "source": [ 380 | "## Shelves" 381 | ] 382 | }, 383 | { 384 | "cell_type": "code", 385 | "execution_count": 41, 386 | "metadata": { 387 | "collapsed": false 388 | }, 389 | "outputs": [], 390 | "source": [ 391 | "from contextlib import closing\n", 392 | "import shelve as sv\n", 393 | "# opens a data file (creates it before if necessary)\n", 394 | "with closing(sv.open('datafile')) as data:\n", 395 | " A = array([[1,2,3],[4,5,6]]) \n", 396 | " data['my_matrix'] = A " 397 | ] 398 | }, 399 | { 400 | "cell_type": "code", 401 | "execution_count": 43, 402 | "metadata": { 403 | "collapsed": false 404 | }, 405 | "outputs": [], 406 | "source": [ 407 | "from contextlib import closing\n", 408 | "import shelve as sv\n", 409 | "with closing(sv.open('datafile')) as data: # opens a data file\n", 410 | " A = data['my_matrix']" 411 | ] 412 | }, 413 | { 414 | "cell_type": "code", 415 | "execution_count": 44, 416 | "metadata": { 417 | "collapsed": false, 418 | "scrolled": true 419 | }, 420 | "outputs": [ 421 | { 422 | "data": { 423 | "text/plain": [ 424 | "array([[1, 2, 3],\n", 425 | " [4, 5, 6]])" 426 | ] 427 | }, 428 | "execution_count": 44, 429 | "metadata": {}, 430 | "output_type": "execute_result" 431 | } 432 | ], 433 | "source": [ 434 | "A" 435 | ] 436 | }, 437 | { 438 | "cell_type": "markdown", 439 | "metadata": {}, 440 | "source": [ 441 | "## Reading and writing Matlab data files" 442 | ] 443 | }, 444 | { 445 | "cell_type": "code", 446 | "execution_count": 50, 447 | "metadata": { 448 | "collapsed": false 449 | }, 450 | "outputs": [ 451 | { 452 | "name": "stdout", 453 | "output_type": "stream", 454 | "text": [ 455 | "{'__version__': '1.0', 'y': array([[2, 4, 6]]), '__header__': b'MATLAB 5.0 MAT-file Platform: posix, Created on: Tue Dec 6 10:50:44 2016', 'x': array([[1, 2, 3]]), '__globals__': []}\n" 456 | ] 457 | } 458 | ], 459 | "source": [ 460 | "import scipy.io\n", 461 | "data = scipy.io.loadmat('datafile.mat')\n", 462 | "print(data)" 463 | ] 464 | }, 465 | { 466 | "cell_type": "code", 467 | "execution_count": 48, 468 | "metadata": { 469 | "collapsed": false 470 | }, 471 | "outputs": [], 472 | "source": [ 473 | "data ={}\n", 474 | "data['x'] = x = array([1,2,3])\n", 475 | "data['y'] = 2*x\n", 476 | "scipy.io.savemat('datafile.mat',data)" 477 | ] 478 | }, 479 | { 480 | "cell_type": "markdown", 481 | "metadata": {}, 482 | "source": [ 483 | "## Reading and writing images" 484 | ] 485 | }, 486 | { 487 | "cell_type": "code", 488 | "execution_count": 55, 489 | "metadata": { 490 | "collapsed": false 491 | }, 492 | "outputs": [ 493 | { 494 | "name": "stdout", 495 | "output_type": "stream", 496 | "text": [ 497 | "(183, 275, 3)\n", 498 | "uint8\n", 499 | "(64, 64, 3)\n" 500 | ] 501 | } 502 | ], 503 | "source": [ 504 | "import scipy.misc as sm\n", 505 | "\n", 506 | "# read image to array\n", 507 | "im = sm.imread(\"test.jpg\") \n", 508 | "print(im.shape) # (128, 128, 3)\n", 509 | "print(im.dtype) # uint8\n", 510 | "\n", 511 | "# resize image\n", 512 | "im_small = sm.imresize(im, (64,64))\n", 513 | "print(im_small.shape) # (64, 64, 3)\n", 514 | "\n", 515 | "# write result to new image file\n", 516 | "sm.imsave(\"test_small.jpg\", im_small)" 517 | ] 518 | }, 519 | { 520 | "cell_type": "code", 521 | "execution_count": 54, 522 | "metadata": { 523 | "collapsed": true 524 | }, 525 | "outputs": [], 526 | "source": [ 527 | "import scipy.misc" 528 | ] 529 | }, 530 | { 531 | "cell_type": "code", 532 | "execution_count": null, 533 | "metadata": { 534 | "collapsed": true 535 | }, 536 | "outputs": [], 537 | "source": [] 538 | } 539 | ], 540 | "metadata": { 541 | "anaconda-cloud": {}, 542 | "kernelspec": { 543 | "display_name": "Python [conda root]", 544 | "language": "python", 545 | "name": "conda-root-py" 546 | }, 547 | "language_info": { 548 | "codemirror_mode": { 549 | "name": "ipython", 550 | "version": 3 551 | }, 552 | "file_extension": ".py", 553 | "mimetype": "text/x-python", 554 | "name": "python", 555 | "nbconvert_exporter": "python", 556 | "pygments_lexer": "ipython3", 557 | "version": "3.5.2" 558 | } 559 | }, 560 | "nbformat": 4, 561 | "nbformat_minor": 0 562 | } 563 | -------------------------------------------------------------------------------- /12-InputOutput/datafile.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Scientific-Computing-with-Python-3/1333ac3fe4f90cb9f157682bf2d3a80824528032/12-InputOutput/datafile.dat -------------------------------------------------------------------------------- /12-InputOutput/tem.dat: -------------------------------------------------------------------------------- 1 | 11:00;-12 2 | 12:00;-08 3 | 13:00;-05 4 | 17:00;-07 5 | 22:00;-10 6 | -------------------------------------------------------------------------------- /12-InputOutput/test.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Scientific-Computing-with-Python-3/1333ac3fe4f90cb9f157682bf2d3a80824528032/12-InputOutput/test.jpg -------------------------------------------------------------------------------- /12-InputOutput/test_small.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Scientific-Computing-with-Python-3/1333ac3fe4f90cb9f157682bf2d3a80824528032/12-InputOutput/test_small.jpg -------------------------------------------------------------------------------- /13-Testing/13-Testing.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 13-Testing" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 3, 13 | "metadata": { 14 | "collapsed": true 15 | }, 16 | "outputs": [], 17 | "source": [ 18 | "from scipy import *" 19 | ] 20 | }, 21 | { 22 | "cell_type": "code", 23 | "execution_count": 4, 24 | "metadata": { 25 | "collapsed": true 26 | }, 27 | "outputs": [], 28 | "source": [ 29 | "def bisect(f, a, b, tol=1.e-8):\n", 30 | " \"\"\"\n", 31 | " Implementation of the bisection algorithm \n", 32 | " f real valued function\n", 33 | " a,b interval boundaries (float) with the property \n", 34 | " f(a) * f(b) <= 0\n", 35 | " tol tolerance (float)\n", 36 | " \"\"\"\n", 37 | " if f(a) * f(b)> 0:\n", 38 | " raise ValueError(\"Incorrect initial interval [a, b]\") \n", 39 | " for i in range(100):\n", 40 | " c = (a + b) / 2.\n", 41 | " if f(a) * f(c) <= 0:\n", 42 | " b = c\n", 43 | " else:\n", 44 | " a = c\n", 45 | " if abs(a - b) < tol:\n", 46 | " return (a + b) / 2\n", 47 | " raise Exception(\n", 48 | " 'No root found within the given tolerance {}'.format(tol))" 49 | ] 50 | }, 51 | { 52 | "cell_type": "markdown", 53 | "metadata": {}, 54 | "source": [ 55 | "Test to see that is finds the root of $f(x)=x$" 56 | ] 57 | }, 58 | { 59 | "cell_type": "code", 60 | "execution_count": 5, 61 | "metadata": { 62 | "collapsed": false 63 | }, 64 | "outputs": [], 65 | "source": [ 66 | "def test_identity():\n", 67 | " result = bisect(lambda x: x, -1., 1.) \n", 68 | " expected = 0.\n", 69 | " assert allclose(result, expected),'expected zero not found'\n", 70 | "\n", 71 | "test_identity()" 72 | ] 73 | }, 74 | { 75 | "cell_type": "markdown", 76 | "metadata": {}, 77 | "source": [ 78 | "Test to see if the sign condition $f(a)f(b)< 0$ is checked" 79 | ] 80 | }, 81 | { 82 | "cell_type": "code", 83 | "execution_count": 6, 84 | "metadata": { 85 | "collapsed": true 86 | }, 87 | "outputs": [], 88 | "source": [ 89 | "def test_badinput():\n", 90 | " try:\n", 91 | " bisect(lambda x: x,0.5,1)\n", 92 | " except ValueError:\n", 93 | " pass\n", 94 | " else:\n", 95 | " raise AssertionError()\n", 96 | "\n", 97 | "test_badinput()" 98 | ] 99 | }, 100 | { 101 | "cell_type": "code", 102 | "execution_count": 7, 103 | "metadata": { 104 | "collapsed": false 105 | }, 106 | "outputs": [], 107 | "source": [ 108 | "def test_equal_boundaries():\n", 109 | " result = bisect(lambda x: x, 0., 0.)\n", 110 | " expected = 0.\n", 111 | " assert allclose(result, expected), \\\n", 112 | " 'test equal interval bounds failed'" 113 | ] 114 | }, 115 | { 116 | "cell_type": "code", 117 | "execution_count": 8, 118 | "metadata": { 119 | "collapsed": false 120 | }, 121 | "outputs": [], 122 | "source": [ 123 | "test_equal_boundaries()" 124 | ] 125 | }, 126 | { 127 | "cell_type": "code", 128 | "execution_count": 9, 129 | "metadata": { 130 | "collapsed": true 131 | }, 132 | "outputs": [], 133 | "source": [ 134 | "def test_reverse_boundaries():\n", 135 | " result = bisect(lambda x: x, 1., -1.)\n", 136 | " expected = 0.\n", 137 | " assert allclose(result, expected),\\\n", 138 | " 'test reverse interval bounds failed'" 139 | ] 140 | }, 141 | { 142 | "cell_type": "code", 143 | "execution_count": 10, 144 | "metadata": { 145 | "collapsed": true 146 | }, 147 | "outputs": [], 148 | "source": [ 149 | "test_reverse_boundaries()" 150 | ] 151 | }, 152 | { 153 | "cell_type": "code", 154 | "execution_count": 15, 155 | "metadata": { 156 | "collapsed": false 157 | }, 158 | "outputs": [ 159 | { 160 | "name": "stderr", 161 | "output_type": "stream", 162 | "text": [ 163 | ".\n", 164 | "----------------------------------------------------------------------\n", 165 | "Ran 1 test in 0.001s\n", 166 | "\n", 167 | "OK\n" 168 | ] 169 | } 170 | ], 171 | "source": [ 172 | "run TestIdentity" 173 | ] 174 | }, 175 | { 176 | "cell_type": "code", 177 | "execution_count": 16, 178 | "metadata": { 179 | "collapsed": false 180 | }, 181 | "outputs": [ 182 | { 183 | "name": "stderr", 184 | "output_type": "stream", 185 | "text": [ 186 | "...\n", 187 | "----------------------------------------------------------------------\n", 188 | "Ran 3 tests in 0.003s\n", 189 | "\n", 190 | "OK\n" 191 | ] 192 | } 193 | ], 194 | "source": [ 195 | "run Testing_all" 196 | ] 197 | }, 198 | { 199 | "cell_type": "code", 200 | "execution_count": 17, 201 | "metadata": { 202 | "collapsed": false 203 | }, 204 | "outputs": [ 205 | { 206 | "name": "stderr", 207 | "output_type": "stream", 208 | "text": [ 209 | "..\n", 210 | "----------------------------------------------------------------------\n", 211 | "Ran 2 tests in 0.003s\n", 212 | "\n", 213 | "OK\n" 214 | ] 215 | } 216 | ], 217 | "source": [ 218 | "run TestString" 219 | ] 220 | }, 221 | { 222 | "cell_type": "code", 223 | "execution_count": 18, 224 | "metadata": { 225 | "collapsed": false 226 | }, 227 | "outputs": [ 228 | { 229 | "name": "stderr", 230 | "output_type": "stream", 231 | "text": [ 232 | "...\n", 233 | "----------------------------------------------------------------------\n", 234 | "Ran 3 tests in 0.003s\n", 235 | "\n", 236 | "OK\n" 237 | ] 238 | } 239 | ], 240 | "source": [ 241 | "run Tests_several" 242 | ] 243 | }, 244 | { 245 | "cell_type": "code", 246 | "execution_count": 19, 247 | "metadata": { 248 | "collapsed": true 249 | }, 250 | "outputs": [], 251 | "source": [ 252 | "import scipy.linalg as sl\n", 253 | "A=rand(10,10)\n", 254 | "[Q,R]=sl.qr(A)" 255 | ] 256 | }, 257 | { 258 | "cell_type": "code", 259 | "execution_count": 22, 260 | "metadata": { 261 | "collapsed": false 262 | }, 263 | "outputs": [], 264 | "source": [ 265 | "import numpy.testing as npt \n", 266 | "npt.assert_allclose(dot(Q.T,Q),identity(Q.shape[0]),atol=1.e-12)" 267 | ] 268 | }, 269 | { 270 | "cell_type": "code", 271 | "execution_count": 24, 272 | "metadata": { 273 | "collapsed": false 274 | }, 275 | "outputs": [], 276 | "source": [ 277 | "npt.assert_allclose(dot(Q,R),A)" 278 | ] 279 | }, 280 | { 281 | "cell_type": "code", 282 | "execution_count": 26, 283 | "metadata": { 284 | "collapsed": false 285 | }, 286 | "outputs": [ 287 | { 288 | "name": "stderr", 289 | "output_type": "stream", 290 | "text": [ 291 | "..\n", 292 | "----------------------------------------------------------------------\n", 293 | "Ran 2 tests in 0.004s\n", 294 | "\n", 295 | "OK\n" 296 | ] 297 | } 298 | ], 299 | "source": [ 300 | "run TestQR" 301 | ] 302 | }, 303 | { 304 | "cell_type": "code", 305 | "execution_count": 27, 306 | "metadata": { 307 | "collapsed": true 308 | }, 309 | "outputs": [], 310 | "source": [ 311 | "test_case = TestIdentity(methodName='test_functionality')" 312 | ] 313 | }, 314 | { 315 | "cell_type": "code", 316 | "execution_count": 28, 317 | "metadata": { 318 | "collapsed": true 319 | }, 320 | "outputs": [], 321 | "source": [ 322 | "test_case.debug()" 323 | ] 324 | }, 325 | { 326 | "cell_type": "code", 327 | "execution_count": 30, 328 | "metadata": { 329 | "collapsed": false 330 | }, 331 | "outputs": [], 332 | "source": [ 333 | "A=zeros((1000,1000))\n", 334 | "A[53,67]=10\n", 335 | "\n", 336 | "def find_elements_1(A):\n", 337 | " b = []\n", 338 | " n, m = A.shape\n", 339 | " for i in range(n):\n", 340 | " for j in range(m):\n", 341 | " if abs(A[i, j]) > 1.e-10:\n", 342 | " b.append(A[i, j])\n", 343 | " return b\n", 344 | "\n", 345 | "def find_elements_2(A):\n", 346 | " return [a for a in A.reshape((-1, )) if abs(a) > 1.e-10]\n", 347 | "\n", 348 | "def find_elements_3(A):\n", 349 | " return [a for a in A.flatten() if abs(a) > 1.e-10]\n", 350 | " \n", 351 | "def find_elements_4(A):\n", 352 | " return A[where(0.0 != A)]" 353 | ] 354 | }, 355 | { 356 | "cell_type": "code", 357 | "execution_count": 32, 358 | "metadata": { 359 | "collapsed": false 360 | }, 361 | "outputs": [ 362 | { 363 | "name": "stdout", 364 | "output_type": "stream", 365 | "text": [ 366 | "50 loops, best of 3: 334 ms per loop\n" 367 | ] 368 | } 369 | ], 370 | "source": [ 371 | "%timeit -n 50 -r 3 find_elements_1(A)" 372 | ] 373 | }, 374 | { 375 | "cell_type": "code", 376 | "execution_count": 33, 377 | "metadata": { 378 | "collapsed": false 379 | }, 380 | "outputs": [ 381 | { 382 | "name": "stdout", 383 | "output_type": "stream", 384 | "text": [ 385 | "50 loops, best of 3: 174 ms per loop\n" 386 | ] 387 | } 388 | ], 389 | "source": [ 390 | "%timeit -n 50 -r 3 find_elements_2(A)" 391 | ] 392 | }, 393 | { 394 | "cell_type": "code", 395 | "execution_count": 34, 396 | "metadata": { 397 | "collapsed": false 398 | }, 399 | "outputs": [ 400 | { 401 | "name": "stdout", 402 | "output_type": "stream", 403 | "text": [ 404 | "50 loops, best of 3: 175 ms per loop\n" 405 | ] 406 | } 407 | ], 408 | "source": [ 409 | "%timeit -n 50 -r 3 find_elements_3(A)" 410 | ] 411 | }, 412 | { 413 | "cell_type": "code", 414 | "execution_count": 35, 415 | "metadata": { 416 | "collapsed": false 417 | }, 418 | "outputs": [ 419 | { 420 | "name": "stdout", 421 | "output_type": "stream", 422 | "text": [ 423 | "50 loops, best of 3: 3.79 ms per loop\n" 424 | ] 425 | } 426 | ], 427 | "source": [ 428 | "%timeit -n 50 -r 3 find_elements_4(A)" 429 | ] 430 | }, 431 | { 432 | "cell_type": "code", 433 | "execution_count": 36, 434 | "metadata": { 435 | "collapsed": true 436 | }, 437 | "outputs": [], 438 | "source": [ 439 | "import timeit\n", 440 | "setup_statements=\"\"\"\n", 441 | "from scipy import zeros\n", 442 | "from numpy import where\n", 443 | "A=zeros((1000,1000))\n", 444 | "A[57,63]=10.\n", 445 | "\n", 446 | "def find_elements_1(A):\n", 447 | " b = []\n", 448 | " n, m = A.shape\n", 449 | " for i in range(n):\n", 450 | " for j in range(m):\n", 451 | " if abs(A[i, j]) > 1.e-10:\n", 452 | " b.append(A[i, j])\n", 453 | " return b\n", 454 | "\n", 455 | "def find_elements_2(A):\n", 456 | " return [a for a in A.reshape((-1,)) if abs(a) > 1.e-10]\n", 457 | "\n", 458 | "def find_elements_3(A):\n", 459 | " return [a for a in A.flatten() if abs(a) > 1.e-10]\n", 460 | "\n", 461 | "def find_elements_4(A):\n", 462 | " return A[where( 0.0 != A)]\n", 463 | "\"\"\"\n", 464 | "experiment_1 = timeit.Timer(stmt = 'find_elements_1(A)',\n", 465 | " setup = setup_statements)\n", 466 | "experiment_2 = timeit.Timer(stmt = 'find_elements_2(A)',\n", 467 | " setup = setup_statements)\n", 468 | "experiment_3 = timeit.Timer(stmt = 'find_elements_3(A)',\n", 469 | " setup = setup_statements)\n", 470 | "experiment_4 = timeit.Timer(stmt = 'find_elements_4(A)',\n", 471 | " setup = setup_statements)" 472 | ] 473 | }, 474 | { 475 | "cell_type": "code", 476 | "execution_count": 38, 477 | "metadata": { 478 | "collapsed": false 479 | }, 480 | "outputs": [ 481 | { 482 | "name": "stdout", 483 | "output_type": "stream", 484 | "text": [ 485 | "335.6477557972539\n", 486 | "182.16045520093758\n", 487 | "185.94143340014853\n", 488 | "3.827910599648021\n" 489 | ] 490 | } 491 | ], 492 | "source": [ 493 | "t1 = experiment_1.repeat(3,5) \n", 494 | "t2 = experiment_2.repeat(3,5) \n", 495 | "t3 = experiment_3.repeat(3,5) \n", 496 | "t4 = experiment_4.repeat(3,5) \n", 497 | "# Results per loop in ms\n", 498 | "print(min(t1)*1000/5) # 615 ms\n", 499 | "print(min(t2)*1000/5) # 543 ms\n", 500 | "print(min(t3)*1000/5) # 546 ms\n", 501 | "print(min(t4)*1000/5) # 7.26 ms" 502 | ] 503 | }, 504 | { 505 | "cell_type": "code", 506 | "execution_count": 39, 507 | "metadata": { 508 | "collapsed": true 509 | }, 510 | "outputs": [], 511 | "source": [ 512 | "import time\n", 513 | "class Timer:\n", 514 | "\tdef __enter__(self):\n", 515 | "\t\tself.start = time.time()\n", 516 | "\tdef __exit__(self, ty, val, tb):\n", 517 | "\t\tend = time.time()\n", 518 | "\t\tself.elapsed=end-self.start\n", 519 | "\t\tprint('Time elapsed {} seconds'.format(self.elapsed))\n", 520 | "\t\treturn False " 521 | ] 522 | }, 523 | { 524 | "cell_type": "code", 525 | "execution_count": 42, 526 | "metadata": { 527 | "collapsed": false 528 | }, 529 | "outputs": [ 530 | { 531 | "name": "stdout", 532 | "output_type": "stream", 533 | "text": [ 534 | "Time elapsed 0.3459136486053467 seconds\n" 535 | ] 536 | } 537 | ], 538 | "source": [ 539 | "with Timer():\n", 540 | " find_elements_1(A)" 541 | ] 542 | }, 543 | { 544 | "cell_type": "code", 545 | "execution_count": null, 546 | "metadata": { 547 | "collapsed": true 548 | }, 549 | "outputs": [], 550 | "source": [] 551 | }, 552 | { 553 | "cell_type": "code", 554 | "execution_count": null, 555 | "metadata": { 556 | "collapsed": true 557 | }, 558 | "outputs": [], 559 | "source": [] 560 | } 561 | ], 562 | "metadata": { 563 | "anaconda-cloud": {}, 564 | "kernelspec": { 565 | "display_name": "Python [conda root]", 566 | "language": "python", 567 | "name": "conda-root-py" 568 | }, 569 | "language_info": { 570 | "codemirror_mode": { 571 | "name": "ipython", 572 | "version": 3 573 | }, 574 | "file_extension": ".py", 575 | "mimetype": "text/x-python", 576 | "name": "python", 577 | "nbconvert_exporter": "python", 578 | "pygments_lexer": "ipython3", 579 | "version": "3.5.2" 580 | } 581 | }, 582 | "nbformat": 4, 583 | "nbformat_minor": 1 584 | } 585 | -------------------------------------------------------------------------------- /13-Testing/TestIdentity.py: -------------------------------------------------------------------------------- 1 | from bisection import bisect 2 | import unittest 3 | 4 | class TestIdentity(unittest.TestCase): 5 | def test(self): 6 | result = bisect(lambda x: x, -1.2, 1.,tol=1.e-8) 7 | expected = 0. 8 | self.assertAlmostEqual(result, expected) 9 | 10 | if __name__=='__main__': 11 | unittest.main() 12 | -------------------------------------------------------------------------------- /13-Testing/TestQR.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import numpy.testing as npt 3 | from scipy.linalg import qr 4 | from scipy import * 5 | 6 | class TestQR(unittest.TestCase): 7 | def setUp(self): 8 | self.A=rand(10,10) 9 | [self.Q,self.R]=qr(self.A) 10 | def test_orthogonal(self): 11 | npt.assert_allclose( 12 | dot(self.Q.T,self.Q),identity(self.Q.shape[0]), atol=1.e-12) 13 | def test_sanity(self): 14 | npt.assert_allclose(dot(self.Q,self.R),self.A) 15 | if __name__=='__main__': 16 | unittest.main() 17 | -------------------------------------------------------------------------------- /13-Testing/TestString.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import os # used for, for example, deleting files 3 | 4 | from find_in_file import find_string, NotFoundError 5 | 6 | class TestFindInFile(unittest.TestCase): 7 | def setUp(self): 8 | file = open('test_file.txt', 'w') 9 | file.write('aha') 10 | file.close() 11 | self.file = open('test_file.txt', 'r') 12 | def tearDown(self): 13 | self.file.close() 14 | os.remove(self.file.name) 15 | def test_exists(self): 16 | line_no=find_string(self.file, 'aha') 17 | self.assertEqual(line_no, 0) 18 | def test_not_exists(self): 19 | self.assertRaises(NotFoundError, find_string, 20 | self.file, 'bha') 21 | 22 | if __name__=='__main__': 23 | unittest.main() 24 | -------------------------------------------------------------------------------- /13-Testing/Testing_all.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from bisection import bisect 3 | 4 | class TestIdentity(unittest.TestCase): 5 | def identity_fcn(self,x): 6 | return x 7 | def test_functionality(self): 8 | result = bisect(self.identity_fcn, -1.2, 1.,tol=1.e-8) 9 | expected = 0. 10 | self.assertAlmostEqual(result, expected) 11 | def test_reverse_boundaries(self): 12 | result = bisect(self.identity_fcn, 1., -1.) 13 | expected = 0. 14 | self.assertAlmostEqual(result, expected) 15 | def test_exceeded_tolerance(self): 16 | tol=1.e-80 17 | self.assertRaises(Exception, bisect, self.identity_fcn, 18 | -1.2, 1.,tol) 19 | if __name__=='__main__': 20 | unittest.main() 21 | -------------------------------------------------------------------------------- /13-Testing/Tests_several.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from bisection import bisect 3 | 4 | class Tests(unittest.TestCase): 5 | def checkifzero(self,fcn_with_zero,interval): 6 | result = bisect(fcn_with_zero,*interval,tol=1.e-8) 7 | function_value=fcn_with_zero(result) 8 | expected=0. 9 | self.assertAlmostEqual(function_value, expected) 10 | test_data=[ 11 | {'name':'identity', 'function':lambda x: x, 12 | 'interval' : [-1.2, 1.]}, 13 | {'name':'parabola', 'function':lambda x: x**2-1, 14 | 'interval' :[0, 10.]}, 15 | {'name':'cubic', 'function':lambda x: x**3-2*x**2, 16 | 'interval':[0.1, 5.]}, 17 | ] 18 | def make_test_function(dic): 19 | return lambda self :\ 20 | self.checkifzero(dic['function'],dic['interval']) 21 | for data in test_data: 22 | setattr(Tests, "test_{name}".format(name=data['name']), 23 | make_test_function(data)) 24 | 25 | if __name__=='__main__': 26 | unittest.main() 27 | -------------------------------------------------------------------------------- /13-Testing/bisection.py: -------------------------------------------------------------------------------- 1 | def bisect(f, a, b, tol=1.e-8): 2 | """ 3 | Implementation of the bisection algorithm 4 | f real valued function 5 | a,b interval boundaries (float) with the property 6 | f(a) * f(b) <= 0 7 | tol tolerance (float) 8 | """ 9 | if f(a) * f(b)> 0: 10 | raise ValueError("Incorrect initial interval [a, b]") 11 | for i in range(100): 12 | c = (a + b) / 2. 13 | if f(a) * f(c) <= 0: 14 | b = c 15 | else: 16 | a = c 17 | if abs(a - b) < tol: 18 | return (a + b) / 2 19 | raise Exception( 20 | 'No root found within the given tolerance {}'.format(tol)) 21 | -------------------------------------------------------------------------------- /13-Testing/find_elements.py: -------------------------------------------------------------------------------- 1 | from scipy import * 2 | 3 | A=zeros((1000,1000)) 4 | A[53,67]=10 5 | 6 | def find_elements_1(A): 7 | b = [] 8 | n, m = A.shape 9 | for i in range(n): 10 | for j in range(m): 11 | if abs(A[i, j]) > 1.e-10: 12 | b.append(A[i, j]) 13 | return b 14 | 15 | def find_elements_2(A): 16 | return [a for a in A.reshape((-1, )) if abs(a) > 1.e-10] 17 | 18 | def find_elements_3(A): 19 | return [a for a in A.flatten() if abs(a) > 1.e-10] 20 | 21 | def find_elements_4(A): 22 | return A[where(0.0 != A)] 23 | -------------------------------------------------------------------------------- /13-Testing/find_in_file.py: -------------------------------------------------------------------------------- 1 | class NotFoundError(Exception): 2 | pass 3 | 4 | def find_string(file, string): 5 | for i,lines in enumerate(file.readlines()): 6 | if string in lines: 7 | return i 8 | raise NotFoundError( 9 | 'String {} not found in File {}'.format(string,file.name)) 10 | -------------------------------------------------------------------------------- /14-comprehensive-example/cluster1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Scientific-Computing-with-Python-3/1333ac3fe4f90cb9f157682bf2d3a80824528032/14-comprehensive-example/cluster1.pdf -------------------------------------------------------------------------------- /14-comprehensive-example/cluster1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Scientific-Computing-with-Python-3/1333ac3fe4f90cb9f157682bf2d3a80824528032/14-comprehensive-example/cluster1.png -------------------------------------------------------------------------------- /14-comprehensive-example/ivp_example.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Scientific-Computing-with-Python-3/1333ac3fe4f90cb9f157682bf2d3a80824528032/14-comprehensive-example/ivp_example.pdf -------------------------------------------------------------------------------- /14-comprehensive-example/ivp_example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Scientific-Computing-with-Python-3/1333ac3fe4f90cb9f157682bf2d3a80824528032/14-comprehensive-example/ivp_example.png -------------------------------------------------------------------------------- /14-comprehensive-example/spectral_4class.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Scientific-Computing-with-Python-3/1333ac3fe4f90cb9f157682bf2d3a80824528032/14-comprehensive-example/spectral_4class.pdf -------------------------------------------------------------------------------- /14-comprehensive-example/spectral_4class.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Scientific-Computing-with-Python-3/1333ac3fe4f90cb9f157682bf2d3a80824528032/14-comprehensive-example/spectral_4class.png -------------------------------------------------------------------------------- /2-VariablesandBasicTypes/.ipynb_checkpoints/2-VariablesandBasicTypes-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 2-Variables and Basic Types\n", 8 | "\n", 9 | "\n", 10 | "Always run this statement first, when working with this book:" 11 | ] 12 | }, 13 | { 14 | "cell_type": "code", 15 | "execution_count": null, 16 | "metadata": { 17 | "collapsed": false 18 | }, 19 | "outputs": [], 20 | "source": [ 21 | "from scipy import *\n", 22 | "from matplotlib.pyplot import *\n", 23 | "%matplotlib inline \n", 24 | "from IPython.core.interactiveshell import InteractiveShell\n", 25 | "InteractiveShell.ast_node_interactivity = \"all\"" 26 | ] 27 | }, 28 | { 29 | "cell_type": "markdown", 30 | "metadata": {}, 31 | "source": [ 32 | "## Variables" 33 | ] 34 | }, 35 | { 36 | "cell_type": "code", 37 | "execution_count": null, 38 | "metadata": { 39 | "collapsed": true 40 | }, 41 | "outputs": [], 42 | "source": [ 43 | "a = 1 \n", 44 | "diameter = 3.\n", 45 | "height = 5.\n", 46 | "cylinder = [diameter, height] # reference to a list" 47 | ] 48 | }, 49 | { 50 | "cell_type": "code", 51 | "execution_count": null, 52 | "metadata": { 53 | "collapsed": false 54 | }, 55 | "outputs": [], 56 | "source": [ 57 | "a = b = c = 1\n", 58 | "a" 59 | ] 60 | }, 61 | { 62 | "cell_type": "code", 63 | "execution_count": null, 64 | "metadata": { 65 | "collapsed": false 66 | }, 67 | "outputs": [], 68 | "source": [ 69 | "a = 1\n", 70 | "a = a + 1 # a gets the value 2\n", 71 | "a\n", 72 | "a = 3 * a\n", 73 | "a" 74 | ] 75 | }, 76 | { 77 | "cell_type": "code", 78 | "execution_count": null, 79 | "metadata": { 80 | "collapsed": false 81 | }, 82 | "outputs": [], 83 | "source": [ 84 | "a = 1\n", 85 | "a += 1 # same as a = a + 1\n", 86 | "a\n", 87 | "a *= 3 # same as a = 3 * a\n", 88 | "a" 89 | ] 90 | }, 91 | { 92 | "cell_type": "markdown", 93 | "metadata": {}, 94 | "source": [ 95 | "## Numeric Types\n", 96 | "\n", 97 | "### Integers" 98 | ] 99 | }, 100 | { 101 | "cell_type": "code", 102 | "execution_count": null, 103 | "metadata": { 104 | "collapsed": false 105 | }, 106 | "outputs": [], 107 | "source": [ 108 | "6 // 2 # 3\n", 109 | "\n", 110 | "7 // 2 # 3\n", 111 | "\n", 112 | "7 / 2 # 3.5 " 113 | ] 114 | }, 115 | { 116 | "cell_type": "markdown", 117 | "metadata": {}, 118 | "source": [ 119 | "### Floating Point Numbers" 120 | ] 121 | }, 122 | { 123 | "cell_type": "code", 124 | "execution_count": null, 125 | "metadata": { 126 | "collapsed": false 127 | }, 128 | "outputs": [], 129 | "source": [ 130 | "0.4 - 0.3 # returns 0.10000000000000003\n", 131 | "\n", 132 | "0.4 - 0.3 == 0.1 # returns False " 133 | ] 134 | }, 135 | { 136 | "cell_type": "markdown", 137 | "metadata": {}, 138 | "source": [ 139 | "#### Infinite and Not a Number" 140 | ] 141 | }, 142 | { 143 | "cell_type": "code", 144 | "execution_count": null, 145 | "metadata": { 146 | "collapsed": false 147 | }, 148 | "outputs": [], 149 | "source": [ 150 | "exp(1000.) # inf\n", 151 | "\n", 152 | "a = inf\n", 153 | "\n", 154 | "3 - a # -inf\n", 155 | "\n", 156 | "3 + a # inf" 157 | ] 158 | }, 159 | { 160 | "cell_type": "code", 161 | "execution_count": null, 162 | "metadata": { 163 | "collapsed": false 164 | }, 165 | "outputs": [], 166 | "source": [ 167 | "a+a # inf\n", 168 | "\n", 169 | "a-a # nan\n", 170 | "\n", 171 | "a/a # nan" 172 | ] 173 | }, 174 | { 175 | "cell_type": "code", 176 | "execution_count": null, 177 | "metadata": { 178 | "collapsed": false 179 | }, 180 | "outputs": [], 181 | "source": [ 182 | "x = nan \n", 183 | "\n", 184 | "x < 0 # False\n", 185 | "\n", 186 | "x > 0 # False\n", 187 | "\n", 188 | "x == x # False" 189 | ] 190 | }, 191 | { 192 | "cell_type": "code", 193 | "execution_count": null, 194 | "metadata": { 195 | "collapsed": false 196 | }, 197 | "outputs": [], 198 | "source": [ 199 | "0 < inf # True \n", 200 | "inf <= inf # True \n", 201 | "inf == inf # True \n", 202 | "-inf < inf # True \n", 203 | "inf - inf # nan \n", 204 | "exp(-inf) # 0 \n", 205 | "exp(1 / inf) # 1" 206 | ] 207 | }, 208 | { 209 | "cell_type": "code", 210 | "execution_count": null, 211 | "metadata": { 212 | "collapsed": false 213 | }, 214 | "outputs": [], 215 | "source": [ 216 | "seterr(all = 'raise')" 217 | ] 218 | }, 219 | { 220 | "cell_type": "markdown", 221 | "metadata": {}, 222 | "source": [ 223 | "#### Underflow: Machine Epsilon" 224 | ] 225 | }, 226 | { 227 | "cell_type": "code", 228 | "execution_count": null, 229 | "metadata": { 230 | "collapsed": false 231 | }, 232 | "outputs": [], 233 | "source": [ 234 | "import sys\n", 235 | "sys.float_info.epsilon # 2.220446049250313e-16 (depending on your system)" 236 | ] 237 | }, 238 | { 239 | "cell_type": "code", 240 | "execution_count": null, 241 | "metadata": { 242 | "collapsed": false 243 | }, 244 | "outputs": [], 245 | "source": [ 246 | "a = '1.356'\n", 247 | "float(a)" 248 | ] 249 | }, 250 | { 251 | "cell_type": "markdown", 252 | "metadata": {}, 253 | "source": [ 254 | "#### Other float types in NumPy" 255 | ] 256 | }, 257 | { 258 | "cell_type": "code", 259 | "execution_count": null, 260 | "metadata": { 261 | "collapsed": false 262 | }, 263 | "outputs": [], 264 | "source": [ 265 | "a = pi # returns 3.141592653589793\n", 266 | "a\n", 267 | "\n", 268 | "a1 = float64(a) # returns 3.1415926535897931\n", 269 | "a1\n", 270 | "\n", 271 | "a2=float32(a) # returns 3.1415927\n", 272 | "a2\n", 273 | "\n", 274 | "a - a1 # returns 0.0 \n", 275 | "a - a2 # returns -8.7422780126189537e-08" 276 | ] 277 | }, 278 | { 279 | "cell_type": "code", 280 | "execution_count": null, 281 | "metadata": { 282 | "collapsed": false 283 | }, 284 | "outputs": [], 285 | "source": [ 286 | "f32 = finfo(float32) \n", 287 | "f32.precision # 6 (decimal digits) \n", 288 | "f64 = finfo(float64) \n", 289 | "f64.precision # 15 (decimal digits) \n", 290 | "f = finfo(float) \n", 291 | "f.precision # 15 (decimal digits) \n", 292 | "f64.max # 1.7976931348623157e+308 (largest number) \n", 293 | "f32.max # 3.4028235e+38 (largest number) \n", 294 | "help(finfo) # Check for more options" 295 | ] 296 | }, 297 | { 298 | "cell_type": "markdown", 299 | "metadata": {}, 300 | "source": [ 301 | "### Complex Numbers" 302 | ] 303 | }, 304 | { 305 | "cell_type": "code", 306 | "execution_count": null, 307 | "metadata": { 308 | "collapsed": false 309 | }, 310 | "outputs": [], 311 | "source": [ 312 | "b = 5.2 \n", 313 | "z = bj # returns a NameError " 314 | ] 315 | }, 316 | { 317 | "cell_type": "code", 318 | "execution_count": null, 319 | "metadata": { 320 | "collapsed": false 321 | }, 322 | "outputs": [], 323 | "source": [ 324 | "z = b*j # returns a NameError" 325 | ] 326 | }, 327 | { 328 | "cell_type": "code", 329 | "execution_count": null, 330 | "metadata": { 331 | "collapsed": false 332 | }, 333 | "outputs": [], 334 | "source": [ 335 | "z = b*1j # is correct\n", 336 | "z" 337 | ] 338 | }, 339 | { 340 | "cell_type": "code", 341 | "execution_count": null, 342 | "metadata": { 343 | "collapsed": false 344 | }, 345 | "outputs": [], 346 | "source": [ 347 | "z = 3.2 + 5.2j \n", 348 | "z.conjugate() # returns (3.2-5.2j)" 349 | ] 350 | }, 351 | { 352 | "cell_type": "markdown", 353 | "metadata": {}, 354 | "source": [ 355 | "#### Real and Imaginary Parts" 356 | ] 357 | }, 358 | { 359 | "cell_type": "code", 360 | "execution_count": null, 361 | "metadata": { 362 | "collapsed": false 363 | }, 364 | "outputs": [], 365 | "source": [ 366 | "z = 1j \n", 367 | "z.real # 0.0 \n", 368 | "z.imag # 1.0 \n", 369 | "z.imag = 2 # AttributeError: readonly attribute" 370 | ] 371 | }, 372 | { 373 | "cell_type": "code", 374 | "execution_count": null, 375 | "metadata": { 376 | "collapsed": false 377 | }, 378 | "outputs": [], 379 | "source": [ 380 | "z = 1 + 0j \n", 381 | "z == 1 # True \n", 382 | "float(z) # TypeError" 383 | ] 384 | }, 385 | { 386 | "cell_type": "code", 387 | "execution_count": null, 388 | "metadata": { 389 | "collapsed": false 390 | }, 391 | "outputs": [], 392 | "source": [ 393 | "import matplotlib.pyplot as plt\n", 394 | "N = 10\n", 395 | "# the following vector contains the Nth roots of unity: \n", 396 | "unity_roots = array([exp(1j*2*pi*k/N) for k in range(N)])\n", 397 | "# access all the real or imaginary parts with real or imag:\n", 398 | "axes(aspect='equal')\n", 399 | "plot(unity_roots.real, unity_roots.imag, 'o')\n", 400 | "allclose(unity_roots**N, 1) # True" 401 | ] 402 | }, 403 | { 404 | "cell_type": "code", 405 | "execution_count": null, 406 | "metadata": { 407 | "collapsed": false 408 | }, 409 | "outputs": [], 410 | "source": [ 411 | "z = 3.2+5.2j \n", 412 | "(z + z.conjugate()) / 2. # returns (3.2+0j) \n", 413 | "((z + z.conjugate()) / 2.).real # returns 3.2 \n", 414 | "(z - z.conjugate()) / 2. # returns 5.2j \n", 415 | "((z - z.conjugate()) / 2.).imag # returns 5.2 \n", 416 | "sqrt(z * z.conjugate()) # returns (6.1057350089894991+0j)" 417 | ] 418 | }, 419 | { 420 | "cell_type": "markdown", 421 | "metadata": {}, 422 | "source": [ 423 | "## Booleans" 424 | ] 425 | }, 426 | { 427 | "cell_type": "code", 428 | "execution_count": null, 429 | "metadata": { 430 | "collapsed": false 431 | }, 432 | "outputs": [], 433 | "source": [ 434 | "a = True\n", 435 | "a\n", 436 | "b = 30>45 # b gets the value False\n", 437 | "b" 438 | ] 439 | }, 440 | { 441 | "cell_type": "code", 442 | "execution_count": null, 443 | "metadata": { 444 | "collapsed": false 445 | }, 446 | "outputs": [], 447 | "source": [ 448 | "x=3\n", 449 | "if x>0:\n", 450 | " print(\"positive\")\n", 451 | "else:\n", 452 | " print(\"nonpositive\")" 453 | ] 454 | }, 455 | { 456 | "cell_type": "markdown", 457 | "metadata": {}, 458 | "source": [ 459 | "### Boolean Operators" 460 | ] 461 | }, 462 | { 463 | "cell_type": "code", 464 | "execution_count": null, 465 | "metadata": { 466 | "collapsed": false 467 | }, 468 | "outputs": [], 469 | "source": [ 470 | "True and False # False\n", 471 | "False or True # True\n", 472 | "(30 > 45) or (27 < 30) # True\n", 473 | "not True # False\n", 474 | "not (3 > 4) # True" 475 | ] 476 | }, 477 | { 478 | "cell_type": "code", 479 | "execution_count": null, 480 | "metadata": { 481 | "collapsed": false 482 | }, 483 | "outputs": [], 484 | "source": [ 485 | "a=3; b=4; c=-1\n", 486 | "\n", 487 | "a < b < c # same as: a < b and b < c\n", 488 | "\n", 489 | "a == b == c # same as: a == b and b == c" 490 | ] 491 | }, 492 | { 493 | "cell_type": "markdown", 494 | "metadata": {}, 495 | "source": [ 496 | "### Boolean Casting" 497 | ] 498 | }, 499 | { 500 | "cell_type": "code", 501 | "execution_count": null, 502 | "metadata": { 503 | "collapsed": false 504 | }, 505 | "outputs": [], 506 | "source": [ 507 | "bool([]) # False \n", 508 | "bool(0) # False \n", 509 | "bool(' ') # True \n", 510 | "bool('') # False \n", 511 | "bool('hello') # True \n", 512 | "bool(1.2) # True \n", 513 | "bool(array([1])) # True \n", 514 | "bool(array([1,2])) # Exception raised!" 515 | ] 516 | }, 517 | { 518 | "cell_type": "markdown", 519 | "metadata": {}, 520 | "source": [ 521 | "#### Automatic Boolean Casting" 522 | ] 523 | }, 524 | { 525 | "cell_type": "code", 526 | "execution_count": null, 527 | "metadata": { 528 | "collapsed": false 529 | }, 530 | "outputs": [], 531 | "source": [ 532 | "if a:\n", 533 | " print('Im here')\n", 534 | "if bool(a): # exactly the same as above\n", 535 | " print('Im there')" 536 | ] 537 | }, 538 | { 539 | "cell_type": "code", 540 | "execution_count": null, 541 | "metadata": { 542 | "collapsed": false 543 | }, 544 | "outputs": [], 545 | "source": [ 546 | "L=[]\n", 547 | "if L:\n", 548 | " print(\"list not empty\")\n", 549 | "else:\n", 550 | " print(\"list is empty\")" 551 | ] 552 | }, 553 | { 554 | "cell_type": "code", 555 | "execution_count": null, 556 | "metadata": { 557 | "collapsed": false 558 | }, 559 | "outputs": [], 560 | "source": [ 561 | "n=23\n", 562 | "if n % 2:\n", 563 | " print(\"n is odd\")\n", 564 | "else:\n", 565 | " print(\"n is even\")" 566 | ] 567 | }, 568 | { 569 | "cell_type": "markdown", 570 | "metadata": {}, 571 | "source": [ 572 | "#### Return values of and and or" 573 | ] 574 | }, 575 | { 576 | "cell_type": "code", 577 | "execution_count": null, 578 | "metadata": { 579 | "collapsed": false 580 | }, 581 | "outputs": [], 582 | "source": [ 583 | "def and_as_function(x,y):\n", 584 | " if not x:\n", 585 | " return x\n", 586 | " else:\n", 587 | " return y\n", 588 | " \n", 589 | "and_as_function(True,False)" 590 | ] 591 | }, 592 | { 593 | "cell_type": "code", 594 | "execution_count": null, 595 | "metadata": { 596 | "collapsed": false 597 | }, 598 | "outputs": [], 599 | "source": [ 600 | "def or_as_function(x,y):\n", 601 | " if x:\n", 602 | " return x\n", 603 | " else:\n", 604 | " return y\n", 605 | " \n", 606 | "or_as_function(True,False)" 607 | ] 608 | }, 609 | { 610 | "cell_type": "code", 611 | "execution_count": null, 612 | "metadata": { 613 | "collapsed": false 614 | }, 615 | "outputs": [], 616 | "source": [ 617 | "True or x_not_defined\n", 618 | "False and x_not_defined" 619 | ] 620 | }, 621 | { 622 | "cell_type": "code", 623 | "execution_count": null, 624 | "metadata": { 625 | "collapsed": false 626 | }, 627 | "outputs": [], 628 | "source": [ 629 | "[1] or 'a' # produces [1]\n", 630 | "'a' or [1] # produces 'a'" 631 | ] 632 | }, 633 | { 634 | "cell_type": "markdown", 635 | "metadata": {}, 636 | "source": [ 637 | "### Booleans and Integers" 638 | ] 639 | }, 640 | { 641 | "cell_type": "code", 642 | "execution_count": null, 643 | "metadata": { 644 | "collapsed": false 645 | }, 646 | "outputs": [], 647 | "source": [ 648 | "def print_ispositive(x):\n", 649 | " possibilities=['nonpositive', 'positive']\n", 650 | " return \"x is {}\".format(possibilities[x>0])\n", 651 | "\n", 652 | "print_ispositive(-23)\n", 653 | "print_ispositive(7)" 654 | ] 655 | }, 656 | { 657 | "cell_type": "code", 658 | "execution_count": null, 659 | "metadata": { 660 | "collapsed": false 661 | }, 662 | "outputs": [], 663 | "source": [ 664 | "True+13\n", 665 | "2*True+5" 666 | ] 667 | }, 668 | { 669 | "cell_type": "markdown", 670 | "metadata": {}, 671 | "source": [ 672 | "## Strings" 673 | ] 674 | }, 675 | { 676 | "cell_type": "code", 677 | "execution_count": null, 678 | "metadata": { 679 | "collapsed": false 680 | }, 681 | "outputs": [], 682 | "source": [ 683 | "name = 'Johan Carlsson'\n", 684 | "child = \"Åsa is Johan Carlsson's daughter\"\n", 685 | "book = \"\"\"Aunt Julia \n", 686 | "and the Scriptwriter\"\"\" \n", 687 | "\n", 688 | "print(name) \n", 689 | "print(child) \n", 690 | "print(book)" 691 | ] 692 | }, 693 | { 694 | "cell_type": "code", 695 | "execution_count": null, 696 | "metadata": { 697 | "collapsed": false 698 | }, 699 | "outputs": [], 700 | "source": [ 701 | "book[-1] # returns 'r'\n", 702 | "\n", 703 | "book[-12:] # returns 'Scriptwriter'" 704 | ] 705 | }, 706 | { 707 | "cell_type": "code", 708 | "execution_count": null, 709 | "metadata": { 710 | "collapsed": false 711 | }, 712 | "outputs": [], 713 | "source": [ 714 | "book[1]='a' # returns TypeError" 715 | ] 716 | }, 717 | { 718 | "cell_type": "code", 719 | "execution_count": null, 720 | "metadata": { 721 | "collapsed": false 722 | }, 723 | "outputs": [], 724 | "source": [ 725 | "print('Temperature:\\t20\\tC\\nPressure:\\t5\\tPa')" 726 | ] 727 | }, 728 | { 729 | "cell_type": "code", 730 | "execution_count": null, 731 | "metadata": { 732 | "collapsed": false 733 | }, 734 | "outputs": [], 735 | "source": [ 736 | "a=\"\"\"\n", 737 | "A multiline\n", 738 | "example\"\"\"\n", 739 | "a # returns '\\nA multiline\\nexample'" 740 | ] 741 | }, 742 | { 743 | "cell_type": "code", 744 | "execution_count": null, 745 | "metadata": { 746 | "collapsed": false 747 | }, 748 | "outputs": [], 749 | "source": [ 750 | "latexfontsize=\"\\\\tiny\"\n", 751 | "print(latexfontsize)" 752 | ] 753 | }, 754 | { 755 | "cell_type": "code", 756 | "execution_count": null, 757 | "metadata": { 758 | "collapsed": false 759 | }, 760 | "outputs": [], 761 | "source": [ 762 | "latexfs=r\"\\tiny\" \n", 763 | "latexfs # returns \"\\\\tiny\"\n", 764 | "latexfontsize == latexfs # returns True" 765 | ] 766 | }, 767 | { 768 | "cell_type": "code", 769 | "execution_count": null, 770 | "metadata": { 771 | "collapsed": false 772 | }, 773 | "outputs": [], 774 | "source": [ 775 | "r\"\\\"\" # returns '\\\\\"'\n", 776 | "r\"\\\\\" # returns '\\\\\\\\'\n" 777 | ] 778 | }, 779 | { 780 | "cell_type": "code", 781 | "execution_count": null, 782 | "metadata": { 783 | "collapsed": false 784 | }, 785 | "outputs": [], 786 | "source": [ 787 | "r\"\\\" # returns an error" 788 | ] 789 | }, 790 | { 791 | "cell_type": "markdown", 792 | "metadata": {}, 793 | "source": [ 794 | "### Operations on strings and string methods" 795 | ] 796 | }, 797 | { 798 | "cell_type": "code", 799 | "execution_count": null, 800 | "metadata": { 801 | "collapsed": false 802 | }, 803 | "outputs": [], 804 | "source": [ 805 | "last_name='Carlsson'\n", 806 | "first_name='Johanna'\n", 807 | "Full_name=first_name+' '+last_name # returns 'Johanna Carlsson'\n", 808 | "\n", 809 | "Full_name" 810 | ] 811 | }, 812 | { 813 | "cell_type": "code", 814 | "execution_count": null, 815 | "metadata": { 816 | "collapsed": false 817 | }, 818 | "outputs": [], 819 | "source": [ 820 | "game=2*'Yo' # returns 'YoYo'\n", 821 | "game" 822 | ] 823 | }, 824 | { 825 | "cell_type": "code", 826 | "execution_count": null, 827 | "metadata": { 828 | "collapsed": false 829 | }, 830 | "outputs": [], 831 | "source": [ 832 | "'Anna' > 'Arvid' # returns false\n", 833 | "\n", 834 | "'ANNA' < 'anna' # returns true\n", 835 | "\n", 836 | "'10B' < '11A' # returns true" 837 | ] 838 | }, 839 | { 840 | "cell_type": "code", 841 | "execution_count": null, 842 | "metadata": { 843 | "collapsed": false 844 | }, 845 | "outputs": [], 846 | "source": [ 847 | "text = 'quod erat demonstrandum'\n", 848 | "text.split() # returns ['quod', 'erat', 'demonstrandum']\n", 849 | "table = 'Johan;Carlsson;19890327'\n", 850 | "table.split(';') # returns ['Johan','Carlsson','19890327']\n", 851 | "king = 'CarlXVIGustaf'\n", 852 | "king.split('XVI') # returns ['Carl','Gustaf']" 853 | ] 854 | }, 855 | { 856 | "cell_type": "code", 857 | "execution_count": null, 858 | "metadata": { 859 | "collapsed": false 860 | }, 861 | "outputs": [], 862 | "source": [ 863 | "sep=';'\n", 864 | "sep.join(['Johan','Carlsson','19890327']) # returns 'Johan;Carlsson;19890327'" 865 | ] 866 | }, 867 | { 868 | "cell_type": "code", 869 | "execution_count": null, 870 | "metadata": { 871 | "collapsed": false 872 | }, 873 | "outputs": [], 874 | "source": [ 875 | "birthday='20101210'\n", 876 | "birthday.find('10') # returns 2 " 877 | ] 878 | }, 879 | { 880 | "cell_type": "markdown", 881 | "metadata": {}, 882 | "source": [ 883 | "### String Formatting" 884 | ] 885 | }, 886 | { 887 | "cell_type": "code", 888 | "execution_count": null, 889 | "metadata": { 890 | "collapsed": false 891 | }, 892 | "outputs": [], 893 | "source": [ 894 | "course_code = \"NUMA21\"\n", 895 | "print(\"This course's name is {}\".format(course_code)) # This course's name is NUMA21" 896 | ] 897 | }, 898 | { 899 | "cell_type": "code", 900 | "execution_count": null, 901 | "metadata": { 902 | "collapsed": false 903 | }, 904 | "outputs": [], 905 | "source": [ 906 | "quantity = 33.45\n", 907 | "print(\"qty{:f}\".format(quantity)) # qty33.450000\n", 908 | "print(\"qty{:8.1f}\".format(quantity)) # qty 33.5\n", 909 | "print(\"qty{:10.2e}\".format(quantity)) # qty 3.35e+01" 910 | ] 911 | }, 912 | { 913 | "cell_type": "code", 914 | "execution_count": null, 915 | "metadata": { 916 | "collapsed": false 917 | }, 918 | "outputs": [], 919 | "source": [ 920 | "print(\"{name} {value:.1f}\".format(name=\"quantity\",value=quantity)) # \"quantity 33.5\"" 921 | ] 922 | }, 923 | { 924 | "cell_type": "code", 925 | "execution_count": null, 926 | "metadata": { 927 | "collapsed": false 928 | }, 929 | "outputs": [], 930 | "source": [ 931 | "r\"we {} in LaTeX \\begin{{equation}}\".format('like')" 932 | ] 933 | } 934 | ], 935 | "metadata": { 936 | "anaconda-cloud": {}, 937 | "kernelspec": { 938 | "display_name": "Python 3", 939 | "language": "python", 940 | "name": "python3" 941 | }, 942 | "language_info": { 943 | "codemirror_mode": { 944 | "name": "ipython", 945 | "version": 3 946 | }, 947 | "file_extension": ".py", 948 | "mimetype": "text/x-python", 949 | "name": "python", 950 | "nbconvert_exporter": "python", 951 | "pygments_lexer": "ipython3", 952 | "version": "3.5.2" 953 | } 954 | }, 955 | "nbformat": 4, 956 | "nbformat_minor": 0 957 | } 958 | -------------------------------------------------------------------------------- /2-VariablesandBasicTypes/2-VariablesandBasicTypes.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 2-Variables and Basic Types\n", 8 | "\n", 9 | "\n", 10 | "Always run this statement first, when working with this book:" 11 | ] 12 | }, 13 | { 14 | "cell_type": "code", 15 | "execution_count": null, 16 | "metadata": { 17 | "collapsed": false 18 | }, 19 | "outputs": [], 20 | "source": [ 21 | "from scipy import *\n", 22 | "from matplotlib.pyplot import *\n", 23 | "%matplotlib inline \n", 24 | "from IPython.core.interactiveshell import InteractiveShell\n", 25 | "InteractiveShell.ast_node_interactivity = \"all\"" 26 | ] 27 | }, 28 | { 29 | "cell_type": "markdown", 30 | "metadata": {}, 31 | "source": [ 32 | "## Variables" 33 | ] 34 | }, 35 | { 36 | "cell_type": "code", 37 | "execution_count": null, 38 | "metadata": { 39 | "collapsed": true 40 | }, 41 | "outputs": [], 42 | "source": [ 43 | "a = 1 \n", 44 | "diameter = 3.\n", 45 | "height = 5.\n", 46 | "cylinder = [diameter, height] # reference to a list" 47 | ] 48 | }, 49 | { 50 | "cell_type": "code", 51 | "execution_count": null, 52 | "metadata": { 53 | "collapsed": false 54 | }, 55 | "outputs": [], 56 | "source": [ 57 | "a = b = c = 1\n", 58 | "a" 59 | ] 60 | }, 61 | { 62 | "cell_type": "code", 63 | "execution_count": null, 64 | "metadata": { 65 | "collapsed": false 66 | }, 67 | "outputs": [], 68 | "source": [ 69 | "a = 1\n", 70 | "a = a + 1 # a gets the value 2\n", 71 | "a\n", 72 | "a = 3 * a\n", 73 | "a" 74 | ] 75 | }, 76 | { 77 | "cell_type": "code", 78 | "execution_count": null, 79 | "metadata": { 80 | "collapsed": false 81 | }, 82 | "outputs": [], 83 | "source": [ 84 | "a = 1\n", 85 | "a += 1 # same as a = a + 1\n", 86 | "a\n", 87 | "a *= 3 # same as a = 3 * a\n", 88 | "a" 89 | ] 90 | }, 91 | { 92 | "cell_type": "markdown", 93 | "metadata": {}, 94 | "source": [ 95 | "## Numeric Types\n", 96 | "\n", 97 | "### Integers" 98 | ] 99 | }, 100 | { 101 | "cell_type": "code", 102 | "execution_count": null, 103 | "metadata": { 104 | "collapsed": false 105 | }, 106 | "outputs": [], 107 | "source": [ 108 | "6 // 2 # 3\n", 109 | "\n", 110 | "7 // 2 # 3\n", 111 | "\n", 112 | "7 / 2 # 3.5 " 113 | ] 114 | }, 115 | { 116 | "cell_type": "markdown", 117 | "metadata": {}, 118 | "source": [ 119 | "### Floating Point Numbers" 120 | ] 121 | }, 122 | { 123 | "cell_type": "code", 124 | "execution_count": null, 125 | "metadata": { 126 | "collapsed": false 127 | }, 128 | "outputs": [], 129 | "source": [ 130 | "0.4 - 0.3 # returns 0.10000000000000003\n", 131 | "\n", 132 | "0.4 - 0.3 == 0.1 # returns False " 133 | ] 134 | }, 135 | { 136 | "cell_type": "markdown", 137 | "metadata": {}, 138 | "source": [ 139 | "#### Infinite and Not a Number" 140 | ] 141 | }, 142 | { 143 | "cell_type": "code", 144 | "execution_count": null, 145 | "metadata": { 146 | "collapsed": false 147 | }, 148 | "outputs": [], 149 | "source": [ 150 | "exp(1000.) # inf\n", 151 | "\n", 152 | "a = inf\n", 153 | "\n", 154 | "3 - a # -inf\n", 155 | "\n", 156 | "3 + a # inf" 157 | ] 158 | }, 159 | { 160 | "cell_type": "code", 161 | "execution_count": null, 162 | "metadata": { 163 | "collapsed": false 164 | }, 165 | "outputs": [], 166 | "source": [ 167 | "a+a # inf\n", 168 | "\n", 169 | "a-a # nan\n", 170 | "\n", 171 | "a/a # nan" 172 | ] 173 | }, 174 | { 175 | "cell_type": "code", 176 | "execution_count": null, 177 | "metadata": { 178 | "collapsed": false 179 | }, 180 | "outputs": [], 181 | "source": [ 182 | "x = nan \n", 183 | "\n", 184 | "x < 0 # False\n", 185 | "\n", 186 | "x > 0 # False\n", 187 | "\n", 188 | "x == x # False" 189 | ] 190 | }, 191 | { 192 | "cell_type": "code", 193 | "execution_count": null, 194 | "metadata": { 195 | "collapsed": false 196 | }, 197 | "outputs": [], 198 | "source": [ 199 | "0 < inf # True \n", 200 | "inf <= inf # True \n", 201 | "inf == inf # True \n", 202 | "-inf < inf # True \n", 203 | "inf - inf # nan \n", 204 | "exp(-inf) # 0 \n", 205 | "exp(1 / inf) # 1" 206 | ] 207 | }, 208 | { 209 | "cell_type": "code", 210 | "execution_count": null, 211 | "metadata": { 212 | "collapsed": false 213 | }, 214 | "outputs": [], 215 | "source": [ 216 | "seterr(all = 'raise')" 217 | ] 218 | }, 219 | { 220 | "cell_type": "markdown", 221 | "metadata": {}, 222 | "source": [ 223 | "#### Underflow: Machine Epsilon" 224 | ] 225 | }, 226 | { 227 | "cell_type": "code", 228 | "execution_count": null, 229 | "metadata": { 230 | "collapsed": false 231 | }, 232 | "outputs": [], 233 | "source": [ 234 | "import sys\n", 235 | "sys.float_info.epsilon # 2.220446049250313e-16 (depending on your system)" 236 | ] 237 | }, 238 | { 239 | "cell_type": "code", 240 | "execution_count": null, 241 | "metadata": { 242 | "collapsed": false 243 | }, 244 | "outputs": [], 245 | "source": [ 246 | "a = '1.356'\n", 247 | "float(a)" 248 | ] 249 | }, 250 | { 251 | "cell_type": "markdown", 252 | "metadata": {}, 253 | "source": [ 254 | "#### Other float types in NumPy" 255 | ] 256 | }, 257 | { 258 | "cell_type": "code", 259 | "execution_count": null, 260 | "metadata": { 261 | "collapsed": false 262 | }, 263 | "outputs": [], 264 | "source": [ 265 | "a = pi # returns 3.141592653589793\n", 266 | "a\n", 267 | "\n", 268 | "a1 = float64(a) # returns 3.1415926535897931\n", 269 | "a1\n", 270 | "\n", 271 | "a2=float32(a) # returns 3.1415927\n", 272 | "a2\n", 273 | "\n", 274 | "a - a1 # returns 0.0 \n", 275 | "a - a2 # returns -8.7422780126189537e-08" 276 | ] 277 | }, 278 | { 279 | "cell_type": "code", 280 | "execution_count": null, 281 | "metadata": { 282 | "collapsed": false 283 | }, 284 | "outputs": [], 285 | "source": [ 286 | "f32 = finfo(float32) \n", 287 | "f32.precision # 6 (decimal digits) \n", 288 | "f64 = finfo(float64) \n", 289 | "f64.precision # 15 (decimal digits) \n", 290 | "f = finfo(float) \n", 291 | "f.precision # 15 (decimal digits) \n", 292 | "f64.max # 1.7976931348623157e+308 (largest number) \n", 293 | "f32.max # 3.4028235e+38 (largest number) \n", 294 | "help(finfo) # Check for more options" 295 | ] 296 | }, 297 | { 298 | "cell_type": "markdown", 299 | "metadata": {}, 300 | "source": [ 301 | "### Complex Numbers" 302 | ] 303 | }, 304 | { 305 | "cell_type": "code", 306 | "execution_count": null, 307 | "metadata": { 308 | "collapsed": false 309 | }, 310 | "outputs": [], 311 | "source": [ 312 | "b = 5.2 \n", 313 | "z = bj # returns a NameError " 314 | ] 315 | }, 316 | { 317 | "cell_type": "code", 318 | "execution_count": null, 319 | "metadata": { 320 | "collapsed": false 321 | }, 322 | "outputs": [], 323 | "source": [ 324 | "z = b*j # returns a NameError" 325 | ] 326 | }, 327 | { 328 | "cell_type": "code", 329 | "execution_count": null, 330 | "metadata": { 331 | "collapsed": false 332 | }, 333 | "outputs": [], 334 | "source": [ 335 | "z = b*1j # is correct\n", 336 | "z" 337 | ] 338 | }, 339 | { 340 | "cell_type": "code", 341 | "execution_count": null, 342 | "metadata": { 343 | "collapsed": false 344 | }, 345 | "outputs": [], 346 | "source": [ 347 | "z = 3.2 + 5.2j \n", 348 | "z.conjugate() # returns (3.2-5.2j)" 349 | ] 350 | }, 351 | { 352 | "cell_type": "markdown", 353 | "metadata": {}, 354 | "source": [ 355 | "#### Real and Imaginary Parts" 356 | ] 357 | }, 358 | { 359 | "cell_type": "code", 360 | "execution_count": null, 361 | "metadata": { 362 | "collapsed": false 363 | }, 364 | "outputs": [], 365 | "source": [ 366 | "z = 1j \n", 367 | "z.real # 0.0 \n", 368 | "z.imag # 1.0 \n", 369 | "z.imag = 2 # AttributeError: readonly attribute" 370 | ] 371 | }, 372 | { 373 | "cell_type": "code", 374 | "execution_count": null, 375 | "metadata": { 376 | "collapsed": false 377 | }, 378 | "outputs": [], 379 | "source": [ 380 | "z = 1 + 0j \n", 381 | "z == 1 # True \n", 382 | "float(z) # TypeError" 383 | ] 384 | }, 385 | { 386 | "cell_type": "code", 387 | "execution_count": null, 388 | "metadata": { 389 | "collapsed": false 390 | }, 391 | "outputs": [], 392 | "source": [ 393 | "import matplotlib.pyplot as plt\n", 394 | "N = 10\n", 395 | "# the following vector contains the Nth roots of unity: \n", 396 | "unity_roots = array([exp(1j*2*pi*k/N) for k in range(N)])\n", 397 | "# access all the real or imaginary parts with real or imag:\n", 398 | "axes(aspect='equal')\n", 399 | "plot(unity_roots.real, unity_roots.imag, 'o')\n", 400 | "allclose(unity_roots**N, 1) # True" 401 | ] 402 | }, 403 | { 404 | "cell_type": "code", 405 | "execution_count": null, 406 | "metadata": { 407 | "collapsed": false 408 | }, 409 | "outputs": [], 410 | "source": [ 411 | "z = 3.2+5.2j \n", 412 | "(z + z.conjugate()) / 2. # returns (3.2+0j) \n", 413 | "((z + z.conjugate()) / 2.).real # returns 3.2 \n", 414 | "(z - z.conjugate()) / 2. # returns 5.2j \n", 415 | "((z - z.conjugate()) / 2.).imag # returns 5.2 \n", 416 | "sqrt(z * z.conjugate()) # returns (6.1057350089894991+0j)" 417 | ] 418 | }, 419 | { 420 | "cell_type": "markdown", 421 | "metadata": {}, 422 | "source": [ 423 | "## Booleans" 424 | ] 425 | }, 426 | { 427 | "cell_type": "code", 428 | "execution_count": null, 429 | "metadata": { 430 | "collapsed": false 431 | }, 432 | "outputs": [], 433 | "source": [ 434 | "a = True\n", 435 | "a\n", 436 | "b = 30>45 # b gets the value False\n", 437 | "b" 438 | ] 439 | }, 440 | { 441 | "cell_type": "code", 442 | "execution_count": null, 443 | "metadata": { 444 | "collapsed": false 445 | }, 446 | "outputs": [], 447 | "source": [ 448 | "x=3\n", 449 | "if x>0:\n", 450 | " print(\"positive\")\n", 451 | "else:\n", 452 | " print(\"nonpositive\")" 453 | ] 454 | }, 455 | { 456 | "cell_type": "markdown", 457 | "metadata": {}, 458 | "source": [ 459 | "### Boolean Operators" 460 | ] 461 | }, 462 | { 463 | "cell_type": "code", 464 | "execution_count": null, 465 | "metadata": { 466 | "collapsed": false 467 | }, 468 | "outputs": [], 469 | "source": [ 470 | "True and False # False\n", 471 | "False or True # True\n", 472 | "(30 > 45) or (27 < 30) # True\n", 473 | "not True # False\n", 474 | "not (3 > 4) # True" 475 | ] 476 | }, 477 | { 478 | "cell_type": "code", 479 | "execution_count": null, 480 | "metadata": { 481 | "collapsed": false 482 | }, 483 | "outputs": [], 484 | "source": [ 485 | "a=3; b=4; c=-1\n", 486 | "\n", 487 | "a < b < c # same as: a < b and b < c\n", 488 | "\n", 489 | "a == b == c # same as: a == b and b == c" 490 | ] 491 | }, 492 | { 493 | "cell_type": "markdown", 494 | "metadata": {}, 495 | "source": [ 496 | "### Boolean Casting" 497 | ] 498 | }, 499 | { 500 | "cell_type": "code", 501 | "execution_count": null, 502 | "metadata": { 503 | "collapsed": false 504 | }, 505 | "outputs": [], 506 | "source": [ 507 | "bool([]) # False \n", 508 | "bool(0) # False \n", 509 | "bool(' ') # True \n", 510 | "bool('') # False \n", 511 | "bool('hello') # True \n", 512 | "bool(1.2) # True \n", 513 | "bool(array([1])) # True \n", 514 | "bool(array([1,2])) # Exception raised!" 515 | ] 516 | }, 517 | { 518 | "cell_type": "markdown", 519 | "metadata": {}, 520 | "source": [ 521 | "#### Automatic Boolean Casting" 522 | ] 523 | }, 524 | { 525 | "cell_type": "code", 526 | "execution_count": null, 527 | "metadata": { 528 | "collapsed": false 529 | }, 530 | "outputs": [], 531 | "source": [ 532 | "if a:\n", 533 | " print('Im here')\n", 534 | "if bool(a): # exactly the same as above\n", 535 | " print('Im there')" 536 | ] 537 | }, 538 | { 539 | "cell_type": "code", 540 | "execution_count": null, 541 | "metadata": { 542 | "collapsed": false 543 | }, 544 | "outputs": [], 545 | "source": [ 546 | "L=[]\n", 547 | "if L:\n", 548 | " print(\"list not empty\")\n", 549 | "else:\n", 550 | " print(\"list is empty\")" 551 | ] 552 | }, 553 | { 554 | "cell_type": "code", 555 | "execution_count": null, 556 | "metadata": { 557 | "collapsed": false 558 | }, 559 | "outputs": [], 560 | "source": [ 561 | "n=23\n", 562 | "if n % 2:\n", 563 | " print(\"n is odd\")\n", 564 | "else:\n", 565 | " print(\"n is even\")" 566 | ] 567 | }, 568 | { 569 | "cell_type": "markdown", 570 | "metadata": {}, 571 | "source": [ 572 | "#### Return values of and and or" 573 | ] 574 | }, 575 | { 576 | "cell_type": "code", 577 | "execution_count": null, 578 | "metadata": { 579 | "collapsed": false 580 | }, 581 | "outputs": [], 582 | "source": [ 583 | "def and_as_function(x,y):\n", 584 | " if not x:\n", 585 | " return x\n", 586 | " else:\n", 587 | " return y\n", 588 | " \n", 589 | "and_as_function(True,False)" 590 | ] 591 | }, 592 | { 593 | "cell_type": "code", 594 | "execution_count": null, 595 | "metadata": { 596 | "collapsed": false 597 | }, 598 | "outputs": [], 599 | "source": [ 600 | "def or_as_function(x,y):\n", 601 | " if x:\n", 602 | " return x\n", 603 | " else:\n", 604 | " return y\n", 605 | " \n", 606 | "or_as_function(True,False)" 607 | ] 608 | }, 609 | { 610 | "cell_type": "code", 611 | "execution_count": null, 612 | "metadata": { 613 | "collapsed": false 614 | }, 615 | "outputs": [], 616 | "source": [ 617 | "True or x_not_defined\n", 618 | "False and x_not_defined" 619 | ] 620 | }, 621 | { 622 | "cell_type": "code", 623 | "execution_count": null, 624 | "metadata": { 625 | "collapsed": false 626 | }, 627 | "outputs": [], 628 | "source": [ 629 | "[1] or 'a' # produces [1]\n", 630 | "'a' or [1] # produces 'a'" 631 | ] 632 | }, 633 | { 634 | "cell_type": "markdown", 635 | "metadata": {}, 636 | "source": [ 637 | "### Booleans and Integers" 638 | ] 639 | }, 640 | { 641 | "cell_type": "code", 642 | "execution_count": null, 643 | "metadata": { 644 | "collapsed": false 645 | }, 646 | "outputs": [], 647 | "source": [ 648 | "def print_ispositive(x):\n", 649 | " possibilities=['nonpositive', 'positive']\n", 650 | " return \"x is {}\".format(possibilities[x>0])\n", 651 | "\n", 652 | "print_ispositive(-23)\n", 653 | "print_ispositive(7)" 654 | ] 655 | }, 656 | { 657 | "cell_type": "code", 658 | "execution_count": null, 659 | "metadata": { 660 | "collapsed": false 661 | }, 662 | "outputs": [], 663 | "source": [ 664 | "True+13\n", 665 | "2*True+5" 666 | ] 667 | }, 668 | { 669 | "cell_type": "markdown", 670 | "metadata": {}, 671 | "source": [ 672 | "## Strings" 673 | ] 674 | }, 675 | { 676 | "cell_type": "code", 677 | "execution_count": null, 678 | "metadata": { 679 | "collapsed": false 680 | }, 681 | "outputs": [], 682 | "source": [ 683 | "name = 'Johan Carlsson'\n", 684 | "child = \"Åsa is Johan Carlsson's daughter\"\n", 685 | "book = \"\"\"Aunt Julia \n", 686 | "and the Scriptwriter\"\"\" \n", 687 | "\n", 688 | "print(name) \n", 689 | "print(child) \n", 690 | "print(book)" 691 | ] 692 | }, 693 | { 694 | "cell_type": "code", 695 | "execution_count": null, 696 | "metadata": { 697 | "collapsed": false 698 | }, 699 | "outputs": [], 700 | "source": [ 701 | "book[-1] # returns 'r'\n", 702 | "\n", 703 | "book[-12:] # returns 'Scriptwriter'" 704 | ] 705 | }, 706 | { 707 | "cell_type": "code", 708 | "execution_count": null, 709 | "metadata": { 710 | "collapsed": false 711 | }, 712 | "outputs": [], 713 | "source": [ 714 | "book[1]='a' # returns TypeError" 715 | ] 716 | }, 717 | { 718 | "cell_type": "code", 719 | "execution_count": null, 720 | "metadata": { 721 | "collapsed": false 722 | }, 723 | "outputs": [], 724 | "source": [ 725 | "print('Temperature:\\t20\\tC\\nPressure:\\t5\\tPa')" 726 | ] 727 | }, 728 | { 729 | "cell_type": "code", 730 | "execution_count": null, 731 | "metadata": { 732 | "collapsed": false 733 | }, 734 | "outputs": [], 735 | "source": [ 736 | "a=\"\"\"\n", 737 | "A multiline\n", 738 | "example\"\"\"\n", 739 | "a # returns '\\nA multiline\\nexample'" 740 | ] 741 | }, 742 | { 743 | "cell_type": "code", 744 | "execution_count": null, 745 | "metadata": { 746 | "collapsed": false 747 | }, 748 | "outputs": [], 749 | "source": [ 750 | "latexfontsize=\"\\\\tiny\"\n", 751 | "print(latexfontsize)" 752 | ] 753 | }, 754 | { 755 | "cell_type": "code", 756 | "execution_count": null, 757 | "metadata": { 758 | "collapsed": false 759 | }, 760 | "outputs": [], 761 | "source": [ 762 | "latexfs=r\"\\tiny\" \n", 763 | "latexfs # returns \"\\\\tiny\"\n", 764 | "latexfontsize == latexfs # returns True" 765 | ] 766 | }, 767 | { 768 | "cell_type": "code", 769 | "execution_count": null, 770 | "metadata": { 771 | "collapsed": false 772 | }, 773 | "outputs": [], 774 | "source": [ 775 | "r\"\\\"\" # returns '\\\\\"'\n", 776 | "r\"\\\\\" # returns '\\\\\\\\'\n" 777 | ] 778 | }, 779 | { 780 | "cell_type": "code", 781 | "execution_count": null, 782 | "metadata": { 783 | "collapsed": false 784 | }, 785 | "outputs": [], 786 | "source": [ 787 | "r\"\\\" # returns an error" 788 | ] 789 | }, 790 | { 791 | "cell_type": "markdown", 792 | "metadata": {}, 793 | "source": [ 794 | "### Operations on strings and string methods" 795 | ] 796 | }, 797 | { 798 | "cell_type": "code", 799 | "execution_count": null, 800 | "metadata": { 801 | "collapsed": false 802 | }, 803 | "outputs": [], 804 | "source": [ 805 | "last_name='Carlsson'\n", 806 | "first_name='Johanna'\n", 807 | "Full_name=first_name+' '+last_name # returns 'Johanna Carlsson'\n", 808 | "\n", 809 | "Full_name" 810 | ] 811 | }, 812 | { 813 | "cell_type": "code", 814 | "execution_count": null, 815 | "metadata": { 816 | "collapsed": false 817 | }, 818 | "outputs": [], 819 | "source": [ 820 | "game=2*'Yo' # returns 'YoYo'\n", 821 | "game" 822 | ] 823 | }, 824 | { 825 | "cell_type": "code", 826 | "execution_count": null, 827 | "metadata": { 828 | "collapsed": false 829 | }, 830 | "outputs": [], 831 | "source": [ 832 | "'Anna' > 'Arvid' # returns false\n", 833 | "\n", 834 | "'ANNA' < 'anna' # returns true\n", 835 | "\n", 836 | "'10B' < '11A' # returns true" 837 | ] 838 | }, 839 | { 840 | "cell_type": "code", 841 | "execution_count": null, 842 | "metadata": { 843 | "collapsed": false 844 | }, 845 | "outputs": [], 846 | "source": [ 847 | "text = 'quod erat demonstrandum'\n", 848 | "text.split() # returns ['quod', 'erat', 'demonstrandum']\n", 849 | "table = 'Johan;Carlsson;19890327'\n", 850 | "table.split(';') # returns ['Johan','Carlsson','19890327']\n", 851 | "king = 'CarlXVIGustaf'\n", 852 | "king.split('XVI') # returns ['Carl','Gustaf']" 853 | ] 854 | }, 855 | { 856 | "cell_type": "code", 857 | "execution_count": null, 858 | "metadata": { 859 | "collapsed": false 860 | }, 861 | "outputs": [], 862 | "source": [ 863 | "sep=';'\n", 864 | "sep.join(['Johan','Carlsson','19890327']) # returns 'Johan;Carlsson;19890327'" 865 | ] 866 | }, 867 | { 868 | "cell_type": "code", 869 | "execution_count": null, 870 | "metadata": { 871 | "collapsed": false 872 | }, 873 | "outputs": [], 874 | "source": [ 875 | "birthday='20101210'\n", 876 | "birthday.find('10') # returns 2 " 877 | ] 878 | }, 879 | { 880 | "cell_type": "markdown", 881 | "metadata": {}, 882 | "source": [ 883 | "### String Formatting" 884 | ] 885 | }, 886 | { 887 | "cell_type": "code", 888 | "execution_count": null, 889 | "metadata": { 890 | "collapsed": false 891 | }, 892 | "outputs": [], 893 | "source": [ 894 | "course_code = \"NUMA21\"\n", 895 | "print(\"This course's name is {}\".format(course_code)) # This course's name is NUMA21" 896 | ] 897 | }, 898 | { 899 | "cell_type": "code", 900 | "execution_count": null, 901 | "metadata": { 902 | "collapsed": false 903 | }, 904 | "outputs": [], 905 | "source": [ 906 | "quantity = 33.45\n", 907 | "print(\"qty{:f}\".format(quantity)) # qty33.450000\n", 908 | "print(\"qty{:8.1f}\".format(quantity)) # qty 33.5\n", 909 | "print(\"qty{:10.2e}\".format(quantity)) # qty 3.35e+01" 910 | ] 911 | }, 912 | { 913 | "cell_type": "code", 914 | "execution_count": null, 915 | "metadata": { 916 | "collapsed": false 917 | }, 918 | "outputs": [], 919 | "source": [ 920 | "print(\"{name} {value:.1f}\".format(name=\"quantity\",value=quantity)) # \"quantity 33.5\"" 921 | ] 922 | }, 923 | { 924 | "cell_type": "code", 925 | "execution_count": null, 926 | "metadata": { 927 | "collapsed": false 928 | }, 929 | "outputs": [], 930 | "source": [ 931 | "r\"we {} in LaTeX \\begin{{equation}}\".format('like')" 932 | ] 933 | } 934 | ], 935 | "metadata": { 936 | "anaconda-cloud": {}, 937 | "kernelspec": { 938 | "display_name": "Python 3", 939 | "language": "python", 940 | "name": "python3" 941 | }, 942 | "language_info": { 943 | "codemirror_mode": { 944 | "name": "ipython", 945 | "version": 3 946 | }, 947 | "file_extension": ".py", 948 | "mimetype": "text/x-python", 949 | "name": "python", 950 | "nbconvert_exporter": "python", 951 | "pygments_lexer": "ipython3", 952 | "version": "3.5.2" 953 | } 954 | }, 955 | "nbformat": 4, 956 | "nbformat_minor": 0 957 | } 958 | -------------------------------------------------------------------------------- /2-VariablesandBasicTypes/2-VariablesandBasicTypes.py: -------------------------------------------------------------------------------- 1 | 2 | # coding: utf-8 3 | 4 | # # 2-Variables and Basic Types 5 | # 6 | # 7 | # Always run this statement first, when working with this book: 8 | 9 | # In[1]: 10 | 11 | from scipy import * 12 | from matplotlib.pyplot import * 13 | get_ipython().magic('matplotlib inline') 14 | from IPython.core.interactiveshell import InteractiveShell 15 | InteractiveShell.ast_node_interactivity = "all" 16 | 17 | 18 | # ## Variables 19 | 20 | # In[2]: 21 | 22 | a = 1 23 | diameter = 3. 24 | height = 5. 25 | cylinder = [diameter, height] # reference to a list 26 | 27 | 28 | # In[3]: 29 | 30 | a = b = c = 1 31 | a 32 | 33 | 34 | # In[4]: 35 | 36 | a = 1 37 | a = a + 1 # a gets the value 2 38 | a 39 | a = 3 * a 40 | a 41 | 42 | 43 | # In[5]: 44 | 45 | a = 1 46 | a += 1 # same as a = a + 1 47 | a 48 | a *= 3 # same as a = 3 * a 49 | a 50 | 51 | 52 | # ## Numeric Types 53 | # 54 | # ### Integers 55 | 56 | # In[6]: 57 | 58 | 6 // 2 # 3 59 | 60 | 7 // 2 # 3 61 | 62 | 7 / 2 # 3.5 63 | 64 | 65 | # ### Floating Point Numbers 66 | 67 | # In[7]: 68 | 69 | 0.4 - 0.3 # returns 0.10000000000000003 70 | 71 | 0.4 - 0.3 == 0.1 # returns False 72 | 73 | 74 | # #### Infinite and Not a Number 75 | 76 | # In[8]: 77 | 78 | exp(1000.) # inf 79 | 80 | a = inf 81 | 82 | 3 - a # -inf 83 | 84 | 3 + a # inf 85 | 86 | 87 | # In[9]: 88 | 89 | a+a # inf 90 | 91 | a-a # nan 92 | 93 | a/a # nan 94 | 95 | 96 | # In[10]: 97 | 98 | x = nan 99 | 100 | x < 0 # False 101 | 102 | x > 0 # False 103 | 104 | x == x # False 105 | 106 | 107 | # In[11]: 108 | 109 | 0 < inf # True 110 | inf <= inf # True 111 | inf == inf # True 112 | -inf < inf # True 113 | inf - inf # nan 114 | exp(-inf) # 0 115 | exp(1 / inf) # 1 116 | 117 | 118 | # In[12]: 119 | 120 | seterr(all = 'raise') 121 | 122 | 123 | # #### Underflow: Machine Epsilon 124 | 125 | # In[13]: 126 | 127 | import sys 128 | sys.float_info.epsilon # 2.220446049250313e-16 (depending on your system) 129 | 130 | 131 | # In[14]: 132 | 133 | a = '1.356' 134 | float(a) 135 | 136 | 137 | # #### Other float types in NumPy 138 | 139 | # In[15]: 140 | 141 | a = pi # returns 3.141592653589793 142 | a 143 | 144 | a1 = float64(a) # returns 3.1415926535897931 145 | a1 146 | 147 | a2=float32(a) # returns 3.1415927 148 | a2 149 | 150 | a - a1 # returns 0.0 151 | a - a2 # returns -8.7422780126189537e-08 152 | 153 | 154 | # In[16]: 155 | 156 | f32 = finfo(float32) 157 | f32.precision # 6 (decimal digits) 158 | f64 = finfo(float64) 159 | f64.precision # 15 (decimal digits) 160 | f = finfo(float) 161 | f.precision # 15 (decimal digits) 162 | f64.max # 1.7976931348623157e+308 (largest number) 163 | f32.max # 3.4028235e+38 (largest number) 164 | help(finfo) # Check for more options 165 | 166 | 167 | # ### Complex Numbers 168 | 169 | # In[17]: 170 | 171 | b = 5.2 172 | z = bj # returns a NameError 173 | 174 | 175 | # In[19]: 176 | 177 | z = b*j # returns a NameError 178 | 179 | 180 | # In[20]: 181 | 182 | z = b*1j # is correct 183 | z 184 | 185 | 186 | # In[21]: 187 | 188 | z = 3.2 + 5.2j 189 | z.conjugate() # returns (3.2-5.2j) 190 | 191 | 192 | # #### Real and Imaginary Parts 193 | 194 | # In[22]: 195 | 196 | z = 1j 197 | z.real # 0.0 198 | z.imag # 1.0 199 | z.imag = 2 # AttributeError: readonly attribute 200 | 201 | 202 | # In[23]: 203 | 204 | z = 1 + 0j 205 | z == 1 # True 206 | float(z) # TypeError 207 | 208 | 209 | # In[24]: 210 | 211 | import matplotlib.pyplot as plt 212 | N = 10 213 | # the following vector contains the Nth roots of unity: 214 | unity_roots = array([exp(1j*2*pi*k/N) for k in range(N)]) 215 | # access all the real or imaginary parts with real or imag: 216 | axes(aspect='equal') 217 | plot(unity_roots.real, unity_roots.imag, 'o') 218 | allclose(unity_roots**N, 1) # True 219 | 220 | 221 | # In[25]: 222 | 223 | z = 3.2+5.2j 224 | (z + z.conjugate()) / 2. # returns (3.2+0j) 225 | ((z + z.conjugate()) / 2.).real # returns 3.2 226 | (z - z.conjugate()) / 2. # returns 5.2j 227 | ((z - z.conjugate()) / 2.).imag # returns 5.2 228 | sqrt(z * z.conjugate()) # returns (6.1057350089894991+0j) 229 | 230 | 231 | # ## Booleans 232 | 233 | # In[26]: 234 | 235 | a = True 236 | a 237 | b = 30>45 # b gets the value False 238 | b 239 | 240 | 241 | # In[27]: 242 | 243 | x=3 244 | if x>0: 245 | print("positive") 246 | else: 247 | print("nonpositive") 248 | 249 | 250 | # ### Boolean Operators 251 | 252 | # In[28]: 253 | 254 | True and False # False 255 | False or True # True 256 | (30 > 45) or (27 < 30) # True 257 | not True # False 258 | not (3 > 4) # True 259 | 260 | 261 | # In[29]: 262 | 263 | a=3; b=4; c=-1 264 | 265 | a < b < c # same as: a < b and b < c 266 | 267 | a == b == c # same as: a == b and b == c 268 | 269 | 270 | # ### Boolean Casting 271 | 272 | # In[30]: 273 | 274 | bool([]) # False 275 | bool(0) # False 276 | bool(' ') # True 277 | bool('') # False 278 | bool('hello') # True 279 | bool(1.2) # True 280 | bool(array([1])) # True 281 | bool(array([1,2])) # Exception raised! 282 | 283 | 284 | # #### Automatic Boolean Casting 285 | 286 | # In[31]: 287 | 288 | if a: 289 | print('Im here') 290 | if bool(a): # exactly the same as above 291 | print('Im there') 292 | 293 | 294 | # In[32]: 295 | 296 | L=[] 297 | if L: 298 | print("list not empty") 299 | else: 300 | print("list is empty") 301 | 302 | 303 | # In[33]: 304 | 305 | n=23 306 | if n % 2: 307 | print("n is odd") 308 | else: 309 | print("n is even") 310 | 311 | 312 | # #### Return values of and and or 313 | 314 | # In[34]: 315 | 316 | def and_as_function(x,y): 317 | if not x: 318 | return x 319 | else: 320 | return y 321 | 322 | and_as_function(True,False) 323 | 324 | 325 | # In[35]: 326 | 327 | def or_as_function(x,y): 328 | if x: 329 | return x 330 | else: 331 | return y 332 | 333 | or_as_function(True,False) 334 | 335 | 336 | # In[36]: 337 | 338 | True or x_not_defined 339 | False and x_not_defined 340 | 341 | 342 | # In[37]: 343 | 344 | [1] or 'a' # produces [1] 345 | 'a' or [1] # produces 'a' 346 | 347 | 348 | # ### Booleans and Integers 349 | 350 | # In[38]: 351 | 352 | def print_ispositive(x): 353 | possibilities=['nonpositive', 'positive'] 354 | return "x is {}".format(possibilities[x>0]) 355 | 356 | print_ispositive(-23) 357 | print_ispositive(7) 358 | 359 | 360 | # In[39]: 361 | 362 | True+13 363 | 2*True+5 364 | 365 | 366 | # ## Strings 367 | 368 | # In[40]: 369 | 370 | name = 'Johan Carlsson' 371 | child = "Åsa is Johan Carlsson's daughter" 372 | book = """Aunt Julia 373 | and the Scriptwriter""" 374 | 375 | print(name) 376 | print(child) 377 | print(book) 378 | 379 | 380 | # In[41]: 381 | 382 | book[-1] # returns 'r' 383 | 384 | book[-12:] # returns 'Scriptwriter' 385 | 386 | 387 | # In[42]: 388 | 389 | book[1]='a' # returns TypeError 390 | 391 | 392 | # In[43]: 393 | 394 | print('Temperature:\t20\tC\nPressure:\t5\tPa') 395 | 396 | 397 | # In[44]: 398 | 399 | a=""" 400 | A multiline 401 | example""" 402 | a # returns '\nA multiline\nexample' 403 | 404 | 405 | # In[45]: 406 | 407 | latexfontsize="\\tiny" 408 | print(latexfontsize) 409 | 410 | 411 | # In[46]: 412 | 413 | latexfs=r"\tiny" 414 | latexfs # returns "\\tiny" 415 | latexfontsize == latexfs # returns True 416 | 417 | 418 | # In[47]: 419 | 420 | r"\"" # returns '\\"' 421 | r"\\" # returns '\\\\' 422 | 423 | 424 | # In[48]: 425 | 426 | r"\" # returns an error 427 | 428 | 429 | # ### Operations on strings and string methods 430 | 431 | # In[49]: 432 | 433 | last_name='Carlsson' 434 | first_name='Johanna' 435 | Full_name=first_name+' '+last_name # returns 'Johanna Carlsson' 436 | 437 | Full_name 438 | 439 | 440 | # In[50]: 441 | 442 | game=2*'Yo' # returns 'YoYo' 443 | game 444 | 445 | 446 | # In[51]: 447 | 448 | 'Anna' > 'Arvid' # returns false 449 | 450 | 'ANNA' < 'anna' # returns true 451 | 452 | '10B' < '11A' # returns true 453 | 454 | 455 | # In[52]: 456 | 457 | text = 'quod erat demonstrandum' 458 | text.split() # returns ['quod', 'erat', 'demonstrandum'] 459 | table = 'Johan;Carlsson;19890327' 460 | table.split(';') # returns ['Johan','Carlsson','19890327'] 461 | king = 'CarlXVIGustaf' 462 | king.split('XVI') # returns ['Carl','Gustaf'] 463 | 464 | 465 | # In[53]: 466 | 467 | sep=';' 468 | sep.join(['Johan','Carlsson','19890327']) # returns 'Johan;Carlsson;19890327' 469 | 470 | 471 | # In[54]: 472 | 473 | birthday='20101210' 474 | birthday.find('10') # returns 2 475 | 476 | 477 | # ### String Formatting 478 | 479 | # In[55]: 480 | 481 | course_code = "NUMA21" 482 | print("This course's name is {}".format(course_code)) # This course's name is NUMA21 483 | 484 | 485 | # In[56]: 486 | 487 | quantity = 33.45 488 | print("qty{:f}".format(quantity)) # qty33.450000 489 | print("qty{:8.1f}".format(quantity)) # qty 33.5 490 | print("qty{:10.2e}".format(quantity)) # qty 3.35e+01 491 | 492 | 493 | # In[57]: 494 | 495 | print("{name} {value:.1f}".format(name="quantity",value=quantity)) # "quantity 33.5" 496 | 497 | 498 | # In[58]: 499 | 500 | r"we {} in LaTeX \begin{{equation}}".format('like') 501 | 502 | -------------------------------------------------------------------------------- /3-Container/3-Container+Types.py: -------------------------------------------------------------------------------- 1 | 2 | # coding: utf-8 3 | 4 | # # 3-Container Types 5 | 6 | # In[1]: 7 | 8 | from scipy import * 9 | from matplotlib.pyplot import * 10 | get_ipython().magic('matplotlib inline') 11 | from IPython.core.interactiveshell import InteractiveShell 12 | InteractiveShell.ast_node_interactivity = "all" 13 | 14 | 15 | # ## Lists 16 | 17 | # In[2]: 18 | 19 | L = ['a', 20.0, 5] 20 | M = [3,['a', -3.0, 5]] 21 | L 22 | M 23 | 24 | L[1] # returns 20.0 25 | 26 | L[0] # returns 'a' 27 | 28 | M[1] # returns ['a',-3.0,5] 29 | 30 | M[1][2] # returns 5 31 | 32 | 33 | # In[3]: 34 | 35 | L=list(range(4)) # generates a list with four elements: [0, 1, 2 ,3] 36 | L 37 | 38 | 39 | # In[4]: 40 | 41 | L=list(range(17,29,4)) # generates [17, 21, 25] 42 | L 43 | 44 | len(L) # returns 3 45 | 46 | 47 | # ### Slicing 48 | 49 | # In[5]: 50 | 51 | L = ['C', 'l', 'o', 'u', 'd','s'] 52 | L[1:5] # remove one element and take three from there 53 | 54 | L = ['C', 'l', 'o', 'u','d', 's'] 55 | L[1:] # ['l', 'o', 'u', 'd','s'] 56 | 57 | L[:5] # ['C', 'l', 'o','u','d'] 58 | 59 | 60 | L[-2:] # ['d', 's'] 61 | 62 | 63 | # In[6]: 64 | 65 | L = list(range(4)) # [0, 1, 2, 3] 66 | L[4] # IndexError: list index out of range 67 | 68 | 69 | # In[7]: 70 | 71 | L[1:100] # same as L[1:] 72 | 73 | 74 | # In[8]: 75 | 76 | L[-100:-1] # same as L[:-1] 77 | 78 | 79 | # In[9]: 80 | 81 | L[-100:100] # same as L[:] 82 | 83 | 84 | # In[10]: 85 | 86 | L[5:0] # empty list [] 87 | 88 | 89 | # In[11]: 90 | 91 | L[-2:2] # empty list [] 92 | 93 | 94 | # In[12]: 95 | 96 | L[1:100] 97 | 98 | 99 | # In[13]: 100 | 101 | a = [1,2,3] 102 | for iteration in range(4): 103 | print(sum(a[0:iteration-1])) 104 | 105 | 106 | # ### Strides 107 | 108 | # In[14]: 109 | 110 | L = list(range(100)) 111 | L[:10:2] # [0, 2, 4, 6, 8] 112 | 113 | 114 | # In[15]: 115 | 116 | L[::20] # [0, 20, 40, 60, 80] 117 | 118 | 119 | # In[16]: 120 | 121 | L[10:20:3] # [10, 13, 16, 19] 122 | 123 | 124 | # In[17]: 125 | 126 | L = [1, 2, 3] 127 | R = L[::-1] # L is not modified 128 | print(R) 129 | 130 | 131 | # ### Altering Lists 132 | 133 | # In[18]: 134 | 135 | L = ['a', 1, 2, 3, 4] 136 | L[2:3] = [] # ['a', 1, 3, 4] 137 | L 138 | 139 | 140 | # In[19]: 141 | 142 | L[3:] = [] # ['a', 1, 3] 143 | L 144 | 145 | 146 | # In[20]: 147 | 148 | L[1:1] = [1000, 2000] # ['a', 1000, 2000, 1, 3] 149 | L 150 | 151 | 152 | # In[21]: 153 | 154 | L = [1, -17] 155 | M = [-23.5, 18.3, 5.0] 156 | L+M # gives [1, -17, 23.5, 18.3, 5.0] 157 | 158 | 159 | # In[22]: 160 | 161 | n = 3 162 | n*[1.,17,3] # gives [1., 17, 3, 1., 17, 3, 1., 17, 3] 163 | 164 | 165 | # In[23]: 166 | 167 | [0]*5 # gives [0,0,0,0,0] 168 | 169 | 170 | # ### Belonging to a list 171 | 172 | # In[24]: 173 | 174 | L = ['a', 1, 'b', 2] 175 | 'a' in L # True 176 | 177 | 178 | # In[25]: 179 | 180 | 3 in L # False 181 | 182 | 183 | # In[26]: 184 | 185 | 4 not in L # True 186 | 187 | 188 | # ### List Methods 189 | 190 | # In[27]: 191 | 192 | L = [1, 2, 3] 193 | L.reverse() # the list L is now reversed 194 | L # [3, 2, 1] 195 | 196 | 197 | # In[28]: 198 | 199 | L=[3, 4, 4, 5] 200 | newL = L.sort() 201 | print(newL) 202 | 203 | 204 | # In[29]: 205 | 206 | L = [0,1,2,3,4] 207 | L.append(5) 208 | L 209 | 210 | 211 | # In[30]: 212 | 213 | L.reverse() 214 | L 215 | 216 | 217 | # In[31]: 218 | 219 | L.sort() 220 | L 221 | 222 | 223 | # In[32]: 224 | 225 | L.remove(0) # [1, 2, 3, 4, 5] 226 | L 227 | 228 | 229 | # In[33]: 230 | 231 | L.pop() # [1, 2, 3, 4] 232 | L 233 | 234 | 235 | # In[34]: 236 | 237 | L.pop() # [1, 2, 3, 4] 238 | L 239 | 240 | 241 | # In[35]: 242 | 243 | L.extend(['a','b','c']) # [1, 2, 3, 'a', 'b', 'c'] 244 | L 245 | 246 | 247 | # In[36]: 248 | 249 | L.count(2) 250 | 251 | 252 | # ### Merging Lists - `zip` 253 | 254 | # In[37]: 255 | 256 | ind = [0,1,2,3,4] 257 | color = ["red", "green", "blue", "alpha"] 258 | list(zip(color,ind)) 259 | 260 | 261 | # ### List Comprehension 262 | 263 | # In[38]: 264 | 265 | L = [2, 3, 10, 1, 5] 266 | 267 | L2 = [x*2 for x in L] # [4, 6, 20, 2, 10] 268 | L2 269 | 270 | 271 | # In[39]: 272 | 273 | L3 = [x*2 for x in L if 4 < x <= 10] # [20, 10] 274 | L3 275 | 276 | 277 | # In[40]: 278 | 279 | M=[[1,2,3],[4,5,6]] 280 | flat = [M[i][j] for i in range(2) for j in range(3)] # [1, 2, 3, 4, 5, 6] 281 | flat 282 | 283 | 284 | # ## Arrays 285 | 286 | # In[41]: 287 | 288 | v = array([1.,2.,3.]) 289 | v 290 | 291 | 292 | # In[42]: 293 | 294 | A = array([[1.,2.,3.],[4.,5.,6.]]) 295 | A 296 | 297 | 298 | # In[43]: 299 | 300 | v[2] # returns 3.0 301 | 302 | 303 | # In[44]: 304 | 305 | A[1,2] # returns 6.0 306 | 307 | 308 | # In[45]: 309 | 310 | M = array([[1.,2.],[3.,4.]]) 311 | v = array([1., 2., 3.]) 312 | v[0] # 1. 313 | 314 | 315 | # In[46]: 316 | 317 | v[:2] # array([1.,2.]) 318 | 319 | 320 | # In[47]: 321 | 322 | M[0,1] # 2. 323 | 324 | 325 | # In[48]: 326 | 327 | v[:2] = [10, 20] # v is now array([10., 20., 3.]) 328 | 329 | 330 | # ## Tuples 331 | 332 | # In[49]: 333 | 334 | my_tuple = 1, 2, 3 # our first tuple 335 | 336 | 337 | # In[50]: 338 | 339 | my_tuple = (1, 2, 3) # the same 340 | 341 | 342 | # In[51]: 343 | 344 | my_tuple = 1, 2, 3, # again the same 345 | 346 | 347 | # In[52]: 348 | 349 | len(my_tuple) # 3, same as for lists 350 | 351 | 352 | # In[53]: 353 | 354 | my_tuple[0] = 'a' # error! tuples are immutable 355 | 356 | 357 | # In[54]: 358 | 359 | singleton = 1, # note the comma 360 | len(singleton) # 1 361 | 362 | 363 | # In[55]: 364 | 365 | a, b = 0, 1 # a gets 0 and b gets 1 366 | print(a) 367 | print(b) 368 | 369 | 370 | # In[56]: 371 | 372 | a, b = [0, 1] # exactly the same effect 373 | 374 | 375 | # In[57]: 376 | 377 | (a, b) = 0, 1 # same 378 | 379 | 380 | # In[58]: 381 | 382 | [a,b] = [0,1] # same thing 383 | 384 | 385 | # In[59]: 386 | 387 | a, b = b, a 388 | print(a) 389 | print(b) 390 | 391 | 392 | # In[60]: 393 | 394 | 1, 2 == 3, 4 395 | 396 | 397 | # In[61]: 398 | 399 | (1, 2) == (3, 4) 400 | 401 | 402 | # ## Dictionaries 403 | # 404 | # ### Creating and Altering Dictionaries 405 | 406 | # In[62]: 407 | 408 | truck_wheel = {'name':'wheel','mass':5.7, 409 | 'Ix':20.0,'Iy':1.,'Iz':17., 410 | 'center of mass':[0.,0.,0.]} 411 | 412 | 413 | # In[63]: 414 | 415 | truck_wheel['name'] 416 | 417 | 418 | # In[64]: 419 | 420 | truck_wheel['mass'] 421 | 422 | 423 | # In[65]: 424 | 425 | truck_wheel['Ixy'] = 0.0 426 | 427 | 428 | # In[66]: 429 | 430 | truck_wheel = dict([('name','wheel'),('mass',5.7), 431 | ('Ix',20.0),('Iy',1.),('Iz',17.),('center of mass',[0.,0.,0.])]) 432 | truck_wheel 433 | 434 | 435 | # ### Looping over Dictionaries 436 | 437 | # In[67]: 438 | 439 | for key in truck_wheel.keys(): 440 | print(key) 441 | 442 | 443 | # In[68]: 444 | 445 | for key in truck_wheel: 446 | print(key) 447 | 448 | 449 | # In[69]: 450 | 451 | for value in truck_wheel.values(): 452 | print(value) 453 | 454 | 455 | # In[70]: 456 | 457 | for item in truck_wheel.items(): 458 | print(item) 459 | 460 | 461 | # ## Sets 462 | 463 | # In[71]: 464 | 465 | A = {1,2,3,4} 466 | B = {5} 467 | 468 | 469 | # In[72]: 470 | 471 | C = A.union(B) # returns set([1,2,3,4,5]) 472 | C 473 | 474 | 475 | # In[73]: 476 | 477 | D = A.intersection(C) # returns set([1,2,3,4]) 478 | D 479 | 480 | 481 | # In[74]: 482 | 483 | E = C.difference(A) # returns set([5]) 484 | E 485 | 486 | 487 | # In[75]: 488 | 489 | 5 in C # returns True 490 | 491 | 492 | # In[76]: 493 | 494 | A = {1,2,3,3,3} 495 | B = {1,2,3} 496 | A == B # returns True 497 | 498 | 499 | # In[77]: 500 | 501 | A = {1,2,3} 502 | B = {1,3,2} 503 | A == B # returns True 504 | 505 | 506 | # In[78]: 507 | 508 | A={1,2,3,4} 509 | A.union({5}) 510 | 511 | 512 | # In[79]: 513 | 514 | A.intersection({2,4,6}) # returns set([2, 4]) 515 | 516 | 517 | # In[80]: 518 | 519 | {2,4}.issubset({1,2,3,4,5}) # returns True 520 | 521 | 522 | # In[81]: 523 | 524 | {1,2,3,4,5}.issuperset({2,4}) # returns True 525 | 526 | 527 | # In[82]: 528 | 529 | empty_set=set([]) 530 | 531 | 532 | # ## Type checking 533 | 534 | # In[83]: 535 | 536 | label = 'local error' 537 | type(label) # returns str 538 | 539 | 540 | # In[84]: 541 | 542 | x = [1, 2] # list 543 | type(x) # returns list 544 | 545 | 546 | # In[85]: 547 | 548 | isinstance(x, list) # True 549 | 550 | 551 | # In[86]: 552 | 553 | test = True 554 | isinstance(test, bool) # True 555 | 556 | 557 | # In[87]: 558 | 559 | isinstance(test, int) # True 560 | 561 | 562 | # In[88]: 563 | 564 | type(test) == int # False 565 | 566 | 567 | # In[89]: 568 | 569 | type(test) == bool # True 570 | 571 | 572 | # In[90]: 573 | 574 | if isinstance(test, int): 575 | print("The variable is an integer") 576 | 577 | -------------------------------------------------------------------------------- /4-LinearAlgebra/4-LinearAlgebra.py: -------------------------------------------------------------------------------- 1 | 2 | # coding: utf-8 3 | 4 | # # 4-Linear Algebra 5 | 6 | # In[1]: 7 | 8 | from scipy import * 9 | from scipy.linalg import * 10 | from matplotlib.pyplot import * 11 | get_ipython().magic('matplotlib inline') 12 | 13 | 14 | # ## Overview 15 | # 16 | # ### Vectors and Matrices 17 | 18 | # In[2]: 19 | 20 | v = array([1.,2.,3.]) 21 | 22 | 23 | # In[3]: 24 | 25 | # two vectors with three components 26 | v1 = array([1., 2., 3.]) 27 | v2 = array([2, 0, 1.]) 28 | 29 | 30 | # In[4]: 31 | 32 | 2*v1 # array([2., 4., 6.]) 33 | 34 | 35 | # In[5]: 36 | 37 | v1/2 # array([0.5, 1., 1.5]) 38 | 39 | 40 | # In[6]: 41 | 42 | # linear combinations 43 | 3*v1 # array([ 3., 6., 9.]) 44 | 45 | 46 | # In[7]: 47 | 48 | 3*v1 + 2*v2 # array([ 7., 6., 11.]) 49 | 50 | 51 | # In[8]: 52 | 53 | # norm 54 | norm(v1) # 3.7416573867739413 55 | 56 | 57 | # In[9]: 58 | 59 | # scalar product 60 | dot(v1, v2) # 5. 61 | 62 | 63 | # In[10]: 64 | 65 | v1 @ v2 # 5 ; alternative formulation 66 | 67 | 68 | # In[11]: 69 | 70 | # elementwise operations: 71 | v1 * v2 # array([2., 0., 3.]) 72 | 73 | 74 | # In[12]: 75 | 76 | v2 / v1 # array([2.,0.,.333333]) 77 | 78 | 79 | # In[13]: 80 | 81 | v1 - v2 # array([-1., 2., 2.]) 82 | 83 | 84 | # In[14]: 85 | 86 | v1 + v2 # array([ 3., 2., 4.]) 87 | 88 | 89 | # In[15]: 90 | 91 | cos(v1) # cosine, elementwise: array([ 0.5403, -0.4161, -0.9899]) 92 | 93 | 94 | # In[16]: 95 | 96 | M = array([[1.,2],[0.,1]]) 97 | 98 | 99 | # ### Indexing and Slices 100 | 101 | # In[17]: 102 | 103 | v = array([1.,2.,3]) 104 | M = array([[1.,2],[3.,4]]) 105 | 106 | v[0] # works as for lists 107 | 108 | 109 | # In[18]: 110 | 111 | v[1:] # array([2.,3.]) 112 | 113 | 114 | # In[19]: 115 | 116 | M[0,0] # 1. 117 | 118 | 119 | # In[20]: 120 | 121 | M[1:] # returns the matrix array([[3.,4]]) 122 | 123 | 124 | # In[21]: 125 | 126 | M[1] # returns the vector array([3.,4.]) 127 | 128 | 129 | # In[22]: 130 | 131 | # access 132 | v[0] # 1. 133 | 134 | 135 | # In[23]: 136 | 137 | v[0] = 10 138 | 139 | 140 | # In[24]: 141 | 142 | # slices 143 | v[:2] # array([10., 2.]) 144 | 145 | 146 | # In[25]: 147 | 148 | v[:2] = [0, 1] # now v == array([0.,1.,3.]) 149 | v 150 | 151 | 152 | # In[26]: 153 | 154 | v[:2] = [1,2,3] # error! 155 | 156 | 157 | # ### Linear Algebra Operations 158 | 159 | # In[27]: 160 | 161 | v = array([1.,2.]) 162 | M = array([[1.,2],[3.,4]]) 163 | dot(M,v) # matrix vector multiplication; returns a vector 164 | 165 | 166 | # In[28]: 167 | 168 | M @ v # alternative formulation 169 | 170 | 171 | # In[29]: 172 | 173 | w = array([7.,0.]) 174 | dot(v,w) # scalar product; the result is a scalar 175 | 176 | 177 | # In[30]: 178 | 179 | v @ w # alternative formulation 180 | 181 | 182 | # In[31]: 183 | 184 | N = array([[3., 8.],[0., 1.]]) 185 | dot(M,N) # results in a matrix 186 | 187 | 188 | # In[32]: 189 | 190 | M @ N # alternative formulation 191 | 192 | 193 | # #### Solving a Linear System 194 | 195 | # In[33]: 196 | 197 | import scipy.linalg as sl 198 | A = array([[1., 2.], 199 | [3., 4.]]) 200 | b = array([1., 4.]) 201 | x = sl.solve(A,b) 202 | 203 | 204 | # In[34]: 205 | 206 | allclose(dot(A, x), b) # True 207 | 208 | 209 | # In[35]: 210 | 211 | allclose(A @ x, b) # alternative formulation 212 | 213 | 214 | # ## Mathematical Preliminaries 215 | # ### The dot operations 216 | 217 | # In[36]: 218 | 219 | angle = pi/3 220 | M = array([[cos(angle), -sin(angle)], 221 | [sin(angle), cos(angle)]]) 222 | v = array([1., 0.]) 223 | y = dot(M, v) 224 | y 225 | 226 | 227 | # ## The Array Type 228 | # ### Array Properties 229 | 230 | # In[37]: 231 | 232 | A=array([[1,2,3],[3,4,6]]) 233 | A.shape # (2, 3) 234 | 235 | 236 | # In[38]: 237 | 238 | A.dtype # dtype('int64') 239 | 240 | 241 | # In[39]: 242 | 243 | A.strides # (24, 8) 244 | 245 | 246 | # ### Creating Arrays from Lists 247 | 248 | # In[40]: 249 | 250 | V = array([1., 2., 1.], dtype=float) 251 | V 252 | 253 | 254 | # In[41]: 255 | 256 | V = array([1., 2., 1.], dtype=complex) 257 | V 258 | 259 | 260 | # In[42]: 261 | 262 | V = array([1, 2]) # [1, 2] is a list of integers 263 | V.dtype # int 264 | 265 | 266 | # In[43]: 267 | 268 | V = array([1., 2]) # [1., 2] mix float/integer 269 | V.dtype # float 270 | 271 | 272 | # In[44]: 273 | 274 | V = array([1. + 0j, 2.]) # mix float/complex 275 | V.dtype # complex 276 | 277 | 278 | # In[45]: 279 | 280 | a = array([1, 2, 3]) 281 | a[0] = 0.5 282 | a # now: array([0, 2, 3]) 283 | 284 | 285 | # In[46]: 286 | 287 | # the identity matrix in 2D 288 | Id = array([[1., 0.], [0., 1.]]) 289 | # Python allows this: 290 | Id = array([[1., 0.], 291 | [0., 1.]]) 292 | # which is more readable 293 | 294 | 295 | # ### Vectors and Matrices 296 | 297 | # In[47]: 298 | 299 | v = array([1., 2., 1.]) 300 | shape(v) 301 | 302 | 303 | # In[48]: 304 | 305 | R = array([[1.,2.,1.]]) # notice the double brackets: this is a matrix 306 | shape(R) # (1,3): this is a row matrix 307 | 308 | 309 | # In[49]: 310 | 311 | C = array([1.,2.,1.]).reshape(3,1) 312 | shape(C) # (3,1): this is a column matrix 313 | 314 | 315 | # ## Array Indexing 316 | # ### Accessing Array Entries 317 | 318 | # In[50]: 319 | 320 | M = array([[1., 2.],[3.,4.]]) 321 | M[0,0] # first row, first column: 1. 322 | 323 | 324 | # In[51]: 325 | 326 | M[-1,0] # last row, first column: 3. 327 | 328 | 329 | # In[52]: 330 | 331 | v = array([1., 2., 3.]) 332 | v1 = v[:2] # v1 is array([1.,2.]) 333 | v1 334 | 335 | 336 | # In[53]: 337 | 338 | v1[0] = 0. # if v1 is changed ... 339 | v1 340 | 341 | 342 | # In[54]: 343 | 344 | v # ... v is changed too: array([0., 2., 3.]) 345 | 346 | 347 | # ### Altering an array using slices 348 | 349 | # In[55]: 350 | 351 | M = array([[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15]]) 352 | shape(M) 353 | 354 | 355 | # In[56]: 356 | 357 | M[1,2] = 2.0 # scalar 358 | M 359 | 360 | 361 | # In[57]: 362 | 363 | M[2,:] = [1.,2.,3.] # vector 364 | M 365 | 366 | 367 | # In[58]: 368 | 369 | M[1:3,:] = array([[1.,2.,3.],[-1.,-2.,-3.]]) # matrix 370 | M 371 | 372 | 373 | # In[59]: 374 | 375 | M[1:4,2:3] = array([[1.],[0.],[-1.0]]) # column matrix 376 | M 377 | 378 | 379 | # ## Functions to Construct Arrays 380 | 381 | # In[60]: 382 | 383 | identity(3) 384 | 385 | 386 | # ## Accessing and Changing the Shape 387 | 388 | # In[61]: 389 | 390 | M = identity(3) 391 | shape(M) # (3, 3) 392 | 393 | 394 | # In[62]: 395 | 396 | v = array([1., 2., 1., 4.]) 397 | shape(v) # (4,) <- singleton (1-tuple) 398 | 399 | 400 | # In[63]: 401 | 402 | M = array([[1.,2.]]) 403 | shape(M) # (1,2) 404 | 405 | 406 | # In[64]: 407 | 408 | M.shape # (1,2) 409 | 410 | 411 | # In[65]: 412 | 413 | shape(1.) # () 414 | 415 | 416 | # In[66]: 417 | 418 | shape([1,2]) # (2,) 419 | 420 | 421 | # In[67]: 422 | 423 | shape([[1,2]]) # (1,2) 424 | 425 | 426 | # ### Number of Dimensions 427 | 428 | # In[68]: 429 | 430 | A=rand(2,3) 431 | ndim(A) # 2 432 | 433 | 434 | # In[69]: 435 | 436 | A.ndim 437 | 438 | 439 | # In[70]: 440 | 441 | T = zeros((2,2,3)) # tensor of shape (2,2,3); three dimensions 442 | ndim(T) # 3 443 | 444 | 445 | # In[71]: 446 | 447 | len(shape(T)) # 3 448 | 449 | 450 | # ### Reshape 451 | 452 | # In[72]: 453 | 454 | v = array([0,1,2,3,4,5]) 455 | M = v.reshape(2,3) 456 | M 457 | 458 | 459 | # In[73]: 460 | 461 | shape(M) # returns (2,3) 462 | 463 | 464 | # In[74]: 465 | 466 | M[0,0] = 10 # now v[0] is 10 467 | v 468 | 469 | 470 | # In[75]: 471 | 472 | v = array([1,2,3,4,5,6,7,8]) 473 | M = v.reshape(2,-1) 474 | shape(M) # returns (2,4) 475 | 476 | 477 | # In[76]: 478 | 479 | M = v.reshape(-1,2) 480 | shape(M) # returns (4,2) 481 | 482 | 483 | # In[77]: 484 | 485 | M = v.reshape(3,-1) # returns error 486 | 487 | 488 | # ### Transpose 489 | 490 | # In[78]: 491 | 492 | A = rand(3,4) 493 | shape(A) # 3,4 494 | 495 | 496 | # In[79]: 497 | 498 | B = A.T # A transpose 499 | shape(B) # 4,3 500 | 501 | 502 | # In[80]: 503 | 504 | v = array([1.,2.,3.]) 505 | v.T # exactly the same vector! 506 | 507 | 508 | # In[81]: 509 | 510 | v.reshape(-1,1) # column matrix containing v 511 | 512 | 513 | # In[82]: 514 | 515 | v.reshape(1,-1) # row matrix containing v 516 | 517 | 518 | # # Stacking 519 | # 520 | # ### Stacking vectors 521 | 522 | # In[83]: 523 | 524 | # v is supposed to have an even length. 525 | def symp(v): 526 | n = len(v) // 2 # use the integer division // 527 | return hstack([v[-n:], -v[:n]]) 528 | v = arange(1,5) 529 | symp(v) 530 | 531 | 532 | # # Functions Acting on Arrays 533 | # 534 | # ## Universal Functions 535 | # 536 | # ### Built-in Universal Functions 537 | 538 | # In[84]: 539 | 540 | cos(pi) # -1 541 | 542 | 543 | # In[85]: 544 | 545 | cos(array([[0, pi/2, pi]])) # array([[1, 0, -1]]) 546 | 547 | 548 | # In[86]: 549 | 550 | 2 * array([2, 4]) # array([4, 8]) 551 | array([1, 2]) * array([1, 8]) # array([1, 16]) 552 | 553 | 554 | # In[87]: 555 | 556 | array([1, 2])**2 # array([1, 4]) 557 | 558 | 559 | # In[88]: 560 | 561 | 2**array([1, 2]) # array([1, 4]) 562 | 563 | 564 | # In[89]: 565 | 566 | array([1, 2])**array([1, 2]) # array([1, 4]) 567 | 568 | 569 | # #### Create Universal Functions: `vectorize` 570 | 571 | # In[90]: 572 | 573 | def const(x): 574 | return 1 575 | const(array([0, 2])) # returns 1 instead of array([1, 1]) 576 | 577 | 578 | # In[91]: 579 | 580 | def heaviside(x): 581 | if x >= 0: 582 | return 1. 583 | else: 584 | return 0. 585 | heaviside(array([-1, 2])) # error 586 | 587 | 588 | # In[92]: 589 | 590 | vheaviside = vectorize(heaviside) 591 | vheaviside(array([-1,2])) # array([0,1]) as expected 592 | 593 | 594 | # In[93]: 595 | 596 | xvals=linspace(-1,1,100) 597 | plot(xvals,vectorize(heaviside)(xvals)) 598 | axis([-1.5,1.5,-0.5,1.5]) 599 | 600 | 601 | # ### Array Functions: `axis` Argument 602 | 603 | # In[94]: 604 | 605 | A = arange(1,9).reshape((2,-1)) 606 | A 607 | 608 | 609 | # In[95]: 610 | 611 | sum(A) # 36 612 | 613 | 614 | # In[96]: 615 | 616 | sum(A, axis=0) # array([ 6, 8, 10, 12]) 617 | 618 | 619 | # In[97]: 620 | 621 | A.sum(axis=1) # array([10, 26]) 622 | 623 | 624 | # ## Linear Algebra Methods in SciPy 625 | 626 | # In[98]: 627 | 628 | import scipy.linalg as sl 629 | A = array([[1,2], [-6,4]]) 630 | [LU,piv] = sl.lu_factor(A) 631 | 632 | 633 | # In[99]: 634 | 635 | bi = array([1,1]) 636 | xi=sl.lu_solve((LU,piv),bi) 637 | xi 638 | 639 | 640 | # ### Solving a least squares problem with SVD 641 | 642 | # In[100]: 643 | 644 | import scipy.linalg as sl 645 | A = array([[1, 2], [-6, 4], [0, 8]]) 646 | b = array([1,1,1]) 647 | [U1, Sigma_1, VT] = sl.svd(A, full_matrices = False, compute_uv = True) 648 | xast = dot(VT.T, dot(U1.T, b)/ Sigma_1) 649 | r = dot(A, xast) - b # computes the residual 650 | nr = sl.norm(r, 2) # computes the Euclidean norm of the residual 651 | nr 652 | 653 | -------------------------------------------------------------------------------- /5-AdvancedArrayConcepts/5-AdvancedArrayConcepts.py: -------------------------------------------------------------------------------- 1 | 2 | # coding: utf-8 3 | 4 | # # 5-Advanced Array Concepts 5 | 6 | # In[1]: 7 | 8 | from scipy import * 9 | from IPython.core.interactiveshell import InteractiveShell 10 | InteractiveShell.ast_node_interactivity = "all" # toggle to: 'last_expr' or 'all' 11 | 12 | 13 | # ## Array Views and Copies 14 | 15 | # In[2]: 16 | 17 | M = array([[1.,2.],[3.,4.]]) 18 | v = M[0,:] # first row of M 19 | M 20 | v 21 | 22 | 23 | # In[3]: 24 | 25 | v[-1] = 0. 26 | v # array([[1.,0.]]) 27 | M # array([[1.,0.],[3.,4.]]) # M is modified as well 28 | 29 | 30 | # In[4]: 31 | 32 | v.base # array([[1.,0.],[3.,4.]]) 33 | 34 | v.base is M # True 35 | M.base is None 36 | 37 | 38 | # ### Slices as Views 39 | 40 | # In[5]: 41 | 42 | a = arange(4) # array([0.,1.,2.,3.]) 43 | b = a[[2,3]] # the index is a list [2,3] 44 | b # array([2.,3.]) 45 | 46 | 47 | # In[6]: 48 | 49 | print(b.base is None) # True, the data was copied 50 | c = a[1:3] 51 | c.base is None # False, this is just a view 52 | 53 | 54 | # In[7]: 55 | 56 | N = M[:] # this is a view of the whole array M 57 | print(N.base is M) 58 | 59 | 60 | # ### Transpose and Reshape as Views 61 | 62 | # In[8]: 63 | 64 | M = random.random_sample((3,3)) 65 | N = M.T 66 | N.base is M # True 67 | 68 | 69 | # In[9]: 70 | 71 | v = arange(10) 72 | C = v.reshape(-1,1) # column matrix 73 | C.base is v # True 74 | 75 | 76 | # ### Array Copy 77 | 78 | # In[10]: 79 | 80 | M = array([[1.,2.],[3.,4.]]) 81 | N = array(M.T) # copy of M.T 82 | N.base is None 83 | 84 | 85 | # ## Comparing Arrays 86 | 87 | # In[11]: 88 | 89 | A = array([0.,0.]) 90 | B = array([0.,0.]) 91 | if abs(B-A) < 1e-10: # an exception is raised here 92 | print("The two arrays are close enough") 93 | 94 | 95 | # ### Boolean Arrays 96 | 97 | # In[12]: 98 | 99 | A = array([True,False]) # Boolean array 100 | A.dtype # dtype('bool') 101 | 102 | 103 | # In[13]: 104 | 105 | M = array([[2, 3], 106 | [1, 4]]) 107 | M > 2 # array([[False, True], 108 | # [False, True]]) 109 | 110 | 111 | # In[14]: 112 | 113 | M == 0 # array([[False, False], 114 | # [False, False]]) 115 | 116 | 117 | # In[15]: 118 | 119 | N = array([[2, 3], 120 | [0, 0]]) 121 | M == N # array([[True, True], 122 | # [False, False]]) 123 | 124 | 125 | # In[16]: 126 | 127 | A = array([[1,2],[3,4]]) 128 | B = array([[1,2],[3,3]]) 129 | A == B # creates array([[True, True], [True, False]]) 130 | (A == B).all() # False 131 | (A != B).any() # True 132 | if (abs(B-A) < 1e-10).all(): 133 | print("The two arrays are close enough") 134 | 135 | 136 | # In[17]: 137 | 138 | (A == B).all() # False 139 | 140 | 141 | # In[18]: 142 | 143 | (A != B).any() # True 144 | 145 | 146 | # In[19]: 147 | 148 | if (abs(B-A) < 1e-10).all(): 149 | print("The two arrays are close enough") 150 | 151 | 152 | # #### Checking for equality 153 | 154 | # In[20]: 155 | 156 | data = random.rand(2)*1e-3 157 | small_error = random.rand(2)*1e-16 158 | data == data + small_error # False 159 | allclose(data, data + small_error, rtol=1.e-5, atol=1.e-8) # True 160 | 161 | 162 | # In[21]: 163 | 164 | atol=1.e-6 165 | rtol=1.e-4 166 | (abs(A-B) < atol+rtol*abs(B)).all() 167 | 168 | 169 | # In[22]: 170 | 171 | data = 1e-3 172 | error = 1e-16 173 | data == data + error # False 174 | allclose(data, data + error, rtol=1.e-5, atol=1.e-8) #True 175 | 176 | 177 | # ### Boolean Operations on arrays 178 | 179 | # In[23]: 180 | 181 | A = array([True, True, False, False]) 182 | B = array([True, False, True, False]) 183 | A and B # error! 184 | 185 | 186 | # In[24]: 187 | 188 | A & B # array([True, False, False, False]) 189 | 190 | A | B # array([True, True, True, False]) 191 | 192 | ~A # array([False, False, True, True]) 193 | 194 | 195 | # In[25]: 196 | 197 | data = linspace(1,100,100) # data 198 | deviation = random.normal(size=100) # the deviations 199 | #don't forget the parentheses in next statement! 200 | exceptional = data[(deviation<-0.5)|(deviation>0.5)] 201 | exceptional = data[abs(deviation)>0.5] # same result 202 | small = data[(abs(deviation)<0.1)& (data <5.)] # small deviation and data #don't forget the parentheses! 203 | exceptional 204 | small 205 | 206 | 207 | # ## Array Indexing 208 | # ### Indexing with Boolean Arrays 209 | 210 | # In[26]: 211 | 212 | B = array([[True, False], 213 | [False, True]]) 214 | M = array([[2, 3], 215 | [1, 4]]) 216 | M[B] # array([2,4]), a vector 217 | 218 | 219 | # In[27]: 220 | 221 | M[B] = 0 222 | M # [[0, 3], [1, 0]] 223 | 224 | 225 | # In[28]: 226 | 227 | M[B] = 10, 20 228 | M # [[10, 3], [1, 20]] 229 | 230 | 231 | # In[29]: 232 | 233 | M[M>2] = 0 234 | M 235 | 236 | 237 | # ### Using `where` 238 | 239 | # In[30]: 240 | 241 | def H(x): 242 | return where(x < 0, 0, 1) 243 | x = linspace(-1,1,11) # [-1. -0.8 -0.6 -0.4 -0.2 0. 0.2 0.4 0.6 0.8 1. ] 244 | print(H(x)) # [0 0 0 0 0 1 1 1 1 1 1] 245 | 246 | 247 | # In[31]: 248 | 249 | x = linspace(-4,4,5) # [-4. -2. 0. 2. 4.] 250 | print(where(x > 0, sqrt(x), 0)) # [ 0.+0.j 0.+0.j 0.+0.j 1.41421356+0.j 2.+0.j ] 251 | print(where(x > 0, 1, -1)) # [-1 -1 -1 1 1] 252 | 253 | 254 | # In[32]: 255 | 256 | a = arange(9) 257 | b = a.reshape((3,3)) 258 | b 259 | 260 | 261 | # In[33]: 262 | 263 | print(where(a > 5)) # (array([6, 7, 8]),) 264 | 265 | 266 | # In[34]: 267 | 268 | print(where(b > 5)) # (array([2, 2, 2]), array([0, 1, 2])) 269 | 270 | 271 | # ## Performance and Vectorization 272 | # 273 | # ### What is slow in Python? 274 | 275 | # In[35]: 276 | 277 | def my_prod(a,b): 278 | val = 0 279 | for aa,bb in zip(a,b): 280 | val += aa*bb 281 | return val 282 | 283 | 284 | # In[36]: 285 | 286 | a=arange(3) 287 | my_prod(a,-a) 288 | 289 | 290 | # In[37]: 291 | 292 | v = arange(1000) 293 | w = empty_like(v) 294 | for i in range(len(v)): 295 | w[i] = v[i] + 5 296 | 297 | 298 | # In[38]: 299 | 300 | w = v + 5 301 | 302 | 303 | # In[39]: 304 | 305 | def my_avg(A): 306 | m,n = A.shape 307 | B = A.copy() 308 | for i in range(1,m-1): 309 | for j in range(1,n-1): 310 | B[i,j] = (A[i-1,j] + A[i+1,j] + A[i,j-1] + A[i,j+1])/4 311 | return B 312 | 313 | 314 | # In[40]: 315 | 316 | def slicing_avg(A): 317 | A[1:-1,1:-1] = (A[:-2,1:-1] + A[2:,1:-1] + A[1:-1,:-2] + A[1:-1,2:])/4 318 | return A 319 | 320 | 321 | # In[41]: 322 | 323 | A = arange(20).reshape(4,-1) 324 | allclose(my_avg(A), slicing_avg(A)) 325 | 326 | 327 | # In[42]: 328 | 329 | def my_func(x): 330 | y = x**3 - 2*x + 5 331 | if y>0.5: 332 | return y-0.5 333 | else: 334 | return 0 335 | 336 | 337 | # In[43]: 338 | 339 | v=arange(10,dtype=float64) 340 | for i in range(len(v)): 341 | v[i] = my_func(v[i]) 342 | v 343 | 344 | 345 | # In[44]: 346 | 347 | my_vecfunc = vectorize(my_func) 348 | 349 | 350 | # In[45]: 351 | 352 | v=arange(10,dtype=float64) 353 | v = my_vecfunc(v) 354 | v 355 | 356 | 357 | # ## Broadcasting 358 | 359 | # In[46]: 360 | 361 | vector = arange(4) # array([0.,1.,2.,3.]) 362 | vector + 1. # array([1.,2.,3.,4.]) 363 | 364 | 365 | # In[47]: 366 | 367 | C = arange(2).reshape(-1,1) # column 368 | R = arange(2).reshape(1,-1) # row 369 | C + R # valid addition: array([[0.,1.],[1.,2.]]) 370 | 371 | 372 | # In[48]: 373 | 374 | M = array([[11, 12, 13, 14], 375 | [21, 22, 23, 24], 376 | [31, 32, 33, 34]]) 377 | v = array([100, 200, 300, 400]) 378 | M + v 379 | 380 | 381 | # #### Shape missmatch 382 | 383 | # In[49]: 384 | 385 | M = array([[11, 12, 13, 14], 386 | [21, 22, 23, 24], 387 | [31, 32, 33, 34]]) 388 | v = array([100, 200, 300]) 389 | M + v # returns an error 390 | 391 | 392 | # In[50]: 393 | 394 | M + v.reshape(-1,1) 395 | 396 | 397 | # #### Rescale Rows 398 | 399 | # In[51]: 400 | 401 | coeff = array([1,10,100]) 402 | rescaled = M*coeff.reshape(-1,1) 403 | rescaled 404 | 405 | 406 | # #### Rescale columns 407 | 408 | # In[52]: 409 | 410 | coeff = array([1,10,100,10000]) 411 | rescaled = M*coeff 412 | rescaled 413 | 414 | 415 | # In[53]: 416 | 417 | rescaled = M*coeff.reshape(1,-1) 418 | rescaled 419 | 420 | 421 | # #### Functions of two variables 422 | 423 | # In[54]: 424 | 425 | u=arange(2) 426 | v=arange(3) 427 | W=u.reshape(-1,1)+v 428 | W 429 | 430 | 431 | # In[55]: 432 | 433 | x=linspace(0,2*pi,5) 434 | y=linspace(0,pi,3) 435 | w=cos(x).reshape(-1,1)+sin(2*y) 436 | w 437 | 438 | 439 | # In[56]: 440 | 441 | x,y = ogrid[0:1:3j,0:1:3j] # x,y are vectors with the contents of linspace(0,1,3) 442 | w = cos(x) + sin(2*y) 443 | w 444 | 445 | 446 | # In[57]: 447 | 448 | x,y = ogrid[0:1:3j, 0:1:3j] 449 | print(x) 450 | print(y) 451 | 452 | 453 | # In[58]: 454 | 455 | x,y = ogrid.__getitem__((slice(0, 1, 3j),slice(0, 1, 3j))) 456 | print(x) 457 | print(y) 458 | 459 | 460 | # In[59]: 461 | 462 | x,y = ogrid[0:1.5:.5, 0:1.5:.5] 463 | print(x) 464 | print(y) 465 | 466 | 467 | # ## Sparse Matrices 468 | # ### Compressed Sparse Row (CSR) 469 | 470 | # In[60]: 471 | 472 | import scipy.sparse as sp 473 | A=array([[1,0,2,0],[0,0,0,0],[3.,0.,0.,0.],[1.,0.,0.,4.]]) 474 | AS=sp.csr_matrix(A) 475 | AS.data # returns array([ 1., 2., 3., 1., 4.]) 476 | 477 | 478 | # In[61]: 479 | 480 | AS.indptr # returns array([0, 2, 2, 3, 5]) 481 | 482 | 483 | # In[62]: 484 | 485 | AS.indices # returns array([0, 2, 0, 0, 3]) 486 | 487 | 488 | # In[63]: 489 | 490 | AS.nnz # returns 5 491 | 492 | 493 | # ### Compressed Sparse Column (CSC) 494 | 495 | # In[64]: 496 | 497 | import scipy.sparse as sp 498 | A=array([[1,0,2,0],[0,0,0,0],[3.,0.,0.,0.],[1.,0.,0.,4.]]) 499 | AS=sp.csc_matrix(A) 500 | AS.data # returns array([ 1., 3., 1., 2., 4.]) 501 | 502 | 503 | # In[65]: 504 | 505 | AS.indptr # returns array([0, 3, 3, 4, 5]) 506 | 507 | 508 | # In[66]: 509 | 510 | AS.indices # returns array([0, 2, 3, 0, 3]) 511 | 512 | 513 | # In[67]: 514 | 515 | AS.nnz # returns 5 516 | 517 | 518 | # ### Row--Based Linked List Format (LIL) 519 | 520 | # In[68]: 521 | 522 | import scipy.sparse as sp 523 | A=array([[1,0,2,0],[0,0,0,0],[3.,0.,0.,0.],[1.,0.,0.,4.]]) 524 | AS=sp.lil_matrix(A) 525 | AS.data # returns array([[1.0, 2.0], [], [3.0], [1.0, 4.0]], dtype=object) 526 | 527 | 528 | # In[69]: 529 | 530 | AS.rows # returns array([[0, 2], [], [0], [0, 3]], dtype=object) 531 | 532 | 533 | # In[70]: 534 | 535 | AS.nnz # returns 5 536 | 537 | 538 | # #### Altering and Slicing matrices in LIL format 539 | 540 | # In[71]: 541 | 542 | BS=AS[1:3,0:2] 543 | BS.data # returns array([[], [3.0]], dtype=object) 544 | 545 | 546 | # In[72]: 547 | 548 | BS.rows # returns array([[], [0]], dtype=object) 549 | 550 | 551 | # In[73]: 552 | 553 | AS[0,1]=17 554 | AS.data # returns array([[1.0, 17.0, 2.0], [], [3.0], [1.0, 4.0]], dtype=object) 555 | 556 | 557 | # In[74]: 558 | 559 | AS.rows # returns array([[0, 1, 2], [], [0], [0, 3]], dtype=object) 560 | 561 | 562 | # In[75]: 563 | 564 | AS.nnz # returns 6 565 | 566 | 567 | # ### Generating Sparse Matrices 568 | 569 | # In[76]: 570 | 571 | import scipy.sparse as sp 572 | sp.eye(20,20,format='lil') 573 | 574 | 575 | # In[77]: 576 | 577 | sp.spdiags(ones((20,)),0,20,20,format='csr') 578 | 579 | 580 | # In[78]: 581 | 582 | sp.identity(20,format='csc') 583 | 584 | 585 | # In[79]: 586 | 587 | AS=sp.rand(20,200,density=0.1,format='csr') 588 | AS.nnz # returns 400 589 | 590 | 591 | # In[80]: 592 | 593 | import scipy.sparse as sp 594 | Z=sp.csr_matrix((20,200)) 595 | Z.nnz 596 | 597 | 598 | # ### Sparse Matrix Methods 599 | 600 | # In[81]: 601 | 602 | AS.toarray() # converts sparse formats to a numpy array 603 | 604 | 605 | # In[82]: 606 | 607 | AS.tocsr() 608 | 609 | 610 | # In[83]: 611 | 612 | AS.tocsc() 613 | 614 | 615 | # In[84]: 616 | 617 | AS.tolil() 618 | 619 | 620 | # In[85]: 621 | 622 | import scipy.sparse as sp 623 | def sparse_sin(A): 624 | if not (sp.isspmatrix_csr(A) or sp.isspmatrix_csc(A)): 625 | A=A.tocsr() 626 | A.data=sin(A.data) 627 | return A 628 | sparse_sin(AS) 629 | 630 | 631 | # In[86]: 632 | 633 | import scipy.sparse as sp 634 | A=array([[1,0,2,0],[0,0,0,0],[3.,0.,0.,0.],[1.,0.,0.,4.]]) 635 | AS=sp.csr_matrix(A) 636 | b=array([1,2,3,4]) 637 | c=AS.dot(b) # returns array([ 7., 0., 3., 17.]) 638 | c 639 | 640 | 641 | # In[87]: 642 | 643 | C=AS.dot(AS) # returns $4 \times 4$ csr_matrix 644 | C 645 | 646 | 647 | # In[88]: 648 | 649 | d=dot(AS,b) # does not return the expected result! 650 | 651 | -------------------------------------------------------------------------------- /6-plotting/amp_mod_sin0.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Scientific-Computing-with-Python-3/1333ac3fe4f90cb9f157682bf2d3a80824528032/6-plotting/amp_mod_sin0.pdf -------------------------------------------------------------------------------- /6-plotting/amp_mod_sin1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Scientific-Computing-with-Python-3/1333ac3fe4f90cb9f157682bf2d3a80824528032/6-plotting/amp_mod_sin1.pdf -------------------------------------------------------------------------------- /6-plotting/amp_mod_sin2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Scientific-Computing-with-Python-3/1333ac3fe4f90cb9f157682bf2d3a80824528032/6-plotting/amp_mod_sin2.pdf -------------------------------------------------------------------------------- /6-plotting/amp_mod_sin2a.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Scientific-Computing-with-Python-3/1333ac3fe4f90cb9f157682bf2d3a80824528032/6-plotting/amp_mod_sin2a.png -------------------------------------------------------------------------------- /6-plotting/amp_mod_sin3.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Scientific-Computing-with-Python-3/1333ac3fe4f90cb9f157682bf2d3a80824528032/6-plotting/amp_mod_sin3.pdf -------------------------------------------------------------------------------- /6-plotting/amp_mod_sin4.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Scientific-Computing-with-Python-3/1333ac3fe4f90cb9f157682bf2d3a80824528032/6-plotting/amp_mod_sin4.pdf -------------------------------------------------------------------------------- /6-plotting/circle_evolution.swf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Scientific-Computing-with-Python-3/1333ac3fe4f90cb9f157682bf2d3a80824528032/6-plotting/circle_evolution.swf -------------------------------------------------------------------------------- /6-plotting/figobjects.py: -------------------------------------------------------------------------------- 1 | from matplotlib.pyplot import * 2 | from scipy import * 3 | 4 | 5 | fig=figure(1) 6 | ax=subplot(111) 7 | x=linspace(0,2*pi,1000) 8 | ax.plot(x,sin(x),label='sin') 9 | amod_sin=lambda x: (1.-0.1*sin(25*x))*sin(x) 10 | ax.plot(x,amod_sin(x),label='modsin') 11 | 12 | savefig('amp_mod_sin0.pdf',transparent=True,bbox_inches='tight') 13 | 14 | for il,line in enumerate(ax.lines): 15 | if line.get_label() == 'sin': 16 | break 17 | ax.lines[il].set_linestyle('-.') 18 | ax.lines[il].set_linewidth(2) 19 | 20 | 21 | ydata=ax.lines[il].get_ydata() 22 | ydata[-1]=-0.5 23 | ax.lines[il].set_ydata(ydata) 24 | 25 | 26 | savefig('amp_mod_sin1.pdf',transparent=True,bbox_inches='tight') 27 | 28 | annot1=ax.annotate('amplitude modulated\n curve', (2.1,1.0),(3.8,0.5), 29 | arrowprops={'width':2,'color':'k', 'connectionstyle':'arc3,rad=+0.5', 'shrink':0.05}, 30 | verticalalignment='bottom', horizontalalignment='left',fontsize=15, 31 | bbox={'facecolor':'gray', 'alpha':0.1, 'pad':10}) 32 | annot2=ax.annotate('corrupted data', (6.3,-0.5),(6.1,-1.1),arrowprops={'width':0.5,'color':'k','shrink':0.1}, 33 | horizontalalignment='center', fontsize=12) 34 | 35 | 36 | axf=ax.fill_between(x, sin(x), amod_sin(x),facecolor='gray') 37 | 38 | savefig('amp_mod_sin2.pdf',transparent=True, bbox_inches='tight') 39 | 40 | axf.remove() 41 | 42 | axf=ax.fill_between(x, sin(x), amod_sin(x), where= amod_sin(x)-sin(x) > 0,facecolor='gray') 43 | 44 | savefig('amp_mod_sin3.pdf',transparent=True, bbox_inches='tight') 45 | 46 | ax.set_xticks(array([0,pi/2,pi,3/2*pi,2*pi])) 47 | ax.set_xticklabels(('$0$','$\pi/2$','$\pi$','$3/2 \pi$','$2 \pi$'),fontsize=18) 48 | ax.set_yticks(array([-1.,0.,1])) 49 | ax.set_yticklabels(('$-1$','$0$','$1$'),fontsize=18) 50 | 51 | savefig('amp_mod_sin4.pdf',transparent=True,bbox_inches='tight') 52 | -------------------------------------------------------------------------------- /6-plotting/mandelbrod.py: -------------------------------------------------------------------------------- 1 | from matplotlib.pyplot import * 2 | from scipy import * 3 | 4 | def mandelbrot(h,w, maxit=20): 5 | X,Y = meshgrid(linspace(-2, 0.8, w), linspace(-1.4, 1.4, h)) 6 | c = X + Y*1j 7 | z = c 8 | exceeds = zeros(z.shape, dtype=bool) 9 | 10 | for iteration in range(maxit): 11 | z = z**2 + c 12 | exceeded = abs(z) > 4 13 | exceeds_now = exceeded & (logical_not(exceeds)) 14 | exceeds[exceeds_now] = True 15 | z[exceeded] = 2 # limit the values to avoid overflow 16 | return exceeds 17 | fig1=figure(1) 18 | ax=subplot(111) 19 | ax.imshow(mandelbrot(400,400),cmap='gray') 20 | ax.axis('off') 21 | fig1.savefig('plotting_mandelbrot_gray.pdf',bbox_inches='tight',transparent=True) 22 | fig2=figure(2) 23 | ax1=subplot(121) 24 | ax2=subplot(122) 25 | ax1.imshow(mandelbrot(40,40),cmap='gray') 26 | ax1.axis('off') 27 | ax2.imshow(mandelbrot(40,40), interpolation='nearest', cmap='gray') 28 | ax2.axis('off') 29 | fig2.savefig('plotting_mandelbrot_small.pdf',bbox_inches='tight',transparent=True) 30 | -------------------------------------------------------------------------------- /6-plotting/sin03.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Scientific-Computing-with-Python-3/1333ac3fe4f90cb9f157682bf2d3a80824528032/6-plotting/sin03.png -------------------------------------------------------------------------------- /6-plotting/test.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Scientific-Computing-with-Python-3/1333ac3fe4f90cb9f157682bf2d3a80824528032/6-plotting/test.pdf -------------------------------------------------------------------------------- /6-plotting/test.svg: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 10 | 11 | 12 | 13 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /7-Functions/.ipynb_checkpoints/7-Functions-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 7 - Functions" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": { 14 | "collapsed": true 15 | }, 16 | "outputs": [], 17 | "source": [ 18 | "from scipy import *\n", 19 | "from matplotlib.pyplot import *\n", 20 | "%matplotlib inline" 21 | ] 22 | }, 23 | { 24 | "cell_type": "markdown", 25 | "metadata": {}, 26 | "source": [ 27 | "## Basics" 28 | ] 29 | }, 30 | { 31 | "cell_type": "code", 32 | "execution_count": null, 33 | "metadata": { 34 | "collapsed": true 35 | }, 36 | "outputs": [], 37 | "source": [ 38 | "def subtract(x1, x2):\n", 39 | " return x1 - x2" 40 | ] 41 | }, 42 | { 43 | "cell_type": "code", 44 | "execution_count": null, 45 | "metadata": { 46 | "collapsed": false 47 | }, 48 | "outputs": [], 49 | "source": [ 50 | "r = subtract(5.0, 4.3)\n", 51 | "r" 52 | ] 53 | }, 54 | { 55 | "cell_type": "markdown", 56 | "metadata": {}, 57 | "source": [ 58 | "## Parameters and Arguments" 59 | ] 60 | }, 61 | { 62 | "cell_type": "code", 63 | "execution_count": null, 64 | "metadata": { 65 | "collapsed": false 66 | }, 67 | "outputs": [], 68 | "source": [ 69 | "z = 3\n", 70 | "e = subtract(5,z)\n", 71 | "e" 72 | ] 73 | }, 74 | { 75 | "cell_type": "code", 76 | "execution_count": null, 77 | "metadata": { 78 | "collapsed": false 79 | }, 80 | "outputs": [], 81 | "source": [ 82 | "z = 3\n", 83 | "e = subtract(x2 = z, x1 = 5)\n", 84 | "e" 85 | ] 86 | }, 87 | { 88 | "cell_type": "markdown", 89 | "metadata": {}, 90 | "source": [ 91 | "### Changing Arguments" 92 | ] 93 | }, 94 | { 95 | "cell_type": "code", 96 | "execution_count": null, 97 | "metadata": { 98 | "collapsed": false 99 | }, 100 | "outputs": [], 101 | "source": [ 102 | "def subtract(x1, x2):\n", 103 | " z = x1 - x2\n", 104 | " x2 = 50.\n", 105 | " return z\n", 106 | "a = 20.\n", 107 | "b = subtract(10, a) # returns -10.\n", 108 | "b" 109 | ] 110 | }, 111 | { 112 | "cell_type": "code", 113 | "execution_count": null, 114 | "metadata": { 115 | "collapsed": false 116 | }, 117 | "outputs": [], 118 | "source": [ 119 | "a # still has the value 20" 120 | ] 121 | }, 122 | { 123 | "cell_type": "code", 124 | "execution_count": null, 125 | "metadata": { 126 | "collapsed": false 127 | }, 128 | "outputs": [], 129 | "source": [ 130 | "def subtract(x):\n", 131 | " z = x[0] - x[1]\n", 132 | " x[1] = 50.\n", 133 | " return z\n", 134 | "a = [10,20]\n", 135 | "b = subtract(a) # returns -10\n", 136 | "b" 137 | ] 138 | }, 139 | { 140 | "cell_type": "code", 141 | "execution_count": null, 142 | "metadata": { 143 | "collapsed": false 144 | }, 145 | "outputs": [], 146 | "source": [ 147 | "a # is now [10, 50.0]\t" 148 | ] 149 | }, 150 | { 151 | "cell_type": "markdown", 152 | "metadata": {}, 153 | "source": [ 154 | "### Access to variables defined outside the local namespace" 155 | ] 156 | }, 157 | { 158 | "cell_type": "code", 159 | "execution_count": null, 160 | "metadata": { 161 | "collapsed": true 162 | }, 163 | "outputs": [], 164 | "source": [ 165 | "import numpy as np # here the variable np is defined\n", 166 | "def sqrt(x):\n", 167 | " return np.sqrt(x) # we use np inside the function" 168 | ] 169 | }, 170 | { 171 | "cell_type": "code", 172 | "execution_count": null, 173 | "metadata": { 174 | "collapsed": false 175 | }, 176 | "outputs": [], 177 | "source": [ 178 | "a = 3\n", 179 | "def multiply(x):\n", 180 | " return a * x # bad style: access to the variable a defined outside\n", 181 | "\n", 182 | "multiply(4) # returns 12" 183 | ] 184 | }, 185 | { 186 | "cell_type": "code", 187 | "execution_count": null, 188 | "metadata": { 189 | "collapsed": false 190 | }, 191 | "outputs": [], 192 | "source": [ 193 | "a=4\n", 194 | "multiply(4) # returns 16" 195 | ] 196 | }, 197 | { 198 | "cell_type": "code", 199 | "execution_count": null, 200 | "metadata": { 201 | "collapsed": true 202 | }, 203 | "outputs": [], 204 | "source": [ 205 | "def multiply(x, a):\n", 206 | " return a * x" 207 | ] 208 | }, 209 | { 210 | "cell_type": "markdown", 211 | "metadata": {}, 212 | "source": [ 213 | "### Default Arguments" 214 | ] 215 | }, 216 | { 217 | "cell_type": "code", 218 | "execution_count": null, 219 | "metadata": { 220 | "collapsed": false 221 | }, 222 | "outputs": [], 223 | "source": [ 224 | "import scipy.linalg as sl\n", 225 | "sl.norm(identity(3))" 226 | ] 227 | }, 228 | { 229 | "cell_type": "code", 230 | "execution_count": null, 231 | "metadata": { 232 | "collapsed": false 233 | }, 234 | "outputs": [], 235 | "source": [ 236 | "sl.norm(identity(3), ord = 'fro')" 237 | ] 238 | }, 239 | { 240 | "cell_type": "code", 241 | "execution_count": null, 242 | "metadata": { 243 | "collapsed": false 244 | }, 245 | "outputs": [], 246 | "source": [ 247 | "sl.norm(identity(3), 'fro')" 248 | ] 249 | }, 250 | { 251 | "cell_type": "code", 252 | "execution_count": null, 253 | "metadata": { 254 | "collapsed": false 255 | }, 256 | "outputs": [], 257 | "source": [ 258 | "def subtract(x1, x2 = 0):\n", 259 | " return x1 - x2\n", 260 | "\n", 261 | "subtract(5)" 262 | ] 263 | }, 264 | { 265 | "cell_type": "code", 266 | "execution_count": null, 267 | "metadata": { 268 | "collapsed": false 269 | }, 270 | "outputs": [], 271 | "source": [ 272 | "def my_list(x1, x2 = []):\n", 273 | " x2.append(x1)\n", 274 | " return x2\n", 275 | "my_list(1) # returns [1]" 276 | ] 277 | }, 278 | { 279 | "cell_type": "code", 280 | "execution_count": null, 281 | "metadata": { 282 | "collapsed": false 283 | }, 284 | "outputs": [], 285 | "source": [ 286 | "my_list(2) # returns [1,2]" 287 | ] 288 | }, 289 | { 290 | "cell_type": "markdown", 291 | "metadata": {}, 292 | "source": [ 293 | "### Variable Number of Arguments" 294 | ] 295 | }, 296 | { 297 | "cell_type": "code", 298 | "execution_count": null, 299 | "metadata": { 300 | "collapsed": true 301 | }, 302 | "outputs": [], 303 | "source": [ 304 | "data = [[1,2],[3,4]]\n", 305 | "style = dict({'linewidth':3,'marker':'o','color':'green'})" 306 | ] 307 | }, 308 | { 309 | "cell_type": "code", 310 | "execution_count": null, 311 | "metadata": { 312 | "collapsed": false 313 | }, 314 | "outputs": [], 315 | "source": [ 316 | "plot(*data, **style)" 317 | ] 318 | }, 319 | { 320 | "cell_type": "markdown", 321 | "metadata": {}, 322 | "source": [ 323 | "## Return Values" 324 | ] 325 | }, 326 | { 327 | "cell_type": "code", 328 | "execution_count": null, 329 | "metadata": { 330 | "collapsed": true 331 | }, 332 | "outputs": [], 333 | "source": [ 334 | "def complex_to_polar(z):\n", 335 | " r = sqrt(z.real ** 2 + z.imag ** 2)\n", 336 | " phi = arctan2(z.imag, z.real)\n", 337 | " return (r,phi) # here the return object is formed" 338 | ] 339 | }, 340 | { 341 | "cell_type": "code", 342 | "execution_count": null, 343 | "metadata": { 344 | "collapsed": false 345 | }, 346 | "outputs": [], 347 | "source": [ 348 | "z = 3 + 5j # here we define a complex number\n", 349 | "a = complex_to_polar(z)\n", 350 | "a" 351 | ] 352 | }, 353 | { 354 | "cell_type": "code", 355 | "execution_count": null, 356 | "metadata": { 357 | "collapsed": false 358 | }, 359 | "outputs": [], 360 | "source": [ 361 | "r = a[0]\n", 362 | "r" 363 | ] 364 | }, 365 | { 366 | "cell_type": "code", 367 | "execution_count": null, 368 | "metadata": { 369 | "collapsed": false 370 | }, 371 | "outputs": [], 372 | "source": [ 373 | "phi = a[1]\n", 374 | "phi" 375 | ] 376 | }, 377 | { 378 | "cell_type": "code", 379 | "execution_count": null, 380 | "metadata": { 381 | "collapsed": false 382 | }, 383 | "outputs": [], 384 | "source": [ 385 | "r,phi = complex_to_polar(z)\n", 386 | "r,phi" 387 | ] 388 | }, 389 | { 390 | "cell_type": "code", 391 | "execution_count": null, 392 | "metadata": { 393 | "collapsed": true 394 | }, 395 | "outputs": [], 396 | "source": [ 397 | "def append_to_list(L, x):\n", 398 | " L.append(x)" 399 | ] 400 | }, 401 | { 402 | "cell_type": "code", 403 | "execution_count": null, 404 | "metadata": { 405 | "collapsed": true 406 | }, 407 | "outputs": [], 408 | "source": [ 409 | "def function_with_dead_code(x):\n", 410 | " return 2 * x\n", 411 | " y = x ** 2 # these two lines ...\n", 412 | " return y # ... are never executed!" 413 | ] 414 | }, 415 | { 416 | "cell_type": "markdown", 417 | "metadata": {}, 418 | "source": [ 419 | "## Recursive functions" 420 | ] 421 | }, 422 | { 423 | "cell_type": "code", 424 | "execution_count": null, 425 | "metadata": { 426 | "collapsed": false 427 | }, 428 | "outputs": [], 429 | "source": [ 430 | "def chebyshev(n, x):\n", 431 | " if n == 0:\n", 432 | " return 1.\n", 433 | " elif n == 1:\n", 434 | " return x\n", 435 | " else:\n", 436 | " return 2. * x * chebyshev(n - 1, x) \\\n", 437 | " - chebyshev(n - 2 ,x)\n", 438 | "\n", 439 | "chebyshev(5, 0.52) # returns 0.39616645119999994" 440 | ] 441 | }, 442 | { 443 | "cell_type": "markdown", 444 | "metadata": {}, 445 | "source": [ 446 | "## Function Documentation" 447 | ] 448 | }, 449 | { 450 | "cell_type": "code", 451 | "execution_count": null, 452 | "metadata": { 453 | "collapsed": true 454 | }, 455 | "outputs": [], 456 | "source": [ 457 | "def newton(f, x0):\n", 458 | " \"\"\"\n", 459 | " Newton's method for computing a zero of a function\n", 460 | " on input:\n", 461 | " f (function) given function f(x)\n", 462 | " x0 (float) initial guess \n", 463 | " on return:\n", 464 | " y (float) the approximated zero of f\n", 465 | " \"\"\"\n", 466 | " ..." 467 | ] 468 | }, 469 | { 470 | "cell_type": "code", 471 | "execution_count": null, 472 | "metadata": { 473 | "collapsed": false 474 | }, 475 | "outputs": [], 476 | "source": [ 477 | "help(newton)" 478 | ] 479 | }, 480 | { 481 | "cell_type": "markdown", 482 | "metadata": {}, 483 | "source": [ 484 | "## Functions are Objects" 485 | ] 486 | }, 487 | { 488 | "cell_type": "code", 489 | "execution_count": null, 490 | "metadata": { 491 | "collapsed": false 492 | }, 493 | "outputs": [], 494 | "source": [ 495 | "def square(x):\n", 496 | " \"\"\"Return the square of `x`\"\"\"\n", 497 | " return x ** 2\n", 498 | "square(4) # 16\n", 499 | "sq = square # now sq is the same as square\n", 500 | "sq(4) # 16\n", 501 | "print(newton(sq, .2)) # passing as argument\n", 502 | "del sq" 503 | ] 504 | }, 505 | { 506 | "cell_type": "markdown", 507 | "metadata": {}, 508 | "source": [ 509 | "### Partial Application" 510 | ] 511 | }, 512 | { 513 | "cell_type": "code", 514 | "execution_count": null, 515 | "metadata": { 516 | "collapsed": false 517 | }, 518 | "outputs": [], 519 | "source": [ 520 | "import functools\n", 521 | "def sin_omega(t, freq):\n", 522 | " return sin(2 * pi * freq * t)\n", 523 | "\n", 524 | "def make_sine(frequency):\n", 525 | " return functools.partial(sin_omega, freq = frequency)\n", 526 | "\n", 527 | "sin1=make_sine(1)\n", 528 | "sin1(2)" 529 | ] 530 | }, 531 | { 532 | "cell_type": "code", 533 | "execution_count": null, 534 | "metadata": { 535 | "collapsed": false 536 | }, 537 | "outputs": [], 538 | "source": [ 539 | "def make_sine(freq):\n", 540 | " \"Make a sine function with frequency freq\"\n", 541 | " def mysine(t):\n", 542 | " return sin_omega(t, freq)\n", 543 | " return mysine\n", 544 | "sin1=make_sine(1)\n", 545 | "sin1(2)" 546 | ] 547 | }, 548 | { 549 | "cell_type": "markdown", 550 | "metadata": {}, 551 | "source": [ 552 | "## Anonymous Functions - the `lambda` keyword" 553 | ] 554 | }, 555 | { 556 | "cell_type": "code", 557 | "execution_count": null, 558 | "metadata": { 559 | "collapsed": false 560 | }, 561 | "outputs": [], 562 | "source": [ 563 | "import scipy.integrate as si\n", 564 | "si.quad(lambda x: x ** 2 + 5, 0, 1) " 565 | ] 566 | }, 567 | { 568 | "cell_type": "code", 569 | "execution_count": null, 570 | "metadata": { 571 | "collapsed": false 572 | }, 573 | "outputs": [], 574 | "source": [ 575 | "parabola = lambda x: x ** 2 + 5 \n", 576 | "parabola(3) # gives 14" 577 | ] 578 | }, 579 | { 580 | "cell_type": "code", 581 | "execution_count": null, 582 | "metadata": { 583 | "collapsed": false 584 | }, 585 | "outputs": [], 586 | "source": [ 587 | "def parabola(x):\n", 588 | " return x ** 2 + 5\n", 589 | "parabola(3)" 590 | ] 591 | }, 592 | { 593 | "cell_type": "code", 594 | "execution_count": null, 595 | "metadata": { 596 | "collapsed": false 597 | }, 598 | "outputs": [], 599 | "source": [ 600 | "import scipy.integrate as si\n", 601 | "for iteration in range(3):\n", 602 | " print(si.quad(lambda x: sin_omega(x, iteration * pi), 0, pi / 2.) )" 603 | ] 604 | }, 605 | { 606 | "cell_type": "markdown", 607 | "metadata": {}, 608 | "source": [ 609 | "## Functions as Decorators" 610 | ] 611 | }, 612 | { 613 | "cell_type": "code", 614 | "execution_count": null, 615 | "metadata": { 616 | "collapsed": true 617 | }, 618 | "outputs": [], 619 | "source": [ 620 | "def how_sparse(A):\n", 621 | " return len(A.reshape(-1).nonzero()[0])" 622 | ] 623 | }, 624 | { 625 | "cell_type": "code", 626 | "execution_count": null, 627 | "metadata": { 628 | "collapsed": false 629 | }, 630 | "outputs": [], 631 | "source": [ 632 | "how_sparse([1,2,0]) # returns an error" 633 | ] 634 | }, 635 | { 636 | "cell_type": "code", 637 | "execution_count": null, 638 | "metadata": { 639 | "collapsed": true 640 | }, 641 | "outputs": [], 642 | "source": [ 643 | "def cast2array(f):\n", 644 | " def new_function(obj):\n", 645 | " fA = f(array(obj))\n", 646 | " return fA\n", 647 | " return new_function" 648 | ] 649 | }, 650 | { 651 | "cell_type": "code", 652 | "execution_count": null, 653 | "metadata": { 654 | "collapsed": true 655 | }, 656 | "outputs": [], 657 | "source": [ 658 | "@cast2array\n", 659 | "def how_sparse(A):\n", 660 | " return len(A.reshape(-1).nonzero()[0]) " 661 | ] 662 | }, 663 | { 664 | "cell_type": "code", 665 | "execution_count": null, 666 | "metadata": { 667 | "collapsed": false 668 | }, 669 | "outputs": [], 670 | "source": [ 671 | "how_sparse([1,2,0]) # returns no error any more" 672 | ] 673 | } 674 | ], 675 | "metadata": { 676 | "anaconda-cloud": {}, 677 | "kernelspec": { 678 | "display_name": "Python [conda root]", 679 | "language": "python", 680 | "name": "conda-root-py" 681 | }, 682 | "language_info": { 683 | "codemirror_mode": { 684 | "name": "ipython", 685 | "version": 3 686 | }, 687 | "file_extension": ".py", 688 | "mimetype": "text/x-python", 689 | "name": "python", 690 | "nbconvert_exporter": "python", 691 | "pygments_lexer": "ipython3", 692 | "version": "3.5.2" 693 | } 694 | }, 695 | "nbformat": 4, 696 | "nbformat_minor": 0 697 | } 698 | -------------------------------------------------------------------------------- /7-Functions/7-Functions.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 7 - Functions" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": { 14 | "collapsed": true 15 | }, 16 | "outputs": [], 17 | "source": [ 18 | "from scipy import *\n", 19 | "from matplotlib.pyplot import *\n", 20 | "%matplotlib inline" 21 | ] 22 | }, 23 | { 24 | "cell_type": "markdown", 25 | "metadata": {}, 26 | "source": [ 27 | "## Basics" 28 | ] 29 | }, 30 | { 31 | "cell_type": "code", 32 | "execution_count": null, 33 | "metadata": { 34 | "collapsed": true 35 | }, 36 | "outputs": [], 37 | "source": [ 38 | "def subtract(x1, x2):\n", 39 | " return x1 - x2" 40 | ] 41 | }, 42 | { 43 | "cell_type": "code", 44 | "execution_count": null, 45 | "metadata": { 46 | "collapsed": false 47 | }, 48 | "outputs": [], 49 | "source": [ 50 | "r = subtract(5.0, 4.3)\n", 51 | "r" 52 | ] 53 | }, 54 | { 55 | "cell_type": "markdown", 56 | "metadata": {}, 57 | "source": [ 58 | "## Parameters and Arguments" 59 | ] 60 | }, 61 | { 62 | "cell_type": "code", 63 | "execution_count": null, 64 | "metadata": { 65 | "collapsed": false 66 | }, 67 | "outputs": [], 68 | "source": [ 69 | "z = 3\n", 70 | "e = subtract(5,z)\n", 71 | "e" 72 | ] 73 | }, 74 | { 75 | "cell_type": "code", 76 | "execution_count": null, 77 | "metadata": { 78 | "collapsed": false 79 | }, 80 | "outputs": [], 81 | "source": [ 82 | "z = 3\n", 83 | "e = subtract(x2 = z, x1 = 5)\n", 84 | "e" 85 | ] 86 | }, 87 | { 88 | "cell_type": "markdown", 89 | "metadata": {}, 90 | "source": [ 91 | "### Changing Arguments" 92 | ] 93 | }, 94 | { 95 | "cell_type": "code", 96 | "execution_count": null, 97 | "metadata": { 98 | "collapsed": false 99 | }, 100 | "outputs": [], 101 | "source": [ 102 | "def subtract(x1, x2):\n", 103 | " z = x1 - x2\n", 104 | " x2 = 50.\n", 105 | " return z\n", 106 | "a = 20.\n", 107 | "b = subtract(10, a) # returns -10.\n", 108 | "b" 109 | ] 110 | }, 111 | { 112 | "cell_type": "code", 113 | "execution_count": null, 114 | "metadata": { 115 | "collapsed": false 116 | }, 117 | "outputs": [], 118 | "source": [ 119 | "a # still has the value 20" 120 | ] 121 | }, 122 | { 123 | "cell_type": "code", 124 | "execution_count": null, 125 | "metadata": { 126 | "collapsed": false 127 | }, 128 | "outputs": [], 129 | "source": [ 130 | "def subtract(x):\n", 131 | " z = x[0] - x[1]\n", 132 | " x[1] = 50.\n", 133 | " return z\n", 134 | "a = [10,20]\n", 135 | "b = subtract(a) # returns -10\n", 136 | "b" 137 | ] 138 | }, 139 | { 140 | "cell_type": "code", 141 | "execution_count": null, 142 | "metadata": { 143 | "collapsed": false 144 | }, 145 | "outputs": [], 146 | "source": [ 147 | "a # is now [10, 50.0]\t" 148 | ] 149 | }, 150 | { 151 | "cell_type": "markdown", 152 | "metadata": {}, 153 | "source": [ 154 | "### Access to variables defined outside the local namespace" 155 | ] 156 | }, 157 | { 158 | "cell_type": "code", 159 | "execution_count": null, 160 | "metadata": { 161 | "collapsed": true 162 | }, 163 | "outputs": [], 164 | "source": [ 165 | "import numpy as np # here the variable np is defined\n", 166 | "def sqrt(x):\n", 167 | " return np.sqrt(x) # we use np inside the function" 168 | ] 169 | }, 170 | { 171 | "cell_type": "code", 172 | "execution_count": null, 173 | "metadata": { 174 | "collapsed": false 175 | }, 176 | "outputs": [], 177 | "source": [ 178 | "a = 3\n", 179 | "def multiply(x):\n", 180 | " return a * x # bad style: access to the variable a defined outside\n", 181 | "\n", 182 | "multiply(4) # returns 12" 183 | ] 184 | }, 185 | { 186 | "cell_type": "code", 187 | "execution_count": null, 188 | "metadata": { 189 | "collapsed": false 190 | }, 191 | "outputs": [], 192 | "source": [ 193 | "a=4\n", 194 | "multiply(4) # returns 16" 195 | ] 196 | }, 197 | { 198 | "cell_type": "code", 199 | "execution_count": null, 200 | "metadata": { 201 | "collapsed": true 202 | }, 203 | "outputs": [], 204 | "source": [ 205 | "def multiply(x, a):\n", 206 | " return a * x" 207 | ] 208 | }, 209 | { 210 | "cell_type": "markdown", 211 | "metadata": {}, 212 | "source": [ 213 | "### Default Arguments" 214 | ] 215 | }, 216 | { 217 | "cell_type": "code", 218 | "execution_count": null, 219 | "metadata": { 220 | "collapsed": false 221 | }, 222 | "outputs": [], 223 | "source": [ 224 | "import scipy.linalg as sl\n", 225 | "sl.norm(identity(3))" 226 | ] 227 | }, 228 | { 229 | "cell_type": "code", 230 | "execution_count": null, 231 | "metadata": { 232 | "collapsed": false 233 | }, 234 | "outputs": [], 235 | "source": [ 236 | "sl.norm(identity(3), ord = 'fro')" 237 | ] 238 | }, 239 | { 240 | "cell_type": "code", 241 | "execution_count": null, 242 | "metadata": { 243 | "collapsed": false 244 | }, 245 | "outputs": [], 246 | "source": [ 247 | "sl.norm(identity(3), 'fro')" 248 | ] 249 | }, 250 | { 251 | "cell_type": "code", 252 | "execution_count": null, 253 | "metadata": { 254 | "collapsed": false 255 | }, 256 | "outputs": [], 257 | "source": [ 258 | "def subtract(x1, x2 = 0):\n", 259 | " return x1 - x2\n", 260 | "\n", 261 | "subtract(5)" 262 | ] 263 | }, 264 | { 265 | "cell_type": "code", 266 | "execution_count": null, 267 | "metadata": { 268 | "collapsed": false 269 | }, 270 | "outputs": [], 271 | "source": [ 272 | "def my_list(x1, x2 = []):\n", 273 | " x2.append(x1)\n", 274 | " return x2\n", 275 | "my_list(1) # returns [1]" 276 | ] 277 | }, 278 | { 279 | "cell_type": "code", 280 | "execution_count": null, 281 | "metadata": { 282 | "collapsed": false 283 | }, 284 | "outputs": [], 285 | "source": [ 286 | "my_list(2) # returns [1,2]" 287 | ] 288 | }, 289 | { 290 | "cell_type": "markdown", 291 | "metadata": {}, 292 | "source": [ 293 | "### Variable Number of Arguments" 294 | ] 295 | }, 296 | { 297 | "cell_type": "code", 298 | "execution_count": null, 299 | "metadata": { 300 | "collapsed": true 301 | }, 302 | "outputs": [], 303 | "source": [ 304 | "data = [[1,2],[3,4]]\n", 305 | "style = dict({'linewidth':3,'marker':'o','color':'green'})" 306 | ] 307 | }, 308 | { 309 | "cell_type": "code", 310 | "execution_count": null, 311 | "metadata": { 312 | "collapsed": false 313 | }, 314 | "outputs": [], 315 | "source": [ 316 | "plot(*data, **style)" 317 | ] 318 | }, 319 | { 320 | "cell_type": "markdown", 321 | "metadata": {}, 322 | "source": [ 323 | "## Return Values" 324 | ] 325 | }, 326 | { 327 | "cell_type": "code", 328 | "execution_count": null, 329 | "metadata": { 330 | "collapsed": true 331 | }, 332 | "outputs": [], 333 | "source": [ 334 | "def complex_to_polar(z):\n", 335 | " r = sqrt(z.real ** 2 + z.imag ** 2)\n", 336 | " phi = arctan2(z.imag, z.real)\n", 337 | " return (r,phi) # here the return object is formed" 338 | ] 339 | }, 340 | { 341 | "cell_type": "code", 342 | "execution_count": null, 343 | "metadata": { 344 | "collapsed": false 345 | }, 346 | "outputs": [], 347 | "source": [ 348 | "z = 3 + 5j # here we define a complex number\n", 349 | "a = complex_to_polar(z)\n", 350 | "a" 351 | ] 352 | }, 353 | { 354 | "cell_type": "code", 355 | "execution_count": null, 356 | "metadata": { 357 | "collapsed": false 358 | }, 359 | "outputs": [], 360 | "source": [ 361 | "r = a[0]\n", 362 | "r" 363 | ] 364 | }, 365 | { 366 | "cell_type": "code", 367 | "execution_count": null, 368 | "metadata": { 369 | "collapsed": false 370 | }, 371 | "outputs": [], 372 | "source": [ 373 | "phi = a[1]\n", 374 | "phi" 375 | ] 376 | }, 377 | { 378 | "cell_type": "code", 379 | "execution_count": null, 380 | "metadata": { 381 | "collapsed": false 382 | }, 383 | "outputs": [], 384 | "source": [ 385 | "r,phi = complex_to_polar(z)\n", 386 | "r,phi" 387 | ] 388 | }, 389 | { 390 | "cell_type": "code", 391 | "execution_count": null, 392 | "metadata": { 393 | "collapsed": true 394 | }, 395 | "outputs": [], 396 | "source": [ 397 | "def append_to_list(L, x):\n", 398 | " L.append(x)" 399 | ] 400 | }, 401 | { 402 | "cell_type": "code", 403 | "execution_count": null, 404 | "metadata": { 405 | "collapsed": true 406 | }, 407 | "outputs": [], 408 | "source": [ 409 | "def function_with_dead_code(x):\n", 410 | " return 2 * x\n", 411 | " y = x ** 2 # these two lines ...\n", 412 | " return y # ... are never executed!" 413 | ] 414 | }, 415 | { 416 | "cell_type": "markdown", 417 | "metadata": {}, 418 | "source": [ 419 | "## Recursive functions" 420 | ] 421 | }, 422 | { 423 | "cell_type": "code", 424 | "execution_count": null, 425 | "metadata": { 426 | "collapsed": false 427 | }, 428 | "outputs": [], 429 | "source": [ 430 | "def chebyshev(n, x):\n", 431 | " if n == 0:\n", 432 | " return 1.\n", 433 | " elif n == 1:\n", 434 | " return x\n", 435 | " else:\n", 436 | " return 2. * x * chebyshev(n - 1, x) \\\n", 437 | " - chebyshev(n - 2 ,x)\n", 438 | "\n", 439 | "chebyshev(5, 0.52) # returns 0.39616645119999994" 440 | ] 441 | }, 442 | { 443 | "cell_type": "markdown", 444 | "metadata": {}, 445 | "source": [ 446 | "## Function Documentation" 447 | ] 448 | }, 449 | { 450 | "cell_type": "code", 451 | "execution_count": null, 452 | "metadata": { 453 | "collapsed": true 454 | }, 455 | "outputs": [], 456 | "source": [ 457 | "def newton(f, x0):\n", 458 | " \"\"\"\n", 459 | " Newton's method for computing a zero of a function\n", 460 | " on input:\n", 461 | " f (function) given function f(x)\n", 462 | " x0 (float) initial guess \n", 463 | " on return:\n", 464 | " y (float) the approximated zero of f\n", 465 | " \"\"\"\n", 466 | " ..." 467 | ] 468 | }, 469 | { 470 | "cell_type": "code", 471 | "execution_count": null, 472 | "metadata": { 473 | "collapsed": false 474 | }, 475 | "outputs": [], 476 | "source": [ 477 | "help(newton)" 478 | ] 479 | }, 480 | { 481 | "cell_type": "markdown", 482 | "metadata": {}, 483 | "source": [ 484 | "## Functions are Objects" 485 | ] 486 | }, 487 | { 488 | "cell_type": "code", 489 | "execution_count": null, 490 | "metadata": { 491 | "collapsed": false 492 | }, 493 | "outputs": [], 494 | "source": [ 495 | "def square(x):\n", 496 | " \"\"\"Return the square of `x`\"\"\"\n", 497 | " return x ** 2\n", 498 | "square(4) # 16\n", 499 | "sq = square # now sq is the same as square\n", 500 | "sq(4) # 16\n", 501 | "print(newton(sq, .2)) # passing as argument\n", 502 | "del sq" 503 | ] 504 | }, 505 | { 506 | "cell_type": "markdown", 507 | "metadata": {}, 508 | "source": [ 509 | "### Partial Application" 510 | ] 511 | }, 512 | { 513 | "cell_type": "code", 514 | "execution_count": null, 515 | "metadata": { 516 | "collapsed": false 517 | }, 518 | "outputs": [], 519 | "source": [ 520 | "import functools\n", 521 | "def sin_omega(t, freq):\n", 522 | " return sin(2 * pi * freq * t)\n", 523 | "\n", 524 | "def make_sine(frequency):\n", 525 | " return functools.partial(sin_omega, freq = frequency)\n", 526 | "\n", 527 | "sin1=make_sine(1)\n", 528 | "sin1(2)" 529 | ] 530 | }, 531 | { 532 | "cell_type": "code", 533 | "execution_count": null, 534 | "metadata": { 535 | "collapsed": false 536 | }, 537 | "outputs": [], 538 | "source": [ 539 | "def make_sine(freq):\n", 540 | " \"Make a sine function with frequency freq\"\n", 541 | " def mysine(t):\n", 542 | " return sin_omega(t, freq)\n", 543 | " return mysine\n", 544 | "sin1=make_sine(1)\n", 545 | "sin1(2)" 546 | ] 547 | }, 548 | { 549 | "cell_type": "markdown", 550 | "metadata": {}, 551 | "source": [ 552 | "## Anonymous Functions - the `lambda` keyword" 553 | ] 554 | }, 555 | { 556 | "cell_type": "code", 557 | "execution_count": null, 558 | "metadata": { 559 | "collapsed": false 560 | }, 561 | "outputs": [], 562 | "source": [ 563 | "import scipy.integrate as si\n", 564 | "si.quad(lambda x: x ** 2 + 5, 0, 1) " 565 | ] 566 | }, 567 | { 568 | "cell_type": "code", 569 | "execution_count": null, 570 | "metadata": { 571 | "collapsed": false 572 | }, 573 | "outputs": [], 574 | "source": [ 575 | "parabola = lambda x: x ** 2 + 5 \n", 576 | "parabola(3) # gives 14" 577 | ] 578 | }, 579 | { 580 | "cell_type": "code", 581 | "execution_count": null, 582 | "metadata": { 583 | "collapsed": false 584 | }, 585 | "outputs": [], 586 | "source": [ 587 | "def parabola(x):\n", 588 | " return x ** 2 + 5\n", 589 | "parabola(3)" 590 | ] 591 | }, 592 | { 593 | "cell_type": "code", 594 | "execution_count": null, 595 | "metadata": { 596 | "collapsed": false 597 | }, 598 | "outputs": [], 599 | "source": [ 600 | "import scipy.integrate as si\n", 601 | "for iteration in range(3):\n", 602 | " print(si.quad(lambda x: sin_omega(x, iteration * pi), 0, pi / 2.) )" 603 | ] 604 | }, 605 | { 606 | "cell_type": "markdown", 607 | "metadata": {}, 608 | "source": [ 609 | "## Functions as Decorators" 610 | ] 611 | }, 612 | { 613 | "cell_type": "code", 614 | "execution_count": null, 615 | "metadata": { 616 | "collapsed": true 617 | }, 618 | "outputs": [], 619 | "source": [ 620 | "def how_sparse(A):\n", 621 | " return len(A.reshape(-1).nonzero()[0])" 622 | ] 623 | }, 624 | { 625 | "cell_type": "code", 626 | "execution_count": null, 627 | "metadata": { 628 | "collapsed": false 629 | }, 630 | "outputs": [], 631 | "source": [ 632 | "how_sparse([1,2,0]) # returns an error" 633 | ] 634 | }, 635 | { 636 | "cell_type": "code", 637 | "execution_count": null, 638 | "metadata": { 639 | "collapsed": true 640 | }, 641 | "outputs": [], 642 | "source": [ 643 | "def cast2array(f):\n", 644 | " def new_function(obj):\n", 645 | " fA = f(array(obj))\n", 646 | " return fA\n", 647 | " return new_function" 648 | ] 649 | }, 650 | { 651 | "cell_type": "code", 652 | "execution_count": null, 653 | "metadata": { 654 | "collapsed": true 655 | }, 656 | "outputs": [], 657 | "source": [ 658 | "@cast2array\n", 659 | "def how_sparse(A):\n", 660 | " return len(A.reshape(-1).nonzero()[0]) " 661 | ] 662 | }, 663 | { 664 | "cell_type": "code", 665 | "execution_count": null, 666 | "metadata": { 667 | "collapsed": false 668 | }, 669 | "outputs": [], 670 | "source": [ 671 | "how_sparse([1,2,0]) # returns no error any more" 672 | ] 673 | } 674 | ], 675 | "metadata": { 676 | "anaconda-cloud": {}, 677 | "kernelspec": { 678 | "display_name": "Python [conda root]", 679 | "language": "python", 680 | "name": "conda-root-py" 681 | }, 682 | "language_info": { 683 | "codemirror_mode": { 684 | "name": "ipython", 685 | "version": 3 686 | }, 687 | "file_extension": ".py", 688 | "mimetype": "text/x-python", 689 | "name": "python", 690 | "nbconvert_exporter": "python", 691 | "pygments_lexer": "ipython3", 692 | "version": "3.5.2" 693 | } 694 | }, 695 | "nbformat": 4, 696 | "nbformat_minor": 0 697 | } 698 | -------------------------------------------------------------------------------- /9-iterators/.ipynb_checkpoints/9-Iterators-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [], 3 | "metadata": {}, 4 | "nbformat": 4, 5 | "nbformat_minor": 1 6 | } 7 | -------------------------------------------------------------------------------- /9-iterators/.ipynb_checkpoints/Chapter 9 Iterators-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "raw", 5 | "metadata": {}, 6 | "source": [] 7 | }, 8 | { 9 | "cell_type": "raw", 10 | "metadata": {}, 11 | "source": [] 12 | }, 13 | { 14 | "cell_type": "markdown", 15 | "metadata": {}, 16 | "source": [ 17 | "# " 18 | ] 19 | } 20 | ], 21 | "metadata": { 22 | "anaconda-cloud": {}, 23 | "kernelspec": { 24 | "display_name": "Python [conda root]", 25 | "language": "python", 26 | "name": "conda-root-py" 27 | }, 28 | "language_info": { 29 | "codemirror_mode": { 30 | "name": "ipython", 31 | "version": 3 32 | }, 33 | "file_extension": ".py", 34 | "mimetype": "text/x-python", 35 | "name": "python", 36 | "nbconvert_exporter": "python", 37 | "pygments_lexer": "ipython3", 38 | "version": "3.5.2" 39 | } 40 | }, 41 | "nbformat": 4, 42 | "nbformat_minor": 0 43 | } 44 | -------------------------------------------------------------------------------- /9-iterators/.ipynb_checkpoints/Untitled-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [], 3 | "metadata": {}, 4 | "nbformat": 4, 5 | "nbformat_minor": 0 6 | } 7 | -------------------------------------------------------------------------------- /9-iterators/.ipynb_checkpoints/Untitled1-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [], 3 | "metadata": {}, 4 | "nbformat": 4, 5 | "nbformat_minor": 0 6 | } 7 | -------------------------------------------------------------------------------- /9-iterators/9-Iterators.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Chapter 9: Iterators\n", 8 | "\n", 9 | "Here we present all code from this chapter, so that you can reproduce results by your own.\n", 10 | "\n", 11 | "We start by importing all general modules" 12 | ] 13 | }, 14 | { 15 | "cell_type": "code", 16 | "execution_count": 1, 17 | "metadata": { 18 | "collapsed": false 19 | }, 20 | "outputs": [], 21 | "source": [ 22 | "from scipy import *\n", 23 | "import itertools" 24 | ] 25 | }, 26 | { 27 | "cell_type": "markdown", 28 | "metadata": { 29 | "collapsed": true 30 | }, 31 | "source": [ 32 | "## Generators\n", 33 | "\n", 34 | "### Example: Odd numbers\n", 35 | "\n", 36 | "A generator for odd numbers smaller than $n$ could be defined like this:" 37 | ] 38 | }, 39 | { 40 | "cell_type": "code", 41 | "execution_count": 2, 42 | "metadata": { 43 | "collapsed": false 44 | }, 45 | "outputs": [], 46 | "source": [ 47 | "def odd_numbers(n):\n", 48 | " \"generator for odd numbers less than n\"\n", 49 | " for k in range(n):\n", 50 | " if k % 2 == 1:\n", 51 | " yield k" 52 | ] 53 | }, 54 | { 55 | "cell_type": "markdown", 56 | "metadata": {}, 57 | "source": [ 58 | "Then you can use it as:" 59 | ] 60 | }, 61 | { 62 | "cell_type": "code", 63 | "execution_count": 3, 64 | "metadata": { 65 | "collapsed": false 66 | }, 67 | "outputs": [ 68 | { 69 | "name": "stdout", 70 | "output_type": "stream", 71 | "text": [ 72 | "1 3 5 7 9 " 73 | ] 74 | } 75 | ], 76 | "source": [ 77 | "g = odd_numbers(10)\n", 78 | "for k in g:\n", 79 | " print(k,end=' ') # do something with k" 80 | ] 81 | }, 82 | { 83 | "cell_type": "markdown", 84 | "metadata": {}, 85 | "source": [ 86 | "or even as:" 87 | ] 88 | }, 89 | { 90 | "cell_type": "code", 91 | "execution_count": 4, 92 | "metadata": { 93 | "collapsed": false 94 | }, 95 | "outputs": [ 96 | { 97 | "name": "stdout", 98 | "output_type": "stream", 99 | "text": [ 100 | "1 3 5 7 9 " 101 | ] 102 | } 103 | ], 104 | "source": [ 105 | "for k in odd_numbers(10):\n", 106 | " print(k,end=' ') # do something with k" 107 | ] 108 | }, 109 | { 110 | "cell_type": "markdown", 111 | "metadata": {}, 112 | "source": [ 113 | "## Iterators are Disposable\n", 114 | "\n", 115 | "Note that an iterable object is able to create new iterators as many time as necessary.\n", 116 | "Let us examine the case of a list:" 117 | ] 118 | }, 119 | { 120 | "cell_type": "code", 121 | "execution_count": 5, 122 | "metadata": { 123 | "collapsed": false 124 | }, 125 | "outputs": [ 126 | { 127 | "data": { 128 | "text/plain": [ 129 | "['a', 'b', 'c']" 130 | ] 131 | }, 132 | "execution_count": 5, 133 | "metadata": {}, 134 | "output_type": "execute_result" 135 | } 136 | ], 137 | "source": [ 138 | "L = ['a', 'b', 'c']\n", 139 | "iterator = iter(L)\n", 140 | "list(iterator) # ['a', 'b', 'c']\n", 141 | "list(iterator) # [] empty list, because the iterator is exhausted\n", 142 | "\n", 143 | "new_iterator = iter(L) # new iterator, ready to be used\n", 144 | "list(new_iterator) # ['a', 'b', 'c']" 145 | ] 146 | }, 147 | { 148 | "cell_type": "markdown", 149 | "metadata": {}, 150 | "source": [ 151 | "## Iterator Tools" 152 | ] 153 | }, 154 | { 155 | "cell_type": "code", 156 | "execution_count": 6, 157 | "metadata": { 158 | "collapsed": false 159 | }, 160 | "outputs": [ 161 | { 162 | "name": "stdout", 163 | "output_type": "stream", 164 | "text": [ 165 | "0 a\n", 166 | "1 b\n", 167 | "2 c\n" 168 | ] 169 | } 170 | ], 171 | "source": [ 172 | "A = ['a', 'b', 'c']\n", 173 | "for iteration, x in enumerate(A):\n", 174 | " print(iteration, x)\n" 175 | ] 176 | }, 177 | { 178 | "cell_type": "code", 179 | "execution_count": 7, 180 | "metadata": { 181 | "collapsed": false 182 | }, 183 | "outputs": [ 184 | { 185 | "name": "stdout", 186 | "output_type": "stream", 187 | "text": [ 188 | "2\n", 189 | "1\n", 190 | "0\n" 191 | ] 192 | } 193 | ], 194 | "source": [ 195 | "A = [0, 1, 2]\n", 196 | "for elt in reversed(A):\n", 197 | " print(elt)" 198 | ] 199 | }, 200 | { 201 | "cell_type": "code", 202 | "execution_count": 8, 203 | "metadata": { 204 | "collapsed": false 205 | }, 206 | "outputs": [ 207 | { 208 | "name": "stdout", 209 | "output_type": "stream", 210 | "text": [ 211 | "integer 0\n", 212 | "integer 1\n", 213 | "integer 2\n", 214 | "integer 3\n", 215 | "integer 4\n", 216 | "integer 5\n" 217 | ] 218 | } 219 | ], 220 | "source": [ 221 | "for iteration in itertools.count():\n", 222 | " if iteration > 5:\n", 223 | " break # without this, the loop goes on forever\n", 224 | " print(\"integer {}\".format(iteration))" 225 | ] 226 | }, 227 | { 228 | "cell_type": "markdown", 229 | "metadata": {}, 230 | "source": [ 231 | "Let us find some odd numbers by combining `islice` with an infinite generator. First we modify the \n", 232 | "generator for odd numbers so that it becomes an infinite generator:" 233 | ] 234 | }, 235 | { 236 | "cell_type": "code", 237 | "execution_count": 9, 238 | "metadata": { 239 | "collapsed": true 240 | }, 241 | "outputs": [], 242 | "source": [ 243 | "def odd_numbers():\n", 244 | " k=-1\n", 245 | " while True:\n", 246 | " k+=1\n", 247 | " if k%2==1:\n", 248 | " yield k" 249 | ] 250 | }, 251 | { 252 | "cell_type": "markdown", 253 | "metadata": {}, 254 | "source": [ 255 | "Then, we use it with `islice` to get a list of some odd numbers:" 256 | ] 257 | }, 258 | { 259 | "cell_type": "code", 260 | "execution_count": 10, 261 | "metadata": { 262 | "collapsed": false 263 | }, 264 | "outputs": [ 265 | { 266 | "data": { 267 | "text/plain": [ 268 | "[21, 37, 53]" 269 | ] 270 | }, 271 | "execution_count": 10, 272 | "metadata": {}, 273 | "output_type": "execute_result" 274 | } 275 | ], 276 | "source": [ 277 | "list(itertools.islice(odd_numbers(),10,30,8))" 278 | ] 279 | }, 280 | { 281 | "cell_type": "markdown", 282 | "metadata": {}, 283 | "source": [ 284 | "## Generators of Recursive Sequences\n", 285 | "\n", 286 | "### Fibonacci Numbers" 287 | ] 288 | }, 289 | { 290 | "cell_type": "code", 291 | "execution_count": 11, 292 | "metadata": { 293 | "collapsed": true 294 | }, 295 | "outputs": [], 296 | "source": [ 297 | "def fibonacci(u0, u1):\n", 298 | " \"\"\"\n", 299 | " Infinite generator of the Fibonacci sequence.\n", 300 | " \"\"\"\n", 301 | " yield u0\n", 302 | " yield u1\n", 303 | " while True:\n", 304 | " u0, u1 = u1, u0+u1\n", 305 | " yield u1" 306 | ] 307 | }, 308 | { 309 | "cell_type": "code", 310 | "execution_count": 12, 311 | "metadata": { 312 | "collapsed": false 313 | }, 314 | "outputs": [ 315 | { 316 | "data": { 317 | "text/plain": [ 318 | "[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]" 319 | ] 320 | }, 321 | "execution_count": 12, 322 | "metadata": {}, 323 | "output_type": "execute_result" 324 | } 325 | ], 326 | "source": [ 327 | "list(itertools.islice(fibonacci(0, 1), 15))" 328 | ] 329 | }, 330 | { 331 | "cell_type": "markdown", 332 | "metadata": {}, 333 | "source": [ 334 | "## Example: Arithmetic Geometric Mean" 335 | ] 336 | }, 337 | { 338 | "cell_type": "code", 339 | "execution_count": 13, 340 | "metadata": { 341 | "collapsed": true 342 | }, 343 | "outputs": [], 344 | "source": [ 345 | "def arithmetic_geometric_mean(a, b):\n", 346 | " \"\"\"\n", 347 | " Generator for the arithmetic and geometric mean\n", 348 | " a, b initial values\n", 349 | " \"\"\" \n", 350 | " while True:\t# infinite loop\n", 351 | " a, b = (a+b)/2, sqrt(a*b)\n", 352 | " yield a, b" 353 | ] 354 | }, 355 | { 356 | "cell_type": "code", 357 | "execution_count": 14, 358 | "metadata": { 359 | "collapsed": true 360 | }, 361 | "outputs": [], 362 | "source": [ 363 | "from itertools import islice\n", 364 | "def elliptic_integral(k, tolerance=1e-5, maxiter=100):\n", 365 | " \"\"\"\n", 366 | " Compute an elliptic integral of the first kind.\n", 367 | " \"\"\"\n", 368 | " a_0, b_0 = 1., sqrt(1-k**2)\n", 369 | " for a, b in islice(arithmetic_geometric_mean(a_0, b_0), maxiter):\n", 370 | " if abs(a-b) < tolerance:\n", 371 | " return pi/(2*a)\n", 372 | " else:\n", 373 | " raise Exception(\"Algorithm did not converge\")" 374 | ] 375 | }, 376 | { 377 | "cell_type": "code", 378 | "execution_count": 15, 379 | "metadata": { 380 | "collapsed": true 381 | }, 382 | "outputs": [], 383 | "source": [ 384 | "def pendulum_period(L, theta, g=9.81):\n", 385 | " return 4*sqrt(L/g)*elliptic_integral(sin(theta/2))" 386 | ] 387 | }, 388 | { 389 | "cell_type": "code", 390 | "execution_count": 16, 391 | "metadata": { 392 | "collapsed": false 393 | }, 394 | "outputs": [ 395 | { 396 | "name": "stdout", 397 | "output_type": "stream", 398 | "text": [ 399 | "Period of pendulum with length 1.5 and initial angle theta 22.5 degree is 2.5551310824\n" 400 | ] 401 | } 402 | ], 403 | "source": [ 404 | "L=1.5\n", 405 | "theta=pi/4\n", 406 | "print('Period of pendulum with length {} and initial angle theta {} degree is'.format(L,theta*180/(2*pi)),\n", 407 | " pendulum_period(L,theta))" 408 | ] 409 | }, 410 | { 411 | "cell_type": "markdown", 412 | "metadata": {}, 413 | "source": [ 414 | "## Convergence Acceleration" 415 | ] 416 | }, 417 | { 418 | "cell_type": "code", 419 | "execution_count": 17, 420 | "metadata": { 421 | "collapsed": true 422 | }, 423 | "outputs": [], 424 | "source": [ 425 | "def Euler_accelerate(sequence):\n", 426 | " \"\"\"\n", 427 | " Accelerate the iterator in the variable `sequence`.\n", 428 | " \"\"\"\n", 429 | " s0 = next(sequence) # Si\n", 430 | " s1 = next(sequence) # Si+1\n", 431 | " s2 = next(sequence) # Si+2\n", 432 | " while True:\n", 433 | " yield s0 - ((s1 - s0)**2)/(s2 - 2*s1 + s0)\n", 434 | " s0, s1, s2 = s1, s2, next(sequence)" 435 | ] 436 | }, 437 | { 438 | "cell_type": "code", 439 | "execution_count": 18, 440 | "metadata": { 441 | "collapsed": true 442 | }, 443 | "outputs": [], 444 | "source": [ 445 | "def pi_series():\n", 446 | " sum = 0.\n", 447 | " j = 1\n", 448 | " for i in itertools.cycle([1, -1]):\n", 449 | " yield sum\n", 450 | " sum += i/j\n", 451 | " j += 2" 452 | ] 453 | }, 454 | { 455 | "cell_type": "code", 456 | "execution_count": 19, 457 | "metadata": { 458 | "collapsed": false 459 | }, 460 | "outputs": [ 461 | { 462 | "data": { 463 | "text/plain": [ 464 | "[0.75,\n", 465 | " 0.7916666666666667,\n", 466 | " 0.7833333333333334,\n", 467 | " 0.7863095238095239,\n", 468 | " 0.784920634920635,\n", 469 | " 0.7856782106782109,\n", 470 | " 0.7852203352203354,\n", 471 | " 0.7855179542679545,\n", 472 | " 0.7853137059019414,\n", 473 | " 0.7854599047323508]" 474 | ] 475 | }, 476 | "execution_count": 19, 477 | "metadata": {}, 478 | "output_type": "execute_result" 479 | } 480 | ], 481 | "source": [ 482 | "N=10\n", 483 | "list(itertools.islice(Euler_accelerate(pi_series()), N))" 484 | ] 485 | }, 486 | { 487 | "cell_type": "markdown", 488 | "metadata": {}, 489 | "source": [ 490 | "## Storing generated values when an exception is raised" 491 | ] 492 | }, 493 | { 494 | "cell_type": "code", 495 | "execution_count": 20, 496 | "metadata": { 497 | "collapsed": true 498 | }, 499 | "outputs": [], 500 | "source": [ 501 | "import itertools\n", 502 | "def power_sequence(u0):\n", 503 | " u = u0\n", 504 | " while True:\n", 505 | " yield u\n", 506 | " u = u**2" 507 | ] 508 | }, 509 | { 510 | "cell_type": "code", 511 | "execution_count": 21, 512 | "metadata": { 513 | "collapsed": false 514 | }, 515 | "outputs": [ 516 | { 517 | "name": "stdout", 518 | "output_type": "stream", 519 | "text": [ 520 | "[2.0, 4.0, 16.0, 256.0, 65536.0, 4294967296.0, 1.8446744073709552e+19, 3.402823669209385e+38, 1.157920892373162e+77, 1.3407807929942597e+154]\n" 521 | ] 522 | } 523 | ], 524 | "source": [ 525 | "generator = power_sequence(2.)\n", 526 | "L = []\n", 527 | "for iteration in range(20):\n", 528 | " try:\n", 529 | " L.append(next(generator))\n", 530 | " except Exception:\n", 531 | " break\n", 532 | "print(L)" 533 | ] 534 | }, 535 | { 536 | "cell_type": "markdown", 537 | "metadata": {}, 538 | "source": [ 539 | "## When Iterators Behave as Lists\n", 540 | "\n", 541 | "### Generator expressions" 542 | ] 543 | }, 544 | { 545 | "cell_type": "code", 546 | "execution_count": 22, 547 | "metadata": { 548 | "collapsed": true 549 | }, 550 | "outputs": [], 551 | "source": [ 552 | "g = (n for n in range(1000) if not n % 100)" 553 | ] 554 | }, 555 | { 556 | "cell_type": "code", 557 | "execution_count": 23, 558 | "metadata": { 559 | "collapsed": false 560 | }, 561 | "outputs": [ 562 | { 563 | "name": "stdout", 564 | "output_type": "stream", 565 | "text": [ 566 | "[0, 100, 200, 300, 400, 500, 600, 700, 800, 900]\n" 567 | ] 568 | } 569 | ], 570 | "source": [ 571 | "print(list(g))" 572 | ] 573 | }, 574 | { 575 | "cell_type": "code", 576 | "execution_count": 24, 577 | "metadata": { 578 | "collapsed": false 579 | }, 580 | "outputs": [ 581 | { 582 | "data": { 583 | "text/plain": [ 584 | "4500" 585 | ] 586 | }, 587 | "execution_count": 24, 588 | "metadata": {}, 589 | "output_type": "execute_result" 590 | } 591 | ], 592 | "source": [ 593 | "sum(n for n in range(1000) if not n % 100) " 594 | ] 595 | }, 596 | { 597 | "cell_type": "markdown", 598 | "metadata": {}, 599 | "source": [ 600 | "#### $\\zeta$-function" 601 | ] 602 | }, 603 | { 604 | "cell_type": "code", 605 | "execution_count": 25, 606 | "metadata": { 607 | "collapsed": false 608 | }, 609 | "outputs": [ 610 | { 611 | "data": { 612 | "text/plain": [ 613 | "1.6439345666815615" 614 | ] 615 | }, 616 | "execution_count": 25, 617 | "metadata": {}, 618 | "output_type": "execute_result" 619 | } 620 | ], 621 | "source": [ 622 | "def generate_zeta(s):\n", 623 | " for n in itertools.count(1):\n", 624 | " yield 1/n**s\n", 625 | "\n", 626 | "def zeta(N, s):\n", 627 | " return sum(x for x in itertools.islice(generate_zeta(s), N))\n", 628 | "\n", 629 | "zeta(1000,2)" 630 | ] 631 | }, 632 | { 633 | "cell_type": "markdown", 634 | "metadata": {}, 635 | "source": [ 636 | "## Iterator Objects\n", 637 | "\n", 638 | "### ODE store" 639 | ] 640 | }, 641 | { 642 | "cell_type": "code", 643 | "execution_count": 26, 644 | "metadata": { 645 | "collapsed": false 646 | }, 647 | "outputs": [ 648 | { 649 | "name": "stdout", 650 | "output_type": "stream", 651 | "text": [ 652 | "1\n", 653 | "1.1\n", 654 | "1.3\n" 655 | ] 656 | }, 657 | { 658 | "data": { 659 | "text/plain": [ 660 | "[1, 1.1, 1.3]" 661 | ] 662 | }, 663 | "execution_count": 26, 664 | "metadata": {}, 665 | "output_type": "execute_result" 666 | } 667 | ], 668 | "source": [ 669 | "class OdeStore:\n", 670 | " \"\"\"Class to store results of ode computations\"\"\"\n", 671 | " def __init__(self, data):\n", 672 | " \"data is a list of the form [[t0, u0], [t1, u1],...]\"\n", 673 | " self.data = data\n", 674 | " def __iter__(self):\n", 675 | " \"By default, we iterate on the values u0, u1,...\"\n", 676 | " for t, u in self.data:\n", 677 | " yield u\n", 678 | "\n", 679 | "store = OdeStore([[0, 1], [0.1, 1.1], [0.2, 1.3]])\n", 680 | "for u in store:\n", 681 | " print(u)\n", 682 | "list(store) " 683 | ] 684 | } 685 | ], 686 | "metadata": { 687 | "anaconda-cloud": {}, 688 | "kernelspec": { 689 | "display_name": "Python [conda root]", 690 | "language": "python", 691 | "name": "conda-root-py" 692 | }, 693 | "language_info": { 694 | "codemirror_mode": { 695 | "name": "ipython", 696 | "version": 3 697 | }, 698 | "file_extension": ".py", 699 | "mimetype": "text/x-python", 700 | "name": "python", 701 | "nbconvert_exporter": "python", 702 | "pygments_lexer": "ipython3", 703 | "version": "3.5.2" 704 | } 705 | }, 706 | "nbformat": 4, 707 | "nbformat_minor": 1 708 | } 709 | -------------------------------------------------------------------------------- /9-iterators/Euler.py: -------------------------------------------------------------------------------- 1 | # See Hairer Wanner: Analysis by its history p. 65 2 | 3 | def th52(x): 4 | fx=x 5 | k=1 6 | while True: 7 | yield fx 8 | fx=fx*(1-x**2/(k*pi)**2) 9 | k+=1 10 | x=linspace(-1,3.5*pi,200) 11 | it=th52(x) 12 | for k in range(10): 13 | plot(x,next(it)) 14 | axis([-2,12,-5,5]) 15 | xlabel('x',fontsize=18) 16 | ylabel('$P_k(x)$',fontsize=18) 17 | xlabel('$x$',fontsize=18) 18 | grid() 19 | ax=gca() 20 | ax.annotate('$k=5$',(8.6,3.4),(9.6,4.2),arrowprops=dict(facecolor='black', shrink=0.05, width=1),fontsize=18) 21 | -------------------------------------------------------------------------------- /9-iterators/seqacceleration.py: -------------------------------------------------------------------------------- 1 | from matplotlib.pyplot import * 2 | import itertools 3 | 4 | def Euler_accelerate(sequence): 5 | """ 6 | Accelerate the iterator in the variable `sequence`. 7 | """ 8 | s0 = next(sequence) # Si 9 | s1 = next(sequence) # Si+1 10 | s2 = next(sequence) # Si+2 11 | while True: 12 | yield s0 - ((s1 - s0)**2)/(s2 - 2*s1 + s0) 13 | s0, s1, s2 = s1, s2, next(sequence) 14 | def pi_series(): 15 | sum = 0. 16 | j = 1 17 | for i in itertools.cycle([1, -1]): 18 | yield sum 19 | sum += i/j 20 | j += 2 21 | sna=array(list(itertools.islice(Euler_accelerate(pi_series()),30))) 22 | snw=array(list(itertools.islice(pi_series(),30))) 23 | plot(log10(abs(snw-pi/4)),label='not accelerated') 24 | plot(log10(abs(sna-pi/4)),label='accelerated',linewidth=3) 25 | legend() 26 | grid() 27 | ylabel('$\log_{10}(|S_N - \pi/4|)$',fontsize=18) 28 | xlabel('N',fontsize=18) 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 Karan 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | # Scientific Computing with Python 3 5 | This is the code repository for [Scientific Computing with Python 3](https://www.packtpub.com/big-data-and-business-intelligence/scientific-computing-python-3-second-edition?utm_source=github&utm_medium=repository&utm_campaign=9781786463517), published by Packt. It contains all the supporting project files necessary to work through the book from start to finish. 6 | ## Instructions and Navigations 7 | All of the code is organized into folders. Each folder starts with a number followed by the application name. For example, Chapter02. 8 | 9 | 10 | 11 | Every book chapter corresponds to a folder. 12 | 13 | These folders contain: 14 | 15 | 16 | 1) An Jupyter notebook file (execute first in a command window: 17 | jupyter notebook 18 | 19 | 20 | 2) A correponding html-file with notebook's output 21 | 22 | 3) The editable python code 23 | 24 | The code will look like the following: 25 | ``` 26 | A block of code is set as follows: 27 | 28 | from scipy import * 29 | from matplotlib.pyplot import * 30 | 31 | Any command-line input or output is written as follows: 32 | jupyter notebook 33 | ``` 34 | 35 | You would need Pyhon3.5 or higher, SciPy, NumPy, Matplotlib, IPython shell (we recommend strongly to install Python and its packages through Anaconda). The examples of the book do not have any special hardware requirements on memory and graphics 36 | 37 | 38 | 39 | ## Related Products 40 | * [Mastering Python Scientific Computing](https://www.packtpub.com/big-data-and-business-intelligence/mastering-python-scientific-computing?utm_source=github&utm_medium=repository&utm_campaign=9781783288823) 41 | 42 | * [Learning SciPy for Numerical and Scientific Computing](https://www.packtpub.com/big-data-and-business-intelligence/learning-scipy-numerical-and-scientific-computing?utm_source=github&utm_medium=repository&utm_campaign=9781782161622) 43 | 44 | * [Scientific Computing with Scala](https://www.packtpub.com/big-data-and-business-intelligence/scientific-computing-scala?utm_source=github&utm_medium=repository&utm_campaign=9781785886942) 45 | ### Suggestions and Feedback 46 | [Click here](https://docs.google.com/forms/d/e/1FAIpQLSe5qwunkGf6PUvzPirPDtuy1Du5Rlzew23UBp2S-P3wB-GcwQ/viewform) if you have any feedback or suggestions. 47 | ### Download a free PDF 48 | 49 | If you have already purchased a print or Kindle version of this book, you can get a DRM-free PDF version at no cost.
Simply click on the link to claim your free PDF.
50 |

https://packt.link/free-ebook/9781786463517

--------------------------------------------------------------------------------