├── Chapter01 ├── chapter01.html ├── chapter01.ipynb └── smartfunctions.py ├── Chapter02 ├── chapter02.html └── chapter02.ipynb ├── Chapter03 ├── chapter03.html └── chapter03.ipynb ├── Chapter04 ├── chapter04.html └── chapter04.ipynb ├── Chapter05 ├── chapter5.html └── chapter5.ipynb ├── Chapter06 ├── chapter06.html └── chapter06.ipynb ├── Chapter07 ├── chapter07.html └── chapter07.ipynb ├── Chapter08 ├── chapter08.html └── chapter08.ipynb ├── Chapter09 ├── chapter09.html └── chapter09.ipynb ├── Chapter10 ├── chapter10.html ├── chapter10.ipynb ├── price.dat ├── rates.dat └── solarWatts.dat ├── Chapter11 ├── chapter11.html ├── chapter11.ipynb └── circle_evolution.swf ├── Chapter12 ├── chapter12.html └── chapter12.ipynb ├── Chapter13 ├── chapter13.html └── chapter13.ipynb ├── Chapter14 ├── a_file.dat ├── chapter14.html ├── chapter14.ipynb ├── datafile.bak ├── datafile.dat ├── datafile.dir ├── file.dat ├── file3.dat ├── measurement.dat ├── newimage.jpg ├── temp.dat ├── test.jpg └── test.txt ├── Chapter15 ├── bisection.py ├── chapter15.html ├── chapter15.ipynb └── find_in_file.py ├── Chapter16 ├── chapter16.html └── chapter16.ipynb ├── Chapter18 ├── Untitled.ipynb └── ch18.ipynb ├── Chapter19 ├── chapter19.html └── chapter19.ipynb ├── LICENSE └── README.md /Chapter01/chapter01.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Scientific Computing with Python (Second Edition)\n", 8 | "## Chapter 01" 9 | ] 10 | }, 11 | { 12 | "cell_type": "markdown", 13 | "metadata": {}, 14 | "source": [ 15 | "*We start by importing all from Numpy. As explained in this chapter the examples are written assuming this import is initially done.*" 16 | ] 17 | }, 18 | { 19 | "cell_type": "code", 20 | "execution_count": 1, 21 | "metadata": {}, 22 | "outputs": [], 23 | "source": [ 24 | "from numpy import *" 25 | ] 26 | }, 27 | { 28 | "cell_type": "markdown", 29 | "metadata": {}, 30 | "source": [ 31 | "## 1.1 Some Installation and configuration instructions" 32 | ] 33 | }, 34 | { 35 | "cell_type": "markdown", 36 | "metadata": {}, 37 | "source": [ 38 | "*No code in this book section*" 39 | ] 40 | }, 41 | { 42 | "cell_type": "markdown", 43 | "metadata": {}, 44 | "source": [ 45 | "## 1.2 Program and program flow\n", 46 | "### 1.2.1 Comments" 47 | ] 48 | }, 49 | { 50 | "cell_type": "code", 51 | "execution_count": 2, 52 | "metadata": {}, 53 | "outputs": [], 54 | "source": [ 55 | "# This is a comment of the following statement\n", 56 | "a = 3 # ... which might get a further comment here " 57 | ] 58 | }, 59 | { 60 | "cell_type": "markdown", 61 | "metadata": {}, 62 | "source": [ 63 | "## 1.3 Basic Datatypes\n", 64 | "### 1.3.1 Numbers" 65 | ] 66 | }, 67 | { 68 | "cell_type": "code", 69 | "execution_count": 3, 70 | "metadata": {}, 71 | "outputs": [], 72 | "source": [ 73 | "from numpy import *" 74 | ] 75 | }, 76 | { 77 | "cell_type": "code", 78 | "execution_count": 4, 79 | "metadata": {}, 80 | "outputs": [ 81 | { 82 | "data": { 83 | "text/plain": [ 84 | "16" 85 | ] 86 | }, 87 | "execution_count": 4, 88 | "metadata": {}, 89 | "output_type": "execute_result" 90 | } 91 | ], 92 | "source": [ 93 | "2 ** (2 + 2) # 16" 94 | ] 95 | }, 96 | { 97 | "cell_type": "code", 98 | "execution_count": 5, 99 | "metadata": {}, 100 | "outputs": [ 101 | { 102 | "data": { 103 | "text/plain": [ 104 | "(-1+0j)" 105 | ] 106 | }, 107 | "execution_count": 5, 108 | "metadata": {}, 109 | "output_type": "execute_result" 110 | } 111 | ], 112 | "source": [ 113 | "1j ** 2 # -1" 114 | ] 115 | }, 116 | { 117 | "cell_type": "code", 118 | "execution_count": 6, 119 | "metadata": {}, 120 | "outputs": [ 121 | { 122 | "data": { 123 | "text/plain": [ 124 | "(1+3j)" 125 | ] 126 | }, 127 | "execution_count": 6, 128 | "metadata": {}, 129 | "output_type": "execute_result" 130 | } 131 | ], 132 | "source": [ 133 | "1. + 3.0j" 134 | ] 135 | }, 136 | { 137 | "cell_type": "markdown", 138 | "metadata": {}, 139 | "source": [ 140 | "### 1.3.2 Strings" 141 | ] 142 | }, 143 | { 144 | "cell_type": "code", 145 | "execution_count": 7, 146 | "metadata": {}, 147 | "outputs": [ 148 | { 149 | "data": { 150 | "text/plain": [ 151 | "'valid string'" 152 | ] 153 | }, 154 | "execution_count": 7, 155 | "metadata": {}, 156 | "output_type": "execute_result" 157 | } 158 | ], 159 | "source": [ 160 | "'valid string'" 161 | ] 162 | }, 163 | { 164 | "cell_type": "code", 165 | "execution_count": 8, 166 | "metadata": {}, 167 | "outputs": [ 168 | { 169 | "data": { 170 | "text/plain": [ 171 | "'string with double quotes'" 172 | ] 173 | }, 174 | "execution_count": 8, 175 | "metadata": {}, 176 | "output_type": "execute_result" 177 | } 178 | ], 179 | "source": [ 180 | "\"string with double quotes\"" 181 | ] 182 | }, 183 | { 184 | "cell_type": "code", 185 | "execution_count": 9, 186 | "metadata": {}, 187 | "outputs": [ 188 | { 189 | "data": { 190 | "text/plain": [ 191 | "\"you shouldn't forget comments\"" 192 | ] 193 | }, 194 | "execution_count": 9, 195 | "metadata": {}, 196 | "output_type": "execute_result" 197 | } 198 | ], 199 | "source": [ 200 | "\"you shouldn't forget comments\"" 201 | ] 202 | }, 203 | { 204 | "cell_type": "code", 205 | "execution_count": 10, 206 | "metadata": {}, 207 | "outputs": [ 208 | { 209 | "data": { 210 | "text/plain": [ 211 | "'these are double quotes: \"..\" '" 212 | ] 213 | }, 214 | "execution_count": 10, 215 | "metadata": {}, 216 | "output_type": "execute_result" 217 | } 218 | ], 219 | "source": [ 220 | "'these are double quotes: \"..\" '" 221 | ] 222 | }, 223 | { 224 | "cell_type": "code", 225 | "execution_count": 11, 226 | "metadata": {}, 227 | "outputs": [ 228 | { 229 | "data": { 230 | "text/plain": [ 231 | "'This is\\n a long,\\n long string'" 232 | ] 233 | }, 234 | "execution_count": 11, 235 | "metadata": {}, 236 | "output_type": "execute_result" 237 | } 238 | ], 239 | "source": [ 240 | "\"\"\"This is\n", 241 | " a long,\n", 242 | " long string\"\"\"" 243 | ] 244 | }, 245 | { 246 | "cell_type": "markdown", 247 | "metadata": {}, 248 | "source": [ 249 | "### 1.3.3 Variables" 250 | ] 251 | }, 252 | { 253 | "cell_type": "code", 254 | "execution_count": 12, 255 | "metadata": {}, 256 | "outputs": [ 257 | { 258 | "name": "stdout", 259 | "output_type": "stream", 260 | "text": [ 261 | "[3, 4]\n" 262 | ] 263 | } 264 | ], 265 | "source": [ 266 | "x = [3, 4] # a list object is created\n", 267 | "\n", 268 | "y = x # this object now has two labels: x and y\n", 269 | "\n", 270 | "del x # we delete one of the labels\n", 271 | "del y # both labels are removed: the object is deleted\n", 272 | "\n", 273 | "x = [3, 4] # a list object is created\n", 274 | "print(x)" 275 | ] 276 | }, 277 | { 278 | "cell_type": "markdown", 279 | "metadata": {}, 280 | "source": [ 281 | "### 1.3.4 Lists" 282 | ] 283 | }, 284 | { 285 | "cell_type": "code", 286 | "execution_count": 13, 287 | "metadata": {}, 288 | "outputs": [ 289 | { 290 | "data": { 291 | "text/plain": [ 292 | "5" 293 | ] 294 | }, 295 | "execution_count": 13, 296 | "metadata": {}, 297 | "output_type": "execute_result" 298 | } 299 | ], 300 | "source": [ 301 | "L1 = [5, 6]\n", 302 | "\n", 303 | "L1[0] # 5" 304 | ] 305 | }, 306 | { 307 | "cell_type": "code", 308 | "execution_count": 14, 309 | "metadata": {}, 310 | "outputs": [ 311 | { 312 | "data": { 313 | "text/plain": [ 314 | "6" 315 | ] 316 | }, 317 | "execution_count": 14, 318 | "metadata": {}, 319 | "output_type": "execute_result" 320 | } 321 | ], 322 | "source": [ 323 | "L1[1] # 6" 324 | ] 325 | }, 326 | { 327 | "cell_type": "markdown", 328 | "metadata": {}, 329 | "source": [ 330 | "*Uncomment the next line in order to see the error*" 331 | ] 332 | }, 333 | { 334 | "cell_type": "code", 335 | "execution_count": 15, 336 | "metadata": {}, 337 | "outputs": [], 338 | "source": [ 339 | "# L1[2] # raises IndexErrorL1 = [5, 6]" 340 | ] 341 | }, 342 | { 343 | "cell_type": "code", 344 | "execution_count": 16, 345 | "metadata": {}, 346 | "outputs": [ 347 | { 348 | "data": { 349 | "text/plain": [ 350 | "5" 351 | ] 352 | }, 353 | "execution_count": 16, 354 | "metadata": {}, 355 | "output_type": "execute_result" 356 | } 357 | ], 358 | "source": [ 359 | "L1[0] # 5" 360 | ] 361 | }, 362 | { 363 | "cell_type": "code", 364 | "execution_count": 17, 365 | "metadata": {}, 366 | "outputs": [ 367 | { 368 | "data": { 369 | "text/plain": [ 370 | "6" 371 | ] 372 | }, 373 | "execution_count": 17, 374 | "metadata": {}, 375 | "output_type": "execute_result" 376 | } 377 | ], 378 | "source": [ 379 | "L1[1] # 6" 380 | ] 381 | }, 382 | { 383 | "cell_type": "markdown", 384 | "metadata": {}, 385 | "source": [ 386 | "*Uncomment the next line in order to see the error*" 387 | ] 388 | }, 389 | { 390 | "cell_type": "code", 391 | "execution_count": 18, 392 | "metadata": {}, 393 | "outputs": [], 394 | "source": [ 395 | "# L1[2] # raises IndexError" 396 | ] 397 | }, 398 | { 399 | "cell_type": "code", 400 | "execution_count": 19, 401 | "metadata": {}, 402 | "outputs": [], 403 | "source": [ 404 | "L2 = ['a', 1, [3, 4]]" 405 | ] 406 | }, 407 | { 408 | "cell_type": "code", 409 | "execution_count": 20, 410 | "metadata": {}, 411 | "outputs": [ 412 | { 413 | "data": { 414 | "text/plain": [ 415 | "'a'" 416 | ] 417 | }, 418 | "execution_count": 20, 419 | "metadata": {}, 420 | "output_type": "execute_result" 421 | } 422 | ], 423 | "source": [ 424 | "L2[0] # 'a'" 425 | ] 426 | }, 427 | { 428 | "cell_type": "code", 429 | "execution_count": 21, 430 | "metadata": {}, 431 | "outputs": [ 432 | { 433 | "data": { 434 | "text/plain": [ 435 | "3" 436 | ] 437 | }, 438 | "execution_count": 21, 439 | "metadata": {}, 440 | "output_type": "execute_result" 441 | } 442 | ], 443 | "source": [ 444 | "L2[2][0] # 3" 445 | ] 446 | }, 447 | { 448 | "cell_type": "code", 449 | "execution_count": 22, 450 | "metadata": {}, 451 | "outputs": [ 452 | { 453 | "data": { 454 | "text/plain": [ 455 | "[3, 4]" 456 | ] 457 | }, 458 | "execution_count": 22, 459 | "metadata": {}, 460 | "output_type": "execute_result" 461 | } 462 | ], 463 | "source": [ 464 | "L2[-1] # last element: [3,4]" 465 | ] 466 | }, 467 | { 468 | "cell_type": "code", 469 | "execution_count": 23, 470 | "metadata": {}, 471 | "outputs": [ 472 | { 473 | "data": { 474 | "text/plain": [ 475 | "1" 476 | ] 477 | }, 478 | "execution_count": 23, 479 | "metadata": {}, 480 | "output_type": "execute_result" 481 | } 482 | ], 483 | "source": [ 484 | "L2[-2] # second to last: 1" 485 | ] 486 | }, 487 | { 488 | "cell_type": "code", 489 | "execution_count": 24, 490 | "metadata": {}, 491 | "outputs": [ 492 | { 493 | "name": "stdout", 494 | "output_type": "stream", 495 | "text": [ 496 | "[0, 1, 2, 3, 4]\n" 497 | ] 498 | } 499 | ], 500 | "source": [ 501 | "print(list(range(5))) # returns [0, 1, 2, 3, 4]" 502 | ] 503 | }, 504 | { 505 | "cell_type": "code", 506 | "execution_count": 25, 507 | "metadata": {}, 508 | "outputs": [ 509 | { 510 | "data": { 511 | "text/plain": [ 512 | "4" 513 | ] 514 | }, 515 | "execution_count": 25, 516 | "metadata": {}, 517 | "output_type": "execute_result" 518 | } 519 | ], 520 | "source": [ 521 | "len(['a', 1, 2, 34]) # returns 4" 522 | ] 523 | }, 524 | { 525 | "cell_type": "code", 526 | "execution_count": 26, 527 | "metadata": {}, 528 | "outputs": [ 529 | { 530 | "data": { 531 | "text/plain": [ 532 | "2" 533 | ] 534 | }, 535 | "execution_count": 26, 536 | "metadata": {}, 537 | "output_type": "execute_result" 538 | } 539 | ], 540 | "source": [ 541 | "len(['a',[1,2]]) # returns 2" 542 | ] 543 | }, 544 | { 545 | "cell_type": "code", 546 | "execution_count": 27, 547 | "metadata": {}, 548 | "outputs": [ 549 | { 550 | "data": { 551 | "text/plain": [ 552 | "'c'" 553 | ] 554 | }, 555 | "execution_count": 27, 556 | "metadata": {}, 557 | "output_type": "execute_result" 558 | } 559 | ], 560 | "source": [ 561 | "L = ['a', 'b', 'c']\n", 562 | "\n", 563 | "L[-1] # 'c'" 564 | ] 565 | }, 566 | { 567 | "cell_type": "code", 568 | "execution_count": 28, 569 | "metadata": {}, 570 | "outputs": [ 571 | { 572 | "data": { 573 | "text/plain": [ 574 | "['a', 'b', 'c', 'd']" 575 | ] 576 | }, 577 | "execution_count": 28, 578 | "metadata": {}, 579 | "output_type": "execute_result" 580 | } 581 | ], 582 | "source": [ 583 | "L.append('d')\n", 584 | "\n", 585 | "L # L is now ['a', 'b', 'c', 'd']" 586 | ] 587 | }, 588 | { 589 | "cell_type": "code", 590 | "execution_count": 29, 591 | "metadata": {}, 592 | "outputs": [ 593 | { 594 | "data": { 595 | "text/plain": [ 596 | "'d'" 597 | ] 598 | }, 599 | "execution_count": 29, 600 | "metadata": {}, 601 | "output_type": "execute_result" 602 | } 603 | ], 604 | "source": [ 605 | "L[-1] # 'd'" 606 | ] 607 | }, 608 | { 609 | "cell_type": "markdown", 610 | "metadata": {}, 611 | "source": [ 612 | "### 1.3.5 Operations on Lists" 613 | ] 614 | }, 615 | { 616 | "cell_type": "code", 617 | "execution_count": 30, 618 | "metadata": {}, 619 | "outputs": [ 620 | { 621 | "data": { 622 | "text/plain": [ 623 | "[1, 2, 3, 4]" 624 | ] 625 | }, 626 | "execution_count": 30, 627 | "metadata": {}, 628 | "output_type": "execute_result" 629 | } 630 | ], 631 | "source": [ 632 | "L1 = [1, 2]\n", 633 | "L2 = [3, 4]\n", 634 | "L = L1 + L2 # [1, 2, 3, 4]\n", 635 | "L" 636 | ] 637 | }, 638 | { 639 | "cell_type": "code", 640 | "execution_count": 31, 641 | "metadata": {}, 642 | "outputs": [ 643 | { 644 | "data": { 645 | "text/plain": [ 646 | "[1, 2, 1, 2, 1, 2]" 647 | ] 648 | }, 649 | "execution_count": 31, 650 | "metadata": {}, 651 | "output_type": "execute_result" 652 | } 653 | ], 654 | "source": [ 655 | "L = [1, 2]\n", 656 | "3 * L # [1, 2, 1, 2, 1, 2]" 657 | ] 658 | }, 659 | { 660 | "cell_type": "markdown", 661 | "metadata": {}, 662 | "source": [ 663 | "### 1.3.6 Boolean Expressions" 664 | ] 665 | }, 666 | { 667 | "cell_type": "code", 668 | "execution_count": 32, 669 | "metadata": {}, 670 | "outputs": [ 671 | { 672 | "data": { 673 | "text/plain": [ 674 | "False" 675 | ] 676 | }, 677 | "execution_count": 32, 678 | "metadata": {}, 679 | "output_type": "execute_result" 680 | } 681 | ], 682 | "source": [ 683 | "2 >= 4 # False" 684 | ] 685 | }, 686 | { 687 | "cell_type": "code", 688 | "execution_count": 33, 689 | "metadata": {}, 690 | "outputs": [ 691 | { 692 | "data": { 693 | "text/plain": [ 694 | "True" 695 | ] 696 | }, 697 | "execution_count": 33, 698 | "metadata": {}, 699 | "output_type": "execute_result" 700 | } 701 | ], 702 | "source": [ 703 | "2 < 3 < 4 # True" 704 | ] 705 | }, 706 | { 707 | "cell_type": "code", 708 | "execution_count": 34, 709 | "metadata": {}, 710 | "outputs": [ 711 | { 712 | "data": { 713 | "text/plain": [ 714 | "False" 715 | ] 716 | }, 717 | "execution_count": 34, 718 | "metadata": {}, 719 | "output_type": "execute_result" 720 | } 721 | ], 722 | "source": [ 723 | "2 < 3 and 3 < 2 # False" 724 | ] 725 | }, 726 | { 727 | "cell_type": "code", 728 | "execution_count": 35, 729 | "metadata": {}, 730 | "outputs": [ 731 | { 732 | "data": { 733 | "text/plain": [ 734 | "True" 735 | ] 736 | }, 737 | "execution_count": 35, 738 | "metadata": {}, 739 | "output_type": "execute_result" 740 | } 741 | ], 742 | "source": [ 743 | "2 != 3 < 4 or False # True" 744 | ] 745 | }, 746 | { 747 | "cell_type": "code", 748 | "execution_count": 36, 749 | "metadata": {}, 750 | "outputs": [ 751 | { 752 | "data": { 753 | "text/plain": [ 754 | "True" 755 | ] 756 | }, 757 | "execution_count": 36, 758 | "metadata": {}, 759 | "output_type": "execute_result" 760 | } 761 | ], 762 | "source": [ 763 | "2 <= 2 and 2 >= 2 # True" 764 | ] 765 | }, 766 | { 767 | "cell_type": "code", 768 | "execution_count": 37, 769 | "metadata": {}, 770 | "outputs": [ 771 | { 772 | "data": { 773 | "text/plain": [ 774 | "True" 775 | ] 776 | }, 777 | "execution_count": 37, 778 | "metadata": {}, 779 | "output_type": "execute_result" 780 | } 781 | ], 782 | "source": [ 783 | "not 2 == 3 # True" 784 | ] 785 | }, 786 | { 787 | "cell_type": "code", 788 | "execution_count": 38, 789 | "metadata": { 790 | "scrolled": false 791 | }, 792 | "outputs": [ 793 | { 794 | "data": { 795 | "text/plain": [ 796 | "True" 797 | ] 798 | }, 799 | "execution_count": 38, 800 | "metadata": {}, 801 | "output_type": "execute_result" 802 | } 803 | ], 804 | "source": [ 805 | "not False or True and False # True!" 806 | ] 807 | }, 808 | { 809 | "cell_type": "markdown", 810 | "metadata": {}, 811 | "source": [ 812 | "## 1.4 Repeating statements with loops" 813 | ] 814 | }, 815 | { 816 | "cell_type": "code", 817 | "execution_count": 39, 818 | "metadata": {}, 819 | "outputs": [ 820 | { 821 | "name": "stdout", 822 | "output_type": "stream", 823 | "text": [ 824 | "2\n", 825 | "4\n", 826 | "20\n" 827 | ] 828 | } 829 | ], 830 | "source": [ 831 | "L = [1, 2, 10]\n", 832 | "for s in L:\n", 833 | " print(s * 2) # output: 2 4 20" 834 | ] 835 | }, 836 | { 837 | "cell_type": "code", 838 | "execution_count": 40, 839 | "metadata": {}, 840 | "outputs": [ 841 | { 842 | "name": "stdout", 843 | "output_type": "stream", 844 | "text": [ 845 | "loop finished\n" 846 | ] 847 | } 848 | ], 849 | "source": [ 850 | "my_list = [...] # define a list\n", 851 | "for elt in my_list:\n", 852 | " ... #do_something\n", 853 | " ... #something_else\n", 854 | "print(\"loop finished\") # outside the for block" 855 | ] 856 | }, 857 | { 858 | "cell_type": "markdown", 859 | "metadata": {}, 860 | "source": [ 861 | "### 1.4.1 Repeating a task" 862 | ] 863 | }, 864 | { 865 | "cell_type": "code", 866 | "execution_count": 41, 867 | "metadata": {}, 868 | "outputs": [], 869 | "source": [ 870 | "n = 30\n", 871 | "for iteration in range(n):\n", 872 | " ... # a statement here gets executed n times" 873 | ] 874 | }, 875 | { 876 | "cell_type": "markdown", 877 | "metadata": {}, 878 | "source": [ 879 | "### 1.4.2 break and else" 880 | ] 881 | }, 882 | { 883 | "cell_type": "code", 884 | "execution_count": 42, 885 | "metadata": {}, 886 | "outputs": [ 887 | { 888 | "name": "stdout", 889 | "output_type": "stream", 890 | "text": [ 891 | "0.5\n", 892 | "0.7\n" 893 | ] 894 | } 895 | ], 896 | "source": [ 897 | "x_values=[0.5, 0.7, 1.2]\n", 898 | "threshold = 0.75\n", 899 | "for x in x_values:\n", 900 | " if x > threshold:\n", 901 | " break\n", 902 | " print(x)" 903 | ] 904 | }, 905 | { 906 | "cell_type": "code", 907 | "execution_count": 43, 908 | "metadata": {}, 909 | "outputs": [ 910 | { 911 | "name": "stdout", 912 | "output_type": "stream", 913 | "text": [ 914 | "all the x are below the threshold\n" 915 | ] 916 | } 917 | ], 918 | "source": [ 919 | "x_values=[0.5, 0.7]\n", 920 | "threshold = 0.75\n", 921 | "for x in x_values:\n", 922 | " if x > threshold:\n", 923 | " break\n", 924 | "else:\n", 925 | " print(\"all the x are below the threshold\")" 926 | ] 927 | }, 928 | { 929 | "cell_type": "markdown", 930 | "metadata": {}, 931 | "source": [ 932 | "## 1.5 Conditional statements" 933 | ] 934 | }, 935 | { 936 | "cell_type": "code", 937 | "execution_count": 44, 938 | "metadata": {}, 939 | "outputs": [ 940 | { 941 | "name": "stdout", 942 | "output_type": "stream", 943 | "text": [ 944 | "5\n" 945 | ] 946 | } 947 | ], 948 | "source": [ 949 | "x = 5\n", 950 | "if x >= 0:\n", 951 | " print(x)\n", 952 | "else:\n", 953 | " print(-x)" 954 | ] 955 | }, 956 | { 957 | "cell_type": "markdown", 958 | "metadata": {}, 959 | "source": [ 960 | "## 1.6 Encapsulating code with functions" 961 | ] 962 | }, 963 | { 964 | "cell_type": "code", 965 | "execution_count": 45, 966 | "metadata": {}, 967 | "outputs": [], 968 | "source": [ 969 | "def f(x):\n", 970 | " return 2*x + 1" 971 | ] 972 | }, 973 | { 974 | "cell_type": "code", 975 | "execution_count": 46, 976 | "metadata": {}, 977 | "outputs": [ 978 | { 979 | "data": { 980 | "text/plain": [ 981 | "5" 982 | ] 983 | }, 984 | "execution_count": 46, 985 | "metadata": {}, 986 | "output_type": "execute_result" 987 | } 988 | ], 989 | "source": [ 990 | "f(2) # 5" 991 | ] 992 | }, 993 | { 994 | "cell_type": "code", 995 | "execution_count": 47, 996 | "metadata": {}, 997 | "outputs": [ 998 | { 999 | "data": { 1000 | "text/plain": [ 1001 | "3" 1002 | ] 1003 | }, 1004 | "execution_count": 47, 1005 | "metadata": {}, 1006 | "output_type": "execute_result" 1007 | } 1008 | ], 1009 | "source": [ 1010 | "f(1) # 3" 1011 | ] 1012 | }, 1013 | { 1014 | "cell_type": "markdown", 1015 | "metadata": {}, 1016 | "source": [ 1017 | "## 1.7 Understanding Scripts and modules" 1018 | ] 1019 | }, 1020 | { 1021 | "cell_type": "code", 1022 | "execution_count": 48, 1023 | "metadata": {}, 1024 | "outputs": [ 1025 | { 1026 | "name": "stdout", 1027 | "output_type": "stream", 1028 | "text": [ 1029 | "[-1, -1, 2, 3, 4, 5, 6, 7, 8, 9]\n" 1030 | ] 1031 | } 1032 | ], 1033 | "source": [ 1034 | "z = []\n", 1035 | "for x in range(10):\n", 1036 | " if f(x) > pi:\n", 1037 | " z.append(x)\n", 1038 | " else:\n", 1039 | " z.append(-1)\n", 1040 | "print(z)" 1041 | ] 1042 | }, 1043 | { 1044 | "cell_type": "markdown", 1045 | "metadata": {}, 1046 | "source": [ 1047 | "### 1.7.1 Simple modules - collecting functions" 1048 | ] 1049 | }, 1050 | { 1051 | "cell_type": "markdown", 1052 | "metadata": {}, 1053 | "source": [ 1054 | "*The next command requires that the file smartfunctions.py exists in the same folder as this file*" 1055 | ] 1056 | }, 1057 | { 1058 | "cell_type": "code", 1059 | "execution_count": 49, 1060 | "metadata": {}, 1061 | "outputs": [], 1062 | "source": [ 1063 | "exec(open('smartfunctions.py').read())" 1064 | ] 1065 | }, 1066 | { 1067 | "cell_type": "markdown", 1068 | "metadata": {}, 1069 | "source": [ 1070 | "### 1.7.2 Using modules and namespaces" 1071 | ] 1072 | }, 1073 | { 1074 | "cell_type": "markdown", 1075 | "metadata": {}, 1076 | "source": [ 1077 | "*The next commands require that the file smartfunctions.py exists in the same folder as this file*" 1078 | ] 1079 | }, 1080 | { 1081 | "cell_type": "code", 1082 | "execution_count": 50, 1083 | "metadata": {}, 1084 | "outputs": [ 1085 | { 1086 | "name": "stdout", 1087 | "output_type": "stream", 1088 | "text": [ 1089 | "5\n" 1090 | ] 1091 | } 1092 | ], 1093 | "source": [ 1094 | "import smartfunctions\n", 1095 | "print(smartfunctions.f(2)) # 5" 1096 | ] 1097 | }, 1098 | { 1099 | "cell_type": "code", 1100 | "execution_count": 51, 1101 | "metadata": {}, 1102 | "outputs": [ 1103 | { 1104 | "name": "stdout", 1105 | "output_type": "stream", 1106 | "text": [ 1107 | "0\n" 1108 | ] 1109 | } 1110 | ], 1111 | "source": [ 1112 | "from smartfunctions import g #import just this function\n", 1113 | "print(g(1)) # 0" 1114 | ] 1115 | }, 1116 | { 1117 | "cell_type": "code", 1118 | "execution_count": 52, 1119 | "metadata": {}, 1120 | "outputs": [ 1121 | { 1122 | "name": "stdout", 1123 | "output_type": "stream", 1124 | "text": [ 1125 | "1.0\n" 1126 | ] 1127 | } 1128 | ], 1129 | "source": [ 1130 | "from smartfunctions import * #import all\n", 1131 | "print(h(2)*f(2)) # 1.0" 1132 | ] 1133 | }, 1134 | { 1135 | "cell_type": "markdown", 1136 | "metadata": {}, 1137 | "source": [ 1138 | "## 1.8 Python Interpreter" 1139 | ] 1140 | }, 1141 | { 1142 | "cell_type": "code", 1143 | "execution_count": 53, 1144 | "metadata": {}, 1145 | "outputs": [], 1146 | "source": [ 1147 | "def f(x):\n", 1148 | " return y**2 \n", 1149 | "a = 3 # here both a and f are defined" 1150 | ] 1151 | }, 1152 | { 1153 | "cell_type": "markdown", 1154 | "metadata": {}, 1155 | "source": [ 1156 | "*To see the runtime error you have to uncomment the next command*" 1157 | ] 1158 | }, 1159 | { 1160 | "cell_type": "code", 1161 | "execution_count": 54, 1162 | "metadata": {}, 1163 | "outputs": [], 1164 | "source": [ 1165 | "# f(2) # error, y is not defined" 1166 | ] 1167 | }, 1168 | { 1169 | "cell_type": "markdown", 1170 | "metadata": {}, 1171 | "source": [ 1172 | "## 1.9 Summary" 1173 | ] 1174 | }, 1175 | { 1176 | "cell_type": "markdown", 1177 | "metadata": {}, 1178 | "source": [ 1179 | "*No code in this book section*" 1180 | ] 1181 | } 1182 | ], 1183 | "metadata": { 1184 | "kernelspec": { 1185 | "display_name": "Python 3", 1186 | "language": "python", 1187 | "name": "python3" 1188 | }, 1189 | "language_info": { 1190 | "codemirror_mode": { 1191 | "name": "ipython", 1192 | "version": 3 1193 | }, 1194 | "file_extension": ".py", 1195 | "mimetype": "text/x-python", 1196 | "name": "python", 1197 | "nbconvert_exporter": "python", 1198 | "pygments_lexer": "ipython3", 1199 | "version": "3.7.6" 1200 | } 1201 | }, 1202 | "nbformat": 4, 1203 | "nbformat_minor": 4 1204 | } 1205 | -------------------------------------------------------------------------------- /Chapter01/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 | -------------------------------------------------------------------------------- /Chapter05/chapter5.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Scientific Computing with Python (Second Edition)\n", 8 | "\n", 9 | "# Chapter 05\n", 10 | "\n", 11 | "*We start by importing all from Numpy. As explained in Chapter 01 the examples are written assuming this import is initially done.*\n" 12 | ] 13 | }, 14 | { 15 | "cell_type": "code", 16 | "execution_count": 1, 17 | "metadata": {}, 18 | "outputs": [], 19 | "source": [ 20 | "from numpy import *" 21 | ] 22 | }, 23 | { 24 | "cell_type": "markdown", 25 | "metadata": {}, 26 | "source": [ 27 | "## 5.1 Array views and copies\n", 28 | "### 5.1.1 Array views\n", 29 | "\n" 30 | ] 31 | }, 32 | { 33 | "cell_type": "code", 34 | "execution_count": 2, 35 | "metadata": {}, 36 | "outputs": [], 37 | "source": [ 38 | "M = array([[1.,2.],[3.,4.]])\n", 39 | "v = M[0,:] # first row of M" 40 | ] 41 | }, 42 | { 43 | "cell_type": "code", 44 | "execution_count": 3, 45 | "metadata": {}, 46 | "outputs": [ 47 | { 48 | "data": { 49 | "text/plain": [ 50 | "array([1., 0.])" 51 | ] 52 | }, 53 | "execution_count": 3, 54 | "metadata": {}, 55 | "output_type": "execute_result" 56 | } 57 | ], 58 | "source": [ 59 | "v[-1] = 0.\n", 60 | "v # array([[1.,0.]])" 61 | ] 62 | }, 63 | { 64 | "cell_type": "code", 65 | "execution_count": 4, 66 | "metadata": {}, 67 | "outputs": [ 68 | { 69 | "data": { 70 | "text/plain": [ 71 | "array([[1., 0.],\n", 72 | " [3., 4.]])" 73 | ] 74 | }, 75 | "execution_count": 4, 76 | "metadata": {}, 77 | "output_type": "execute_result" 78 | } 79 | ], 80 | "source": [ 81 | "M # array([[1.,0.],[3.,4.]]) # M is modified as well" 82 | ] 83 | }, 84 | { 85 | "cell_type": "code", 86 | "execution_count": 5, 87 | "metadata": {}, 88 | "outputs": [ 89 | { 90 | "data": { 91 | "text/plain": [ 92 | "array([[1., 0.],\n", 93 | " [3., 4.]])" 94 | ] 95 | }, 96 | "execution_count": 5, 97 | "metadata": {}, 98 | "output_type": "execute_result" 99 | } 100 | ], 101 | "source": [ 102 | "v.base # array([[1.,0.],[3.,4.]])" 103 | ] 104 | }, 105 | { 106 | "cell_type": "code", 107 | "execution_count": 6, 108 | "metadata": {}, 109 | "outputs": [ 110 | { 111 | "name": "stdout", 112 | "output_type": "stream", 113 | "text": [ 114 | "None\n" 115 | ] 116 | } 117 | ], 118 | "source": [ 119 | "print(M.base) # None" 120 | ] 121 | }, 122 | { 123 | "cell_type": "markdown", 124 | "metadata": {}, 125 | "source": [ 126 | "### 5.1.2 Slices as views" 127 | ] 128 | }, 129 | { 130 | "cell_type": "code", 131 | "execution_count": 7, 132 | "metadata": {}, 133 | "outputs": [ 134 | { 135 | "data": { 136 | "text/plain": [ 137 | "array([2, 3])" 138 | ] 139 | }, 140 | "execution_count": 7, 141 | "metadata": {}, 142 | "output_type": "execute_result" 143 | } 144 | ], 145 | "source": [ 146 | "a = arange(4) # array([0.,1.,2.,3.])\n", 147 | "b = a[[2,3]] # the index is a list [2,3]\n", 148 | "b # array([2.,3.])" 149 | ] 150 | }, 151 | { 152 | "cell_type": "code", 153 | "execution_count": 8, 154 | "metadata": {}, 155 | "outputs": [ 156 | { 157 | "data": { 158 | "text/plain": [ 159 | "True" 160 | ] 161 | }, 162 | "execution_count": 8, 163 | "metadata": {}, 164 | "output_type": "execute_result" 165 | } 166 | ], 167 | "source": [ 168 | "b.base is None # True, the data was copied" 169 | ] 170 | }, 171 | { 172 | "cell_type": "code", 173 | "execution_count": 9, 174 | "metadata": {}, 175 | "outputs": [ 176 | { 177 | "data": { 178 | "text/plain": [ 179 | "False" 180 | ] 181 | }, 182 | "execution_count": 9, 183 | "metadata": {}, 184 | "output_type": "execute_result" 185 | } 186 | ], 187 | "source": [ 188 | "c = a[1:3] \n", 189 | "c.base is None # False, this is just a view" 190 | ] 191 | }, 192 | { 193 | "cell_type": "markdown", 194 | "metadata": {}, 195 | "source": [ 196 | "### 5.1.3 Generating views by transposing and reshaping" 197 | ] 198 | }, 199 | { 200 | "cell_type": "code", 201 | "execution_count": 10, 202 | "metadata": {}, 203 | "outputs": [ 204 | { 205 | "data": { 206 | "text/plain": [ 207 | "True" 208 | ] 209 | }, 210 | "execution_count": 10, 211 | "metadata": {}, 212 | "output_type": "execute_result" 213 | } 214 | ], 215 | "source": [ 216 | "M = random.random_sample((3,3))\n", 217 | "N = M.T\n", 218 | "N.base is M # True" 219 | ] 220 | }, 221 | { 222 | "cell_type": "code", 223 | "execution_count": 11, 224 | "metadata": {}, 225 | "outputs": [ 226 | { 227 | "data": { 228 | "text/plain": [ 229 | "True" 230 | ] 231 | }, 232 | "execution_count": 11, 233 | "metadata": {}, 234 | "output_type": "execute_result" 235 | } 236 | ], 237 | "source": [ 238 | "v = arange(10)\n", 239 | "C = v.reshape(-1,1) # column matrix\n", 240 | "C.base is v # True" 241 | ] 242 | }, 243 | { 244 | "cell_type": "markdown", 245 | "metadata": {}, 246 | "source": [ 247 | "### 5.1.4 Array copies" 248 | ] 249 | }, 250 | { 251 | "cell_type": "code", 252 | "execution_count": 12, 253 | "metadata": {}, 254 | "outputs": [], 255 | "source": [ 256 | "M = array([[1.,2.],[3.,4.]])\n", 257 | "N = array(M.T) # copy of M.T" 258 | ] 259 | }, 260 | { 261 | "cell_type": "code", 262 | "execution_count": 13, 263 | "metadata": {}, 264 | "outputs": [ 265 | { 266 | "data": { 267 | "text/plain": [ 268 | "True" 269 | ] 270 | }, 271 | "execution_count": 13, 272 | "metadata": {}, 273 | "output_type": "execute_result" 274 | } 275 | ], 276 | "source": [ 277 | "N.base is None # True" 278 | ] 279 | }, 280 | { 281 | "cell_type": "markdown", 282 | "metadata": {}, 283 | "source": [ 284 | "## 5.2 Comparing arrays" 285 | ] 286 | }, 287 | { 288 | "cell_type": "code", 289 | "execution_count": 14, 290 | "metadata": { 291 | "tags": [ 292 | "raise-exceptions" 293 | ] 294 | }, 295 | "outputs": [ 296 | { 297 | "ename": "ValueError", 298 | "evalue": "The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()", 299 | "output_type": "error", 300 | "traceback": [ 301 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 302 | "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)", 303 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mA\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0marray\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0.\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m0.\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0mB\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0marray\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0.\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m0.\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0;32mif\u001b[0m \u001b[0mabs\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mB\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0mA\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m<\u001b[0m \u001b[0;36m1e-10\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;31m# an exception is raised here\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 4\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"The two arrays are close enough\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 304 | "\u001b[0;31mValueError\u001b[0m: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()" 305 | ] 306 | } 307 | ], 308 | "source": [ 309 | "A = array([0.,0.])\n", 310 | "B = array([0.,0.])\n", 311 | "if abs(B-A) < 1e-10: # an exception is raised here\n", 312 | " print(\"The two arrays are close enough\")" 313 | ] 314 | }, 315 | { 316 | "cell_type": "markdown", 317 | "metadata": {}, 318 | "source": [ 319 | "### 5.2.1 Boolean arrays" 320 | ] 321 | }, 322 | { 323 | "cell_type": "code", 324 | "execution_count": null, 325 | "metadata": {}, 326 | "outputs": [], 327 | "source": [ 328 | "A = array([True,False]) # Boolean array\n", 329 | "A.dtype # dtype('bool')" 330 | ] 331 | }, 332 | { 333 | "cell_type": "code", 334 | "execution_count": null, 335 | "metadata": {}, 336 | "outputs": [], 337 | "source": [ 338 | "M = array([[2, 3],\n", 339 | " [1, 4]])\n", 340 | "M > 2 # array([[False, True],\n", 341 | " # [False, True]])" 342 | ] 343 | }, 344 | { 345 | "cell_type": "code", 346 | "execution_count": null, 347 | "metadata": {}, 348 | "outputs": [], 349 | "source": [ 350 | "M == 0 # array([[False, False],\n", 351 | " # [False, False]])" 352 | ] 353 | }, 354 | { 355 | "cell_type": "code", 356 | "execution_count": null, 357 | "metadata": {}, 358 | "outputs": [], 359 | "source": [ 360 | "N = array([[2, 3],\n", 361 | " [0, 0]])\n", 362 | "M == N # array([[True, True],\n", 363 | " # [False, False]])" 364 | ] 365 | }, 366 | { 367 | "cell_type": "code", 368 | "execution_count": null, 369 | "metadata": {}, 370 | "outputs": [], 371 | "source": [ 372 | "A = array([[1,2],[3,4]])\n", 373 | "B = array([[1,2],[3,3]])\n", 374 | "A == B # creates array([[True, True], [True, False]]) " 375 | ] 376 | }, 377 | { 378 | "cell_type": "code", 379 | "execution_count": null, 380 | "metadata": {}, 381 | "outputs": [], 382 | "source": [ 383 | "(A == B).all() # False" 384 | ] 385 | }, 386 | { 387 | "cell_type": "code", 388 | "execution_count": null, 389 | "metadata": {}, 390 | "outputs": [], 391 | "source": [ 392 | "(A != B).any() # True" 393 | ] 394 | }, 395 | { 396 | "cell_type": "code", 397 | "execution_count": null, 398 | "metadata": {}, 399 | "outputs": [], 400 | "source": [ 401 | "if (abs(B-A) < 1e-10).all():\n", 402 | " print(\"The two arrays are close enough\")" 403 | ] 404 | }, 405 | { 406 | "cell_type": "markdown", 407 | "metadata": {}, 408 | "source": [ 409 | "### 5.2.2 Checking for array equality" 410 | ] 411 | }, 412 | { 413 | "cell_type": "code", 414 | "execution_count": null, 415 | "metadata": {}, 416 | "outputs": [], 417 | "source": [ 418 | "data = random.rand(2)*1e-3\n", 419 | "small_error = random.rand(2)*1e-16\n", 420 | "data == data + small_error # False\n", 421 | "allclose(data, data + small_error, rtol=1.e-5, atol=1.e-8) # True" 422 | ] 423 | }, 424 | { 425 | "cell_type": "code", 426 | "execution_count": null, 427 | "metadata": {}, 428 | "outputs": [], 429 | "source": [ 430 | "atol=1.e-5\n", 431 | "rtol=1.e-8\n", 432 | "(abs(A-B) < atol+rtol*abs(B)).all()" 433 | ] 434 | }, 435 | { 436 | "cell_type": "code", 437 | "execution_count": null, 438 | "metadata": {}, 439 | "outputs": [], 440 | "source": [ 441 | "data = 1e-3\n", 442 | "error = 1e-16\n", 443 | "data == data + error # False\n", 444 | "allclose(data, data + error, rtol=1.e-5, atol=1.e-8) #True" 445 | ] 446 | }, 447 | { 448 | "cell_type": "markdown", 449 | "metadata": {}, 450 | "source": [ 451 | "### 5.2.3 Boolean operations on arrays" 452 | ] 453 | }, 454 | { 455 | "cell_type": "code", 456 | "execution_count": null, 457 | "metadata": { 458 | "tags": [ 459 | "raises-exception" 460 | ] 461 | }, 462 | "outputs": [], 463 | "source": [ 464 | "A = array([True, True, False, False])\n", 465 | "B = array([True, False, True, False])\n", 466 | "A and B # error!" 467 | ] 468 | }, 469 | { 470 | "cell_type": "code", 471 | "execution_count": null, 472 | "metadata": {}, 473 | "outputs": [], 474 | "source": [ 475 | "A & B # array([True, False, False, False])" 476 | ] 477 | }, 478 | { 479 | "cell_type": "code", 480 | "execution_count": null, 481 | "metadata": {}, 482 | "outputs": [], 483 | "source": [ 484 | "A | B # array([True, True, True, False])" 485 | ] 486 | }, 487 | { 488 | "cell_type": "code", 489 | "execution_count": null, 490 | "metadata": {}, 491 | "outputs": [], 492 | "source": [ 493 | "~A # array([False, False, True, True])" 494 | ] 495 | }, 496 | { 497 | "cell_type": "code", 498 | "execution_count": null, 499 | "metadata": {}, 500 | "outputs": [], 501 | "source": [ 502 | "data = linspace(1,100,100) # data \n", 503 | "deviation = random.normal(size=100) # the deviations\n", 504 | "data = data + deviation \n", 505 | "# do not forget the parentheses in the next statement! \n", 506 | "exceptional = data[(deviation<-0.5)|(deviation>0.5)] \n", 507 | "exceptional = data[abs(deviation)>0.5] # same result \n", 508 | "small = data[(abs(deviation)<0.1)&(data<5.)] # small deviation and data" 509 | ] 510 | }, 511 | { 512 | "cell_type": "code", 513 | "execution_count": null, 514 | "metadata": {}, 515 | "outputs": [], 516 | "source": [ 517 | "exceptional, small" 518 | ] 519 | }, 520 | { 521 | "cell_type": "markdown", 522 | "metadata": {}, 523 | "source": [ 524 | "## 5.3 Array indexing\n", 525 | "### 5.3.1 Indexing with Boolean arrays" 526 | ] 527 | }, 528 | { 529 | "cell_type": "code", 530 | "execution_count": null, 531 | "metadata": {}, 532 | "outputs": [], 533 | "source": [ 534 | "B = array([[True, False],\n", 535 | " [False, True]])\n", 536 | "M = array([[2, 3],\n", 537 | " [1, 4]])\n", 538 | "M[B] # array([2,4]), a vector" 539 | ] 540 | }, 541 | { 542 | "cell_type": "code", 543 | "execution_count": null, 544 | "metadata": {}, 545 | "outputs": [], 546 | "source": [ 547 | "M[B] = 0\n", 548 | "M # [[0, 3], [1, 0]]" 549 | ] 550 | }, 551 | { 552 | "cell_type": "code", 553 | "execution_count": null, 554 | "metadata": {}, 555 | "outputs": [], 556 | "source": [ 557 | "M[B] = 10, 20\n", 558 | "M # [[10, 3], [1, 20]]" 559 | ] 560 | }, 561 | { 562 | "cell_type": "code", 563 | "execution_count": null, 564 | "metadata": {}, 565 | "outputs": [], 566 | "source": [ 567 | "M[M>2] = 0 # all the elements > 2 are replaced by 0\n", 568 | "M" 569 | ] 570 | }, 571 | { 572 | "cell_type": "markdown", 573 | "metadata": {}, 574 | "source": [ 575 | "### 5.3.2 Using the command where" 576 | ] 577 | }, 578 | { 579 | "cell_type": "code", 580 | "execution_count": null, 581 | "metadata": {}, 582 | "outputs": [], 583 | "source": [ 584 | "def H(x):\n", 585 | " return where(x < 0, 0, 1)\n", 586 | "x = linspace(-1,1,11) # [-1. -0.8 -0.6 -0.4 -0.2 0. 0.2 0.4 0.6 0.8 1. ]\n", 587 | "print(H(x)) # [0 0 0 0 0 1 1 1 1 1 1]" 588 | ] 589 | }, 590 | { 591 | "cell_type": "code", 592 | "execution_count": null, 593 | "metadata": {}, 594 | "outputs": [], 595 | "source": [ 596 | "x = linspace(-4,4,5)\n", 597 | "# [-4. -2. 0. 2. 4.]\n", 598 | "\n", 599 | "print(where(x < 0, -x, x))\n", 600 | "# [ 4., 2., 0, 2., 4.] ]\n", 601 | "print(where(x > 0, 1, -1)) # [-1 -1 -1 1 1]" 602 | ] 603 | }, 604 | { 605 | "cell_type": "code", 606 | "execution_count": null, 607 | "metadata": {}, 608 | "outputs": [], 609 | "source": [ 610 | "a = arange(9)\n", 611 | "b = a.reshape((3,3))\n", 612 | "\n", 613 | "print(where(a > 5)) # (array([6, 7, 8]),)\n", 614 | "print(where(b > 5)) # (array([2, 2, 2]), array([0, 1, 2]))" 615 | ] 616 | }, 617 | { 618 | "cell_type": "markdown", 619 | "metadata": {}, 620 | "source": [ 621 | "## 5.4 Performance and vectorization" 622 | ] 623 | }, 624 | { 625 | "cell_type": "code", 626 | "execution_count": null, 627 | "metadata": {}, 628 | "outputs": [], 629 | "source": [ 630 | "def my_prod(a,b):\n", 631 | " val = 0\n", 632 | " for aa, bb in zip(a,b):\n", 633 | " val += aa*bb\n", 634 | " return val" 635 | ] 636 | }, 637 | { 638 | "cell_type": "markdown", 639 | "metadata": {}, 640 | "source": [ 641 | "### 5.4.1 Vectorization" 642 | ] 643 | }, 644 | { 645 | "cell_type": "code", 646 | "execution_count": null, 647 | "metadata": {}, 648 | "outputs": [], 649 | "source": [ 650 | "v=arange(10)\n", 651 | "w=zeros((10,))\n", 652 | "for i in range(len(v)):\n", 653 | " w[i] = v[i] + 5\n", 654 | "w" 655 | ] 656 | }, 657 | { 658 | "cell_type": "code", 659 | "execution_count": null, 660 | "metadata": {}, 661 | "outputs": [], 662 | "source": [ 663 | "w = v + 5\n", 664 | "w" 665 | ] 666 | }, 667 | { 668 | "cell_type": "code", 669 | "execution_count": null, 670 | "metadata": {}, 671 | "outputs": [], 672 | "source": [ 673 | "def my_avg(A):\n", 674 | " m,n = A.shape\n", 675 | " B = A.copy()\n", 676 | " for i in range(1,m-1):\n", 677 | " for j in range(1,n-1):\n", 678 | " B[i,j] = (A[i-1,j] + A[i+1,j] + A[i,j-1] + A[i,j+1])/4\n", 679 | " return B\n", 680 | "\n", 681 | "def slicing_avg(A):\n", 682 | " A[1:-1,1:-1] = (A[:-2,1:-1] + A[2:,1:-1] +\n", 683 | " A[1:-1,:-2] + A[1:-1,2:])/4\n", 684 | " return A\n" 685 | ] 686 | }, 687 | { 688 | "cell_type": "code", 689 | "execution_count": null, 690 | "metadata": {}, 691 | "outputs": [], 692 | "source": [ 693 | "def my_func(x):\n", 694 | " y = x**3 - 2*x + 5\n", 695 | " if y>0.5:\n", 696 | " return y-0.5\n", 697 | " else:\n", 698 | " return 0" 699 | ] 700 | }, 701 | { 702 | "cell_type": "code", 703 | "execution_count": null, 704 | "metadata": {}, 705 | "outputs": [], 706 | "source": [ 707 | "[my_func(vk) for vk in v]" 708 | ] 709 | }, 710 | { 711 | "cell_type": "code", 712 | "execution_count": null, 713 | "metadata": {}, 714 | "outputs": [], 715 | "source": [ 716 | "vectorize(my_func)(v)" 717 | ] 718 | }, 719 | { 720 | "cell_type": "markdown", 721 | "metadata": {}, 722 | "source": [ 723 | "## 5.5 Broadcasting\n", 724 | "### 5.5.1 Mathematical views\n" 725 | ] 726 | }, 727 | { 728 | "cell_type": "code", 729 | "execution_count": null, 730 | "metadata": {}, 731 | "outputs": [], 732 | "source": [ 733 | "vector = arange(4) # array([0.,1.,2.,3.])\n", 734 | "vector + 1. # array([1.,2.,3.,4.])" 735 | ] 736 | }, 737 | { 738 | "cell_type": "code", 739 | "execution_count": null, 740 | "metadata": {}, 741 | "outputs": [], 742 | "source": [ 743 | "C = arange(2).reshape(-1,1) # column\n", 744 | "R = arange(2).reshape(1,-1) # row\n", 745 | "C + R # valid addition: array([[0.,1.],[1.,2.]])" 746 | ] 747 | }, 748 | { 749 | "cell_type": "markdown", 750 | "metadata": {}, 751 | "source": [ 752 | "### 5.5.2 Broadcasting arrays" 753 | ] 754 | }, 755 | { 756 | "cell_type": "code", 757 | "execution_count": null, 758 | "metadata": {}, 759 | "outputs": [], 760 | "source": [ 761 | "M = array([[11, 12, 13, 14],\n", 762 | " [21, 22, 23, 24],\n", 763 | " [31, 32, 33, 34]])\n", 764 | "v = array([100, 200, 300, 400])\n", 765 | "M + v # works directly\n", 766 | "\n" 767 | ] 768 | }, 769 | { 770 | "cell_type": "code", 771 | "execution_count": null, 772 | "metadata": { 773 | "tags": [ 774 | "raises-exception" 775 | ] 776 | }, 777 | "outputs": [], 778 | "source": [ 779 | "M + v.reshape(-1,1)" 780 | ] 781 | }, 782 | { 783 | "cell_type": "code", 784 | "execution_count": null, 785 | "metadata": { 786 | "tags": [ 787 | "raises-exception" 788 | ] 789 | }, 790 | "outputs": [], 791 | "source": [ 792 | "M = array([[11, 12, 13, 14],\n", 793 | " [21, 22, 23, 24],\n", 794 | " [31, 32, 33, 34]])\n", 795 | "v = array([100, 200, 300])\n", 796 | "M+v" 797 | ] 798 | }, 799 | { 800 | "cell_type": "code", 801 | "execution_count": null, 802 | "metadata": {}, 803 | "outputs": [], 804 | "source": [ 805 | "M + v.reshape(-1,1)" 806 | ] 807 | }, 808 | { 809 | "cell_type": "markdown", 810 | "metadata": {}, 811 | "source": [ 812 | "### 5.5.3 Typical examples" 813 | ] 814 | }, 815 | { 816 | "cell_type": "code", 817 | "execution_count": null, 818 | "metadata": {}, 819 | "outputs": [], 820 | "source": [ 821 | "coeff=array([-1,-2,-3]).reshape(-1,1)\n", 822 | "M*coeff" 823 | ] 824 | }, 825 | { 826 | "cell_type": "code", 827 | "execution_count": null, 828 | "metadata": {}, 829 | "outputs": [], 830 | "source": [ 831 | "coeff=array([-1,-2,-3,-4])\n", 832 | "M*coeff" 833 | ] 834 | }, 835 | { 836 | "cell_type": "code", 837 | "execution_count": null, 838 | "metadata": {}, 839 | "outputs": [], 840 | "source": [ 841 | "u=array([1, 2])\n", 842 | "v=array([1, 2, 3])\n", 843 | "W=u.reshape(-1,1) + v\n", 844 | "W" 845 | ] 846 | }, 847 | { 848 | "cell_type": "code", 849 | "execution_count": null, 850 | "metadata": {}, 851 | "outputs": [], 852 | "source": [ 853 | "x,y = ogrid[0:1:3j,0:1:3j] \n", 854 | "# x,y are vectors with the contents of linspace(0,1,3)\n", 855 | "w = cos(x) + sin(2*y)\n", 856 | "w" 857 | ] 858 | }, 859 | { 860 | "cell_type": "code", 861 | "execution_count": null, 862 | "metadata": {}, 863 | "outputs": [], 864 | "source": [ 865 | "x,y = ogrid[0:1:3j, 0:1:3j]\n", 866 | "x, y" 867 | ] 868 | }, 869 | { 870 | "cell_type": "code", 871 | "execution_count": null, 872 | "metadata": {}, 873 | "outputs": [], 874 | "source": [ 875 | "x, y = ogrid.__getitem__((slice(0, 1, 3j),slice(0, 1, 3j)))\n", 876 | "x, y " 877 | ] 878 | }, 879 | { 880 | "cell_type": "markdown", 881 | "metadata": {}, 882 | "source": [ 883 | "## 5.6. Sparse matrices\n", 884 | "### 5.6.1 Sparse matrix formats" 885 | ] 886 | }, 887 | { 888 | "cell_type": "code", 889 | "execution_count": null, 890 | "metadata": {}, 891 | "outputs": [], 892 | "source": [ 893 | "import scipy.sparse as sp\n", 894 | "A = array([[1,0,2,0],[0,0,0,0],[3.,0.,0.,0.],[1.,0.,0.,4.]])\n", 895 | "AS = sp.csr_matrix(A)" 896 | ] 897 | }, 898 | { 899 | "cell_type": "code", 900 | "execution_count": null, 901 | "metadata": {}, 902 | "outputs": [], 903 | "source": [ 904 | "AS.data" 905 | ] 906 | }, 907 | { 908 | "cell_type": "code", 909 | "execution_count": null, 910 | "metadata": {}, 911 | "outputs": [], 912 | "source": [ 913 | "AS.indptr" 914 | ] 915 | }, 916 | { 917 | "cell_type": "code", 918 | "execution_count": null, 919 | "metadata": {}, 920 | "outputs": [], 921 | "source": [ 922 | "AS.indices" 923 | ] 924 | }, 925 | { 926 | "cell_type": "code", 927 | "execution_count": null, 928 | "metadata": {}, 929 | "outputs": [], 930 | "source": [ 931 | "AS.nnz" 932 | ] 933 | }, 934 | { 935 | "cell_type": "code", 936 | "execution_count": null, 937 | "metadata": {}, 938 | "outputs": [], 939 | "source": [ 940 | "import scipy.sparse as sp\n", 941 | "A = array([[1,0,2,0],[0,0,0,0],[3.,0.,0.,0.],[1.,0.,0.,4.]])\n", 942 | "AS = sp.csc_matrix(A)\n", 943 | "AS.data # returns array([ 1., 3., 1., 2., 4.]) " 944 | ] 945 | }, 946 | { 947 | "cell_type": "code", 948 | "execution_count": null, 949 | "metadata": {}, 950 | "outputs": [], 951 | "source": [ 952 | "AS.indptr # returns array([0, 3, 3, 4, 5])" 953 | ] 954 | }, 955 | { 956 | "cell_type": "code", 957 | "execution_count": null, 958 | "metadata": {}, 959 | "outputs": [], 960 | "source": [ 961 | "AS.indices # returns array([0, 2, 3, 0, 3])" 962 | ] 963 | }, 964 | { 965 | "cell_type": "code", 966 | "execution_count": null, 967 | "metadata": {}, 968 | "outputs": [], 969 | "source": [ 970 | "AS.nnz # returns 5" 971 | ] 972 | }, 973 | { 974 | "cell_type": "code", 975 | "execution_count": 15, 976 | "metadata": {}, 977 | "outputs": [], 978 | "source": [ 979 | "import scipy.sparse as sp\n", 980 | "A = array([[1,0,2,0],[0,0,0,0], [3.,0.,0.,0.], [1.,0.,0.,4.]]) \n", 981 | "AS = sp.lil_matrix(A)" 982 | ] 983 | }, 984 | { 985 | "cell_type": "code", 986 | "execution_count": 16, 987 | "metadata": {}, 988 | "outputs": [ 989 | { 990 | "data": { 991 | "text/plain": [ 992 | "array([list([1.0, 2.0]), list([]), list([3.0]), list([1.0, 4.0])],\n", 993 | " dtype=object)" 994 | ] 995 | }, 996 | "execution_count": 16, 997 | "metadata": {}, 998 | "output_type": "execute_result" 999 | } 1000 | ], 1001 | "source": [ 1002 | "AS.data # returns array([[1.0, 2.0], [], [3.0], [1.0, 4.0]], dtype=object)" 1003 | ] 1004 | }, 1005 | { 1006 | "cell_type": "code", 1007 | "execution_count": 17, 1008 | "metadata": {}, 1009 | "outputs": [ 1010 | { 1011 | "data": { 1012 | "text/plain": [ 1013 | "array([list([0, 2]), list([]), list([0]), list([0, 3])], dtype=object)" 1014 | ] 1015 | }, 1016 | "execution_count": 17, 1017 | "metadata": {}, 1018 | "output_type": "execute_result" 1019 | } 1020 | ], 1021 | "source": [ 1022 | "AS.rows # returns array([[0, 2], [], [0], [0, 3]], dtype=object)" 1023 | ] 1024 | }, 1025 | { 1026 | "cell_type": "code", 1027 | "execution_count": 18, 1028 | "metadata": {}, 1029 | "outputs": [ 1030 | { 1031 | "data": { 1032 | "text/plain": [ 1033 | "5" 1034 | ] 1035 | }, 1036 | "execution_count": 18, 1037 | "metadata": {}, 1038 | "output_type": "execute_result" 1039 | } 1040 | ], 1041 | "source": [ 1042 | "AS.nnz # returns 5" 1043 | ] 1044 | }, 1045 | { 1046 | "cell_type": "code", 1047 | "execution_count": 19, 1048 | "metadata": {}, 1049 | "outputs": [ 1050 | { 1051 | "data": { 1052 | "text/plain": [ 1053 | "array([list([]), list([3.0])], dtype=object)" 1054 | ] 1055 | }, 1056 | "execution_count": 19, 1057 | "metadata": {}, 1058 | "output_type": "execute_result" 1059 | } 1060 | ], 1061 | "source": [ 1062 | "BS = AS[1:3,0:2]\n", 1063 | "BS.data # returns array([[], [3.0]], dtype=object)" 1064 | ] 1065 | }, 1066 | { 1067 | "cell_type": "code", 1068 | "execution_count": 20, 1069 | "metadata": {}, 1070 | "outputs": [ 1071 | { 1072 | "data": { 1073 | "text/plain": [ 1074 | "array([list([]), list([0])], dtype=object)" 1075 | ] 1076 | }, 1077 | "execution_count": 20, 1078 | "metadata": {}, 1079 | "output_type": "execute_result" 1080 | } 1081 | ], 1082 | "source": [ 1083 | "BS.rows # returns array([[], [0]], dtype=object)" 1084 | ] 1085 | }, 1086 | { 1087 | "cell_type": "code", 1088 | "execution_count": 21, 1089 | "metadata": {}, 1090 | "outputs": [ 1091 | { 1092 | "data": { 1093 | "text/plain": [ 1094 | "array([list([1.0, 17.0, 2.0]), list([]), list([3.0]), list([1.0, 4.0])],\n", 1095 | " dtype=object)" 1096 | ] 1097 | }, 1098 | "execution_count": 21, 1099 | "metadata": {}, 1100 | "output_type": "execute_result" 1101 | } 1102 | ], 1103 | "source": [ 1104 | "AS[0,1] = 17 \n", 1105 | "AS.data # returns array([[1.0, 17.0, 2.0], [], [3.0], [1.0, 4.0]])" 1106 | ] 1107 | }, 1108 | { 1109 | "cell_type": "code", 1110 | "execution_count": 22, 1111 | "metadata": {}, 1112 | "outputs": [ 1113 | { 1114 | "data": { 1115 | "text/plain": [ 1116 | "array([list([0, 1, 2]), list([]), list([0]), list([0, 3])], dtype=object)" 1117 | ] 1118 | }, 1119 | "execution_count": 22, 1120 | "metadata": {}, 1121 | "output_type": "execute_result" 1122 | } 1123 | ], 1124 | "source": [ 1125 | "AS.rows # returns array([[0, 1, 2], [], [0], [0, 3]])" 1126 | ] 1127 | }, 1128 | { 1129 | "cell_type": "code", 1130 | "execution_count": 23, 1131 | "metadata": {}, 1132 | "outputs": [ 1133 | { 1134 | "data": { 1135 | "text/plain": [ 1136 | "6" 1137 | ] 1138 | }, 1139 | "execution_count": 23, 1140 | "metadata": {}, 1141 | "output_type": "execute_result" 1142 | } 1143 | ], 1144 | "source": [ 1145 | "AS.nnz # returns 6" 1146 | ] 1147 | }, 1148 | { 1149 | "cell_type": "markdown", 1150 | "metadata": {}, 1151 | "source": [ 1152 | "### 5.6.2 Generating sparse matrices" 1153 | ] 1154 | }, 1155 | { 1156 | "cell_type": "code", 1157 | "execution_count": 24, 1158 | "metadata": {}, 1159 | "outputs": [ 1160 | { 1161 | "data": { 1162 | "text/plain": [ 1163 | "<20x20 sparse matrix of type ''\n", 1164 | "\twith 20 stored elements in Compressed Sparse Column format>" 1165 | ] 1166 | }, 1167 | "execution_count": 24, 1168 | "metadata": {}, 1169 | "output_type": "execute_result" 1170 | } 1171 | ], 1172 | "source": [ 1173 | "import scipy.sparse as sp\n", 1174 | "sp.eye(20,20,format = 'lil') \n", 1175 | "sp.spdiags(ones((20,)),0,20,20, format = 'csr') \n", 1176 | "sp.identity(20,format ='csc')" 1177 | ] 1178 | }, 1179 | { 1180 | "cell_type": "code", 1181 | "execution_count": 25, 1182 | "metadata": {}, 1183 | "outputs": [ 1184 | { 1185 | "data": { 1186 | "text/plain": [ 1187 | "400" 1188 | ] 1189 | }, 1190 | "execution_count": 25, 1191 | "metadata": {}, 1192 | "output_type": "execute_result" 1193 | } 1194 | ], 1195 | "source": [ 1196 | "import scipy.sparse as sp \n", 1197 | "AS=sp.rand(20,200,density=0.1,format='csr')\n", 1198 | "AS.nnz # returns 400" 1199 | ] 1200 | }, 1201 | { 1202 | "cell_type": "code", 1203 | "execution_count": 26, 1204 | "metadata": {}, 1205 | "outputs": [ 1206 | { 1207 | "data": { 1208 | "text/plain": [ 1209 | "0" 1210 | ] 1211 | }, 1212 | "execution_count": 26, 1213 | "metadata": {}, 1214 | "output_type": "execute_result" 1215 | } 1216 | ], 1217 | "source": [ 1218 | "import scipy.sparse as sp\n", 1219 | "Z=sp.csr_matrix((20,200))\n", 1220 | "Z.nnz # returns 0" 1221 | ] 1222 | }, 1223 | { 1224 | "cell_type": "markdown", 1225 | "metadata": {}, 1226 | "source": [ 1227 | "### 5.6.3 Sparse matrix methods" 1228 | ] 1229 | }, 1230 | { 1231 | "cell_type": "code", 1232 | "execution_count": 27, 1233 | "metadata": {}, 1234 | "outputs": [ 1235 | { 1236 | "data": { 1237 | "text/plain": [ 1238 | "'\n", 1239 | "\twith 400 stored elements in Compressed Sparse Row format>>" 1240 | ] 1241 | }, 1242 | "execution_count": 27, 1243 | "metadata": {}, 1244 | "output_type": "execute_result" 1245 | } 1246 | ], 1247 | "source": [ 1248 | "AS.toarray # converts sparse formats to a numpy array \n", 1249 | "AS.tocsr\n", 1250 | "AS.tocsc\n", 1251 | "AS.tolil" 1252 | ] 1253 | }, 1254 | { 1255 | "cell_type": "code", 1256 | "execution_count": 28, 1257 | "metadata": {}, 1258 | "outputs": [], 1259 | "source": [ 1260 | "import scipy.sparse as sp\n", 1261 | "def sparse_sin(A):\n", 1262 | " if not (sp.isspmatrix_csr(A) or sp.isspmatrix_csc(A)):\n", 1263 | " A = A.tocsr()\n", 1264 | " A.data = sin(A.data)\n", 1265 | " return A" 1266 | ] 1267 | }, 1268 | { 1269 | "cell_type": "code", 1270 | "execution_count": 29, 1271 | "metadata": {}, 1272 | "outputs": [ 1273 | { 1274 | "data": { 1275 | "text/plain": [ 1276 | "array([ 7., 0., 3., 17.])" 1277 | ] 1278 | }, 1279 | "execution_count": 29, 1280 | "metadata": {}, 1281 | "output_type": "execute_result" 1282 | } 1283 | ], 1284 | "source": [ 1285 | "import scipy.sparse as sp\n", 1286 | "A = array([[1,0,2,0],[0,0,0,0],[3.,0.,0.,0.],[1.,0.,0.,4.]])\n", 1287 | "AS = sp.csr_matrix(A)\n", 1288 | "b = array([1,2,3,4])\n", 1289 | "c = AS.dot(b) # returns array([ 7., 0., 3., 17.])\n", 1290 | "c" 1291 | ] 1292 | }, 1293 | { 1294 | "cell_type": "code", 1295 | "execution_count": 30, 1296 | "metadata": {}, 1297 | "outputs": [ 1298 | { 1299 | "data": { 1300 | "text/plain": [ 1301 | "array([<4x4 sparse matrix of type ''\n", 1302 | "\twith 5 stored elements in Compressed Sparse Row format>,\n", 1303 | " <4x4 sparse matrix of type ''\n", 1304 | "\twith 5 stored elements in Compressed Sparse Row format>,\n", 1305 | " <4x4 sparse matrix of type ''\n", 1306 | "\twith 5 stored elements in Compressed Sparse Row format>,\n", 1307 | " <4x4 sparse matrix of type ''\n", 1308 | "\twith 5 stored elements in Compressed Sparse Row format>], dtype=object)" 1309 | ] 1310 | }, 1311 | "execution_count": 30, 1312 | "metadata": {}, 1313 | "output_type": "execute_result" 1314 | } 1315 | ], 1316 | "source": [ 1317 | "C = AS.dot(AS) # returns csr_matrix\n", 1318 | "d = dot(AS,b) # does not return the expected result!\n", 1319 | "d" 1320 | ] 1321 | } 1322 | ], 1323 | "metadata": { 1324 | "celltoolbar": "Tags", 1325 | "kernelspec": { 1326 | "display_name": "Python 3", 1327 | "language": "python", 1328 | "name": "python3" 1329 | }, 1330 | "language_info": { 1331 | "codemirror_mode": { 1332 | "name": "ipython", 1333 | "version": 3 1334 | }, 1335 | "file_extension": ".py", 1336 | "mimetype": "text/x-python", 1337 | "name": "python", 1338 | "nbconvert_exporter": "python", 1339 | "pygments_lexer": "ipython3", 1340 | "version": "3.7.6" 1341 | } 1342 | }, 1343 | "nbformat": 4, 1344 | "nbformat_minor": 4 1345 | } 1346 | -------------------------------------------------------------------------------- /Chapter09/chapter09.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Scientific Computing with Python (Second Edition)\n", 8 | "# Chapter 09\n", 9 | "\n", 10 | "*We start by importing all from Numpy. As explained in Chapter 01 the examples are written assuming this import is initially done.*\n" 11 | ] 12 | }, 13 | { 14 | "cell_type": "code", 15 | "execution_count": 1, 16 | "metadata": {}, 17 | "outputs": [], 18 | "source": [ 19 | "from numpy import *" 20 | ] 21 | }, 22 | { 23 | "cell_type": "markdown", 24 | "metadata": {}, 25 | "source": [ 26 | "## 9.1 The for statement" 27 | ] 28 | }, 29 | { 30 | "cell_type": "code", 31 | "execution_count": 3, 32 | "metadata": {}, 33 | "outputs": [ 34 | { 35 | "name": "stdout", 36 | "output_type": "stream", 37 | "text": [ 38 | "a\n", 39 | "b\n", 40 | "c\n" 41 | ] 42 | } 43 | ], 44 | "source": [ 45 | "for s in ['a', 'b', 'c']:\n", 46 | " print(s) # a b c" 47 | ] 48 | }, 49 | { 50 | "cell_type": "code", 51 | "execution_count": 4, 52 | "metadata": {}, 53 | "outputs": [ 54 | { 55 | "name": "stdout", 56 | "output_type": "stream", 57 | "text": [ 58 | "(0, 0) 1.0\n", 59 | "(0, 1) 1.0\n", 60 | "(0, 2) 1.0\n", 61 | "(0, 3) 1.0\n", 62 | "(0, 4) 1.0\n", 63 | "(1, 0) 1.0\n", 64 | "(1, 1) 1.0\n", 65 | "(1, 2) 1.0\n", 66 | "(1, 3) 1.0\n", 67 | "(1, 4) 1.0\n", 68 | "(2, 0) 1.0\n", 69 | "(2, 1) 1.0\n", 70 | "(2, 2) 1.0\n", 71 | "(2, 3) 1.0\n", 72 | "(2, 4) 1.0\n" 73 | ] 74 | } 75 | ], 76 | "source": [ 77 | "a=ones((3,5))\n", 78 | "for k,el in ndenumerate(a):\n", 79 | " print(k,el) \n", 80 | "# prints something like this: (1, 3) 1.0" 81 | ] 82 | }, 83 | { 84 | "cell_type": "markdown", 85 | "metadata": {}, 86 | "source": [ 87 | "## 9.2 Controlling the flow inside the loop" 88 | ] 89 | }, 90 | { 91 | "cell_type": "markdown", 92 | "metadata": {}, 93 | "source": [ 94 | "*We prepare here the next code example from the book.*" 95 | ] 96 | }, 97 | { 98 | "cell_type": "code", 99 | "execution_count": 6, 100 | "metadata": {}, 101 | "outputs": [], 102 | "source": [ 103 | "def compute():\n", 104 | " return 1.e-5\n", 105 | "tolerance = 1.e-3" 106 | ] 107 | }, 108 | { 109 | "cell_type": "code", 110 | "execution_count": 7, 111 | "metadata": {}, 112 | "outputs": [ 113 | { 114 | "name": "stdout", 115 | "output_type": "stream", 116 | "text": [ 117 | "The algorithm converged in 1 steps\n" 118 | ] 119 | } 120 | ], 121 | "source": [ 122 | "maxIteration = 10000\n", 123 | "for iteration in range(maxIteration):\n", 124 | " residual = compute() # some computation\n", 125 | " if residual < tolerance:\n", 126 | " break\n", 127 | "else: # only executed if the for loop is not broken\n", 128 | " raise Exception(\"The algorithm did not converge\")\n", 129 | "print(f\"The algorithm converged in {iteration + 1} steps\")" 130 | ] 131 | }, 132 | { 133 | "cell_type": "markdown", 134 | "metadata": {}, 135 | "source": [ 136 | "## 9.3 Iterable objects" 137 | ] 138 | }, 139 | { 140 | "cell_type": "code", 141 | "execution_count": 8, 142 | "metadata": {}, 143 | "outputs": [], 144 | "source": [ 145 | "l=[1,2] \n", 146 | "li=l.__iter__() " 147 | ] 148 | }, 149 | { 150 | "cell_type": "code", 151 | "execution_count": 9, 152 | "metadata": {}, 153 | "outputs": [ 154 | { 155 | "data": { 156 | "text/plain": [ 157 | "1" 158 | ] 159 | }, 160 | "execution_count": 9, 161 | "metadata": {}, 162 | "output_type": "execute_result" 163 | } 164 | ], 165 | "source": [ 166 | "li.__next__() # returns 1 " 167 | ] 168 | }, 169 | { 170 | "cell_type": "code", 171 | "execution_count": 10, 172 | "metadata": {}, 173 | "outputs": [ 174 | { 175 | "data": { 176 | "text/plain": [ 177 | "2" 178 | ] 179 | }, 180 | "execution_count": 10, 181 | "metadata": {}, 182 | "output_type": "execute_result" 183 | } 184 | ], 185 | "source": [ 186 | "li.__next__() # returns 2 " 187 | ] 188 | }, 189 | { 190 | "cell_type": "markdown", 191 | "metadata": {}, 192 | "source": [ 193 | "*Uncomment the next line to see the exception*" 194 | ] 195 | }, 196 | { 197 | "cell_type": "code", 198 | "execution_count": 12, 199 | "metadata": {}, 200 | "outputs": [], 201 | "source": [ 202 | "# li.__next__() # raises StopIteration exception " 203 | ] 204 | }, 205 | { 206 | "cell_type": "markdown", 207 | "metadata": {}, 208 | "source": [ 209 | "### 9.3.1 Generators" 210 | ] 211 | }, 212 | { 213 | "cell_type": "code", 214 | "execution_count": 13, 215 | "metadata": {}, 216 | "outputs": [], 217 | "source": [ 218 | "def odd_numbers(n): \n", 219 | " \"generator for odd numbers less than n\" \n", 220 | " for k in range(n): \n", 221 | " if k % 2 == 1: \n", 222 | " yield k" 223 | ] 224 | }, 225 | { 226 | "cell_type": "code", 227 | "execution_count": 14, 228 | "metadata": {}, 229 | "outputs": [ 230 | { 231 | "name": "stdout", 232 | "output_type": "stream", 233 | "text": [ 234 | "1\n", 235 | "3\n", 236 | "5\n", 237 | "7\n", 238 | "9\n" 239 | ] 240 | } 241 | ], 242 | "source": [ 243 | "g = odd_numbers(10)\n", 244 | "for k in g:\n", 245 | " ... # do something with k\n", 246 | " print(k)" 247 | ] 248 | }, 249 | { 250 | "cell_type": "code", 251 | "execution_count": 15, 252 | "metadata": {}, 253 | "outputs": [ 254 | { 255 | "name": "stdout", 256 | "output_type": "stream", 257 | "text": [ 258 | "1\n", 259 | "3\n", 260 | "5\n", 261 | "7\n", 262 | "9\n" 263 | ] 264 | } 265 | ], 266 | "source": [ 267 | "for k in odd_numbers(10):\n", 268 | " ... # do something with k\n", 269 | " print(k)" 270 | ] 271 | }, 272 | { 273 | "cell_type": "markdown", 274 | "metadata": {}, 275 | "source": [ 276 | "### 9.3.2 Iterators are disposable" 277 | ] 278 | }, 279 | { 280 | "cell_type": "code", 281 | "execution_count": 17, 282 | "metadata": {}, 283 | "outputs": [ 284 | { 285 | "data": { 286 | "text/plain": [ 287 | "[]" 288 | ] 289 | }, 290 | "execution_count": 17, 291 | "metadata": {}, 292 | "output_type": "execute_result" 293 | } 294 | ], 295 | "source": [ 296 | "L = ['a', 'b', 'c']\n", 297 | "iterator = iter(L)\n", 298 | "list(iterator) # ['a', 'b', 'c']\n", 299 | "list(iterator) # [] empty list, because the iterator is exhausted" 300 | ] 301 | }, 302 | { 303 | "cell_type": "code", 304 | "execution_count": 18, 305 | "metadata": {}, 306 | "outputs": [ 307 | { 308 | "data": { 309 | "text/plain": [ 310 | "['a', 'b', 'c']" 311 | ] 312 | }, 313 | "execution_count": 18, 314 | "metadata": {}, 315 | "output_type": "execute_result" 316 | } 317 | ], 318 | "source": [ 319 | "new_iterator = iter(L) # new iterator, ready to be used\n", 320 | "list(new_iterator) # ['a', 'b', 'c']" 321 | ] 322 | }, 323 | { 324 | "cell_type": "code", 325 | "execution_count": 19, 326 | "metadata": {}, 327 | "outputs": [ 328 | { 329 | "name": "stdout", 330 | "output_type": "stream", 331 | "text": [ 332 | "1\n", 333 | "3\n", 334 | "5\n", 335 | "7\n", 336 | "9\n" 337 | ] 338 | } 339 | ], 340 | "source": [ 341 | "g = odd_numbers(10)\n", 342 | "for k in g:\n", 343 | " ... # do something with k\n", 344 | " print(k)" 345 | ] 346 | }, 347 | { 348 | "cell_type": "code", 349 | "execution_count": 20, 350 | "metadata": {}, 351 | "outputs": [], 352 | "source": [ 353 | "# now the iterator is exhausted:\n", 354 | "for k in g: # nothing will happen!!\n", 355 | " ...\n", 356 | " print(k)" 357 | ] 358 | }, 359 | { 360 | "cell_type": "code", 361 | "execution_count": 22, 362 | "metadata": {}, 363 | "outputs": [ 364 | { 365 | "name": "stdout", 366 | "output_type": "stream", 367 | "text": [ 368 | "1\n", 369 | "3\n", 370 | "5\n", 371 | "7\n", 372 | "9\n" 373 | ] 374 | } 375 | ], 376 | "source": [ 377 | "# to loop through it again, create a new one:\n", 378 | "g = odd_numbers(10)\n", 379 | "for k in g:\n", 380 | " ...\n", 381 | " print(k)" 382 | ] 383 | }, 384 | { 385 | "cell_type": "markdown", 386 | "metadata": {}, 387 | "source": [ 388 | "### 9.3.3 Iterator tools" 389 | ] 390 | }, 391 | { 392 | "cell_type": "code", 393 | "execution_count": 23, 394 | "metadata": {}, 395 | "outputs": [ 396 | { 397 | "name": "stdout", 398 | "output_type": "stream", 399 | "text": [ 400 | "0 a\n", 401 | "1 b\n", 402 | "2 c\n" 403 | ] 404 | } 405 | ], 406 | "source": [ 407 | "A = ['a', 'b', 'c']\n", 408 | "for iteration, x in enumerate(A):\n", 409 | " print(iteration, x) # result: (0, 'a') (1, 'b') (2, 'c')" 410 | ] 411 | }, 412 | { 413 | "cell_type": "code", 414 | "execution_count": 25, 415 | "metadata": {}, 416 | "outputs": [ 417 | { 418 | "name": "stdout", 419 | "output_type": "stream", 420 | "text": [ 421 | "2\n", 422 | "1\n", 423 | "0\n" 424 | ] 425 | } 426 | ], 427 | "source": [ 428 | "A = [0, 1, 2]\n", 429 | "for elt in reversed(A):\n", 430 | " print(elt) # result: 2 1 0" 431 | ] 432 | }, 433 | { 434 | "cell_type": "code", 435 | "execution_count": 26, 436 | "metadata": {}, 437 | "outputs": [], 438 | "source": [ 439 | "import itertools" 440 | ] 441 | }, 442 | { 443 | "cell_type": "code", 444 | "execution_count": 27, 445 | "metadata": {}, 446 | "outputs": [], 447 | "source": [ 448 | "for iteration in itertools.count():\n", 449 | " if iteration > 100:\n", 450 | " break # without this, the loop goes on forever\n", 451 | " print(f'integer: {iteration}')\n", 452 | " # prints the 100 first integer" 453 | ] 454 | }, 455 | { 456 | "cell_type": "code", 457 | "execution_count": 28, 458 | "metadata": {}, 459 | "outputs": [ 460 | { 461 | "name": "stdout", 462 | "output_type": "stream", 463 | "text": [ 464 | "0\n", 465 | "1\n", 466 | "2\n", 467 | "3\n", 468 | "4\n", 469 | "5\n", 470 | "6\n", 471 | "7\n", 472 | "8\n", 473 | "9\n" 474 | ] 475 | } 476 | ], 477 | "source": [ 478 | "from itertools import count, islice\n", 479 | "for iteration in islice(count(), 10): \n", 480 | " # same effect as range(10)\n", 481 | " print (iteration)" 482 | ] 483 | }, 484 | { 485 | "cell_type": "code", 486 | "execution_count": 29, 487 | "metadata": {}, 488 | "outputs": [ 489 | { 490 | "data": { 491 | "text/plain": [ 492 | "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]" 493 | ] 494 | }, 495 | "execution_count": 29, 496 | "metadata": {}, 497 | "output_type": "execute_result" 498 | } 499 | ], 500 | "source": [ 501 | "list(islice(count(), 10))" 502 | ] 503 | }, 504 | { 505 | "cell_type": "code", 506 | "execution_count": 31, 507 | "metadata": {}, 508 | "outputs": [], 509 | "source": [ 510 | "def odd_numbers():\n", 511 | " k=-1\n", 512 | " while True: # this makes it an infinite generator\n", 513 | " k+=1\n", 514 | " if k%2==1:\n", 515 | " yield k" 516 | ] 517 | }, 518 | { 519 | "cell_type": "code", 520 | "execution_count": 32, 521 | "metadata": {}, 522 | "outputs": [ 523 | { 524 | "data": { 525 | "text/plain": [ 526 | "[21, 37, 53]" 527 | ] 528 | }, 529 | "execution_count": 32, 530 | "metadata": {}, 531 | "output_type": "execute_result" 532 | } 533 | ], 534 | "source": [ 535 | "list(itertools.islice(odd_numbers(),10,30,8)) \n", 536 | "# returns [21, 37, 53]" 537 | ] 538 | }, 539 | { 540 | "cell_type": "markdown", 541 | "metadata": {}, 542 | "source": [ 543 | "### 9.3.4 Generators of recursive sequences\n" 544 | ] 545 | }, 546 | { 547 | "cell_type": "code", 548 | "execution_count": 33, 549 | "metadata": {}, 550 | "outputs": [], 551 | "source": [ 552 | "def fibonacci(u0, u1):\n", 553 | " \"\"\"\n", 554 | " Infinite generator of the Fibonacci sequence.\n", 555 | " \"\"\"\n", 556 | " yield u0\n", 557 | " yield u1\n", 558 | " while True:\n", 559 | " u0, u1 = u1, u1 + u0 \n", 560 | " # we shifted the elements and compute the new one\n", 561 | " yield u1" 562 | ] 563 | }, 564 | { 565 | "cell_type": "code", 566 | "execution_count": 35, 567 | "metadata": {}, 568 | "outputs": [ 569 | { 570 | "data": { 571 | "text/plain": [ 572 | "[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]" 573 | ] 574 | }, 575 | "execution_count": 35, 576 | "metadata": {}, 577 | "output_type": "execute_result" 578 | } 579 | ], 580 | "source": [ 581 | "# sequence of the 10 first Fibonacci numbers:\n", 582 | "list(itertools.islice(fibonacci(0, 1), 10))" 583 | ] 584 | }, 585 | { 586 | "cell_type": "code", 587 | "execution_count": 36, 588 | "metadata": {}, 589 | "outputs": [], 590 | "source": [ 591 | "def arithmetic_geometric_mean(a, b):\n", 592 | " \"\"\"\n", 593 | " Generator for the arithmetic and geometric mean\n", 594 | " a, b initial values\n", 595 | " \"\"\" \n", 596 | " while True: # infinite loop\n", 597 | " a, b = (a+b)/2, sqrt(a*b)\n", 598 | " yield a, b" 599 | ] 600 | }, 601 | { 602 | "cell_type": "code", 603 | "execution_count": 37, 604 | "metadata": {}, 605 | "outputs": [], 606 | "source": [ 607 | "def elliptic_integral(k, tolerance=1.e-5):\n", 608 | " \"\"\"\n", 609 | " Compute an elliptic integral of the first kind.\n", 610 | " \"\"\"\n", 611 | " a_0, b_0 = 1., sqrt(1-k**2)\n", 612 | " for a, b in arithmetic_geometric_mean(a_0, b_0):\n", 613 | " if abs(a-b) < tolerance:\n", 614 | " return pi/(2*a)" 615 | ] 616 | }, 617 | { 618 | "cell_type": "code", 619 | "execution_count": 38, 620 | "metadata": {}, 621 | "outputs": [], 622 | "source": [ 623 | "from itertools import islice\n", 624 | "def elliptic_integral(k, tolerance=1e-5, maxiter=100):\n", 625 | " \"\"\"\n", 626 | " Compute an elliptic integral of the first kind.\n", 627 | " \"\"\"\n", 628 | " a_0, b_0 = 1., sqrt(1-k**2)\n", 629 | " for a, b in islice(arithmetic_geometric_mean(a_0, b_0), \n", 630 | " maxiter):\n", 631 | " if abs(a-b) < tolerance:\n", 632 | " return pi/(2*a)\n", 633 | " else:\n", 634 | " raise Exception(\"Algorithm did not converge\")" 635 | ] 636 | }, 637 | { 638 | "cell_type": "code", 639 | "execution_count": 39, 640 | "metadata": {}, 641 | "outputs": [], 642 | "source": [ 643 | "def pendulum_period(L, theta, g=9.81):\n", 644 | " return 4*sqrt(L/g)*elliptic_integral(sin(theta/2))" 645 | ] 646 | }, 647 | { 648 | "cell_type": "code", 649 | "execution_count": 40, 650 | "metadata": {}, 651 | "outputs": [ 652 | { 653 | "data": { 654 | "text/plain": [ 655 | "2.367841947461051" 656 | ] 657 | }, 658 | "execution_count": 40, 659 | "metadata": {}, 660 | "output_type": "execute_result" 661 | } 662 | ], 663 | "source": [ 664 | "pendulum_period(1,pi/2)" 665 | ] 666 | }, 667 | { 668 | "cell_type": "code", 669 | "execution_count": 41, 670 | "metadata": {}, 671 | "outputs": [], 672 | "source": [ 673 | "def Euler_accelerate(sequence):\n", 674 | " \"\"\"\n", 675 | " Accelerate the iterator in the variable `sequence`.\n", 676 | " \"\"\"\n", 677 | " s0 = sequence.__next__() # Si\n", 678 | " s1 = sequence.__next__() # Si+1\n", 679 | " s2 = sequence.__next__() # Si+2\n", 680 | " while True:\n", 681 | " yield s0 - ((s1 - s0)**2)/(s2 - 2*s1 + s0)\n", 682 | " s0, s1, s2 = s1, s2, sequence.__next__()" 683 | ] 684 | }, 685 | { 686 | "cell_type": "code", 687 | "execution_count": 42, 688 | "metadata": {}, 689 | "outputs": [], 690 | "source": [ 691 | "def pi_series():\n", 692 | " sum = 0.\n", 693 | " j = 1\n", 694 | " for i in itertools.cycle([1, -1]):\n", 695 | " yield sum\n", 696 | " sum += i/j\n", 697 | " j += 2" 698 | ] 699 | }, 700 | { 701 | "cell_type": "code", 702 | "execution_count": 43, 703 | "metadata": {}, 704 | "outputs": [ 705 | { 706 | "data": { 707 | "text/plain": [ 708 | "[0.75,\n", 709 | " 0.7916666666666667,\n", 710 | " 0.7833333333333334,\n", 711 | " 0.7863095238095239,\n", 712 | " 0.784920634920635,\n", 713 | " 0.7856782106782109,\n", 714 | " 0.7852203352203354,\n", 715 | " 0.7855179542679545,\n", 716 | " 0.7853137059019414,\n", 717 | " 0.7854599047323508,\n", 718 | " 0.7853516796241258,\n", 719 | " 0.7854340248151667,\n", 720 | " 0.7853699222510641,\n", 721 | " 0.7854207973019391,\n", 722 | " 0.7853797463988194]" 723 | ] 724 | }, 725 | "execution_count": 43, 726 | "metadata": {}, 727 | "output_type": "execute_result" 728 | } 729 | ], 730 | "source": [ 731 | "N=15\n", 732 | "list(itertools.islice(Euler_accelerate(pi_series()), N))" 733 | ] 734 | }, 735 | { 736 | "cell_type": "markdown", 737 | "metadata": {}, 738 | "source": [ 739 | "## 9.4 List-filling patterns\n", 740 | "### 9.4.1 List filling with the append method\n" 741 | ] 742 | }, 743 | { 744 | "cell_type": "code", 745 | "execution_count": 47, 746 | "metadata": {}, 747 | "outputs": [ 748 | { 749 | "data": { 750 | "text/plain": [ 751 | "[0, 1, 2]" 752 | ] 753 | }, 754 | "execution_count": 47, 755 | "metadata": {}, 756 | "output_type": "execute_result" 757 | } 758 | ], 759 | "source": [ 760 | "L = []\n", 761 | "n=3\n", 762 | "for k in range(n):\n", 763 | " # call various functions here\n", 764 | " # that compute \"result\"\n", 765 | " result = k\n", 766 | " L.append(result)\n", 767 | "L" 768 | ] 769 | }, 770 | { 771 | "cell_type": "markdown", 772 | "metadata": {}, 773 | "source": [ 774 | "### 9.4.2 List from iterators" 775 | ] 776 | }, 777 | { 778 | "cell_type": "code", 779 | "execution_count": 48, 780 | "metadata": {}, 781 | "outputs": [], 782 | "source": [ 783 | "def result_iterator():\n", 784 | " for k in itertools.count(): # infinite iterator\n", 785 | " # call various functions here\n", 786 | " # that t lists compute \"result\"\n", 787 | " result = k\n", 788 | " yield result" 789 | ] 790 | }, 791 | { 792 | "cell_type": "code", 793 | "execution_count": 51, 794 | "metadata": {}, 795 | "outputs": [ 796 | { 797 | "data": { 798 | "text/plain": [ 799 | "[0, 1, 2]" 800 | ] 801 | }, 802 | "execution_count": 51, 803 | "metadata": {}, 804 | "output_type": "execute_result" 805 | } 806 | ], 807 | "source": [ 808 | "L = list(itertools.islice(result_iterator(), n)) # no append needed!\n", 809 | "L" 810 | ] 811 | }, 812 | { 813 | "cell_type": "markdown", 814 | "metadata": {}, 815 | "source": [ 816 | "The next statement requires the built-in function `sum`. As we previously imported numpy by \n", 817 | "`from numpy import *` the next statement uses numpy.sum and will not give us the result described in the book.\n", 818 | "Deleting the imported `sum` gives us the built-in `sum` back" 819 | ] 820 | }, 821 | { 822 | "cell_type": "code", 823 | "execution_count": 91, 824 | "metadata": {}, 825 | "outputs": [], 826 | "source": [ 827 | "del sum" 828 | ] 829 | }, 830 | { 831 | "cell_type": "code", 832 | "execution_count": 92, 833 | "metadata": {}, 834 | "outputs": [ 835 | { 836 | "data": { 837 | "text/plain": [ 838 | "190" 839 | ] 840 | }, 841 | "execution_count": 92, 842 | "metadata": {}, 843 | "output_type": "execute_result" 844 | } 845 | ], 846 | "source": [ 847 | "sum(itertools.islice(result_iterator(), n))" 848 | ] 849 | }, 850 | { 851 | "cell_type": "code", 852 | "execution_count": 93, 853 | "metadata": {}, 854 | "outputs": [], 855 | "source": [ 856 | "L=list(itertools.takewhile(lambda x: abs(x) > 1.e-8, result_iterator()))" 857 | ] 858 | }, 859 | { 860 | "cell_type": "code", 861 | "execution_count": 94, 862 | "metadata": {}, 863 | "outputs": [ 864 | { 865 | "data": { 866 | "text/plain": [ 867 | "[]" 868 | ] 869 | }, 870 | "execution_count": 94, 871 | "metadata": {}, 872 | "output_type": "execute_result" 873 | } 874 | ], 875 | "source": [ 876 | "L" 877 | ] 878 | }, 879 | { 880 | "cell_type": "markdown", 881 | "metadata": {}, 882 | "source": [ 883 | "### 9.4.3 Storing generated values" 884 | ] 885 | }, 886 | { 887 | "cell_type": "code", 888 | "execution_count": 95, 889 | "metadata": {}, 890 | "outputs": [], 891 | "source": [ 892 | "import itertools\n", 893 | "def power_sequence(u0):\n", 894 | " u = u0\n", 895 | " while True:\n", 896 | " yield u\n", 897 | " u = u**2" 898 | ] 899 | }, 900 | { 901 | "cell_type": "markdown", 902 | "metadata": {}, 903 | "source": [ 904 | "*To see the OverflowError exception, uncomment the next line.*" 905 | ] 906 | }, 907 | { 908 | "cell_type": "code", 909 | "execution_count": 96, 910 | "metadata": {}, 911 | "outputs": [], 912 | "source": [ 913 | "# list(itertools.islice(power_sequence(2.), 20))" 914 | ] 915 | }, 916 | { 917 | "cell_type": "code", 918 | "execution_count": 97, 919 | "metadata": {}, 920 | "outputs": [ 921 | { 922 | "data": { 923 | "text/plain": [ 924 | "[2.0,\n", 925 | " 4.0,\n", 926 | " 16.0,\n", 927 | " 256.0,\n", 928 | " 65536.0,\n", 929 | " 4294967296.0,\n", 930 | " 1.8446744073709552e+19,\n", 931 | " 3.402823669209385e+38,\n", 932 | " 1.157920892373162e+77,\n", 933 | " 1.3407807929942597e+154]" 934 | ] 935 | }, 936 | "execution_count": 97, 937 | "metadata": {}, 938 | "output_type": "execute_result" 939 | } 940 | ], 941 | "source": [ 942 | "generator = power_sequence(2.)\n", 943 | "L = []\n", 944 | "for iteration in range(20):\n", 945 | " try:\n", 946 | " L.append(next(generator))\n", 947 | " except Exception:\n", 948 | " break\n", 949 | "L" 950 | ] 951 | }, 952 | { 953 | "cell_type": "markdown", 954 | "metadata": {}, 955 | "source": [ 956 | "## 9.5 When iterators behave as lists\n", 957 | "### 9.5.1 Generator expressions\n" 958 | ] 959 | }, 960 | { 961 | "cell_type": "code", 962 | "execution_count": 98, 963 | "metadata": {}, 964 | "outputs": [], 965 | "source": [ 966 | "g = (n for n in range(1000) if not n % 100)\n", 967 | "# generator for 100, 200, ... , 900" 968 | ] 969 | }, 970 | { 971 | "cell_type": "markdown", 972 | "metadata": {}, 973 | "source": [ 974 | "*See the comment above, concerning built-in functions and numpy's `sum`*" 975 | ] 976 | }, 977 | { 978 | "cell_type": "code", 979 | "execution_count": 99, 980 | "metadata": {}, 981 | "outputs": [ 982 | { 983 | "data": { 984 | "text/plain": [ 985 | "4500" 986 | ] 987 | }, 988 | "execution_count": 99, 989 | "metadata": {}, 990 | "output_type": "execute_result" 991 | } 992 | ], 993 | "source": [ 994 | "sum(n for n in range(1000) if not n % 100) # returns 4500 " 995 | ] 996 | }, 997 | { 998 | "cell_type": "code", 999 | "execution_count": 100, 1000 | "metadata": {}, 1001 | "outputs": [ 1002 | { 1003 | "data": { 1004 | "text/plain": [ 1005 | "1.5961632439130233" 1006 | ] 1007 | }, 1008 | "execution_count": 100, 1009 | "metadata": {}, 1010 | "output_type": "execute_result" 1011 | } 1012 | ], 1013 | "source": [ 1014 | "N=20\n", 1015 | "s=2\n", 1016 | "sum(1/n**s for n in itertools.islice(itertools.count(1), N))\n" 1017 | ] 1018 | }, 1019 | { 1020 | "cell_type": "code", 1021 | "execution_count": 101, 1022 | "metadata": {}, 1023 | "outputs": [ 1024 | { 1025 | "data": { 1026 | "text/plain": [ 1027 | "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]" 1028 | ] 1029 | }, 1030 | "execution_count": 101, 1031 | "metadata": {}, 1032 | "output_type": "execute_result" 1033 | } 1034 | ], 1035 | "source": [ 1036 | "list(itertools.islice(itertools.count(1), N))" 1037 | ] 1038 | }, 1039 | { 1040 | "cell_type": "code", 1041 | "execution_count": 102, 1042 | "metadata": {}, 1043 | "outputs": [], 1044 | "source": [ 1045 | "def generate_zeta(s):\n", 1046 | " for n in itertools.count(1):\n", 1047 | " yield 1/n**s" 1048 | ] 1049 | }, 1050 | { 1051 | "cell_type": "code", 1052 | "execution_count": 103, 1053 | "metadata": {}, 1054 | "outputs": [], 1055 | "source": [ 1056 | "def zeta(N, s):\n", 1057 | " # make sure that you do not use the scipy.sum here\n", 1058 | " return sum(itertools.islice(generate_zeta(s), N))" 1059 | ] 1060 | }, 1061 | { 1062 | "cell_type": "code", 1063 | "execution_count": 104, 1064 | "metadata": {}, 1065 | "outputs": [ 1066 | { 1067 | "data": { 1068 | "text/plain": [ 1069 | "1.5961632439130233" 1070 | ] 1071 | }, 1072 | "execution_count": 104, 1073 | "metadata": {}, 1074 | "output_type": "execute_result" 1075 | } 1076 | ], 1077 | "source": [ 1078 | "zeta(20,2)" 1079 | ] 1080 | }, 1081 | { 1082 | "cell_type": "markdown", 1083 | "metadata": {}, 1084 | "source": [ 1085 | "### 9.5.2 Zipping iterators" 1086 | ] 1087 | }, 1088 | { 1089 | "cell_type": "markdown", 1090 | "metadata": {}, 1091 | "source": [ 1092 | "*We first create for the example two iterators:*" 1093 | ] 1094 | }, 1095 | { 1096 | "cell_type": "code", 1097 | "execution_count": 108, 1098 | "metadata": {}, 1099 | "outputs": [], 1100 | "source": [ 1101 | "def odd_numbers():\n", 1102 | " k=-1\n", 1103 | " while True: # this makes it an infinite generator\n", 1104 | " k+=1\n", 1105 | " if k%2==1:\n", 1106 | " yield k\n", 1107 | "def even_numbers():\n", 1108 | " k=0\n", 1109 | " while True: # this makes it an infinite generator\n", 1110 | " k+=1\n", 1111 | " if k%2==0:\n", 1112 | " yield k " 1113 | ] 1114 | }, 1115 | { 1116 | "cell_type": "code", 1117 | "execution_count": 109, 1118 | "metadata": {}, 1119 | "outputs": [ 1120 | { 1121 | "name": "stdout", 1122 | "output_type": "stream", 1123 | "text": [ 1124 | "1 2\n", 1125 | "3 4\n", 1126 | "5 6\n", 1127 | "7 8\n", 1128 | "9 10\n", 1129 | "11 12\n", 1130 | "13 14\n", 1131 | "15 16\n", 1132 | "17 18\n", 1133 | "19 20\n" 1134 | ] 1135 | } 1136 | ], 1137 | "source": [ 1138 | "xg = itertools.islice(odd_numbers(),10) # some iterator\n", 1139 | "yg = itertools.islice(even_numbers(),10) # another iterator\n", 1140 | "\n", 1141 | "for x, y in zip(xg, yg):\n", 1142 | " print(x, y)" 1143 | ] 1144 | }, 1145 | { 1146 | "cell_type": "markdown", 1147 | "metadata": {}, 1148 | "source": [ 1149 | "## 9.6 Iterator objects\n" 1150 | ] 1151 | }, 1152 | { 1153 | "cell_type": "code", 1154 | "execution_count": 112, 1155 | "metadata": {}, 1156 | "outputs": [ 1157 | { 1158 | "name": "stdout", 1159 | "output_type": "stream", 1160 | "text": [ 1161 | "1\n", 1162 | "1.1\n", 1163 | "1.3\n" 1164 | ] 1165 | }, 1166 | { 1167 | "data": { 1168 | "text/plain": [ 1169 | "[1, 1.1, 1.3]" 1170 | ] 1171 | }, 1172 | "execution_count": 112, 1173 | "metadata": {}, 1174 | "output_type": "execute_result" 1175 | } 1176 | ], 1177 | "source": [ 1178 | "class OdeStore:\n", 1179 | " \"\"\"\n", 1180 | " Class to store results of ode computations\n", 1181 | " \"\"\"\n", 1182 | " def __init__(self, data):\n", 1183 | " \"data is a list of the form [[t0, u0], [t1, u1],...]\"\n", 1184 | " self.data = data\n", 1185 | " \n", 1186 | " def __iter__(self):\n", 1187 | " \"By default, we iterate on the values u0, u1,...\"\n", 1188 | " for t, u in self.data:\n", 1189 | " yield u\n", 1190 | "\n", 1191 | "store = OdeStore([[0, 1], [0.1, 1.1], [0.2, 1.3]])\n", 1192 | "for u in store:\n", 1193 | " print(u)\n", 1194 | "# result: 1, 1.1, 1.3\n", 1195 | "list(store) # [1, 1.1, 1.3]" 1196 | ] 1197 | }, 1198 | { 1199 | "cell_type": "markdown", 1200 | "metadata": {}, 1201 | "source": [ 1202 | "## 9.7 Infinite iterations\n", 1203 | "### 9.7.1 The while loop\n", 1204 | "*no complete code in this subsecdtion*\n", 1205 | "### 9.7.2 Recursion\n", 1206 | "\n" 1207 | ] 1208 | }, 1209 | { 1210 | "cell_type": "code", 1211 | "execution_count": 115, 1212 | "metadata": {}, 1213 | "outputs": [], 1214 | "source": [ 1215 | "def f(N):\n", 1216 | " if N == 0: \n", 1217 | " return 0\n", 1218 | " return f(N-1)" 1219 | ] 1220 | } 1221 | ], 1222 | "metadata": { 1223 | "kernelspec": { 1224 | "display_name": "Python 3", 1225 | "language": "python", 1226 | "name": "python3" 1227 | }, 1228 | "language_info": { 1229 | "codemirror_mode": { 1230 | "name": "ipython", 1231 | "version": 3 1232 | }, 1233 | "file_extension": ".py", 1234 | "mimetype": "text/x-python", 1235 | "name": "python", 1236 | "nbconvert_exporter": "python", 1237 | "pygments_lexer": "ipython3", 1238 | "version": "3.7.6" 1239 | } 1240 | }, 1241 | "nbformat": 4, 1242 | "nbformat_minor": 4 1243 | } 1244 | -------------------------------------------------------------------------------- /Chapter10/rates.dat: -------------------------------------------------------------------------------- 1 | Date;Euro_SEK 2 | 2019-01-02;10.214 3 | 2019-01-03;10.280 4 | 2019-01-04;10.246 5 | 2019-01-07;10.223 6 | 2019-01-08;10.185 7 | 2019-01-09;10.226 8 | 2019-01-10;10.230 9 | 2019-01-11;10.233 10 | 2019-01-14;10.249 11 | 2019-01-15;10.240 12 | 2019-01-16;10.248 13 | 2019-01-17;10.285 14 | 2019-01-18;10.251 15 | 2019-01-21;10.251 16 | 2019-01-22;10.253 17 | 2019-01-23;10.245 18 | 2019-01-24;10.284 19 | 2019-01-25;10.298 20 | 2019-01-28;10.350 21 | 2019-01-29;10.350 22 | 2019-01-30;10.384 23 | 2019-01-31;10.373 24 | 2019-02-01;10.387 25 | 2019-02-04;10.411 26 | 2019-02-05;10.399 27 | 2019-02-06;10.425 28 | 2019-02-07;10.473 29 | 2019-02-08;10.497 30 | 2019-02-11;10.485 31 | 2019-02-12;10.472 32 | 2019-02-13;10.408 33 | 2019-02-14;10.477 34 | 2019-02-15;10.481 35 | 2019-02-18;10.468 36 | 2019-02-19;10.600 37 | 2019-02-20;10.570 38 | 2019-02-21;10.618 39 | 2019-02-22;10.599 40 | 2019-02-25;10.579 41 | 2019-02-26;10.585 42 | 2019-02-27;10.544 43 | 2019-02-28;10.484 44 | 2019-03-01;10.500 45 | 2019-03-04;10.554 46 | 2019-03-05;10.552 47 | 2019-03-06;10.537 48 | 2019-03-07;10.562 49 | 2019-03-08;10.631 50 | 2019-03-11;10.580 51 | 2019-03-12;10.571 52 | 2019-03-13;10.554 53 | 2019-03-14;10.537 54 | 2019-03-15;10.496 55 | 2019-03-18;10.464 56 | 2019-03-19;10.448 57 | 2019-03-20;10.431 58 | 2019-03-21;10.428 59 | 2019-03-22;10.472 60 | 2019-03-25;10.445 61 | 2019-03-26;10.426 62 | 2019-03-27;10.429 63 | 2019-03-28;10.476 64 | 2019-03-29;10.398 65 | 2019-04-01;10.420 66 | 2019-04-02;10.441 67 | 2019-04-03;10.430 68 | 2019-04-04;10.407 69 | 2019-04-05;10.426 70 | 2019-04-08;10.432 71 | 2019-04-09;10.425 72 | 2019-04-10;10.440 73 | 2019-04-11;10.437 74 | 2019-04-12;10.478 75 | 2019-04-15;10.460 76 | 2019-04-16;10.463 77 | 2019-04-17;10.440 78 | 2019-04-18;10.476 79 | 2019-04-23;10.507 80 | 2019-04-24;10.501 81 | 2019-04-25;10.629 82 | 2019-04-26;10.573 83 | 2019-04-29;10.611 84 | 2019-04-30;10.635 85 | 2019-05-02;10.685 86 | 2019-05-03;10.704 87 | 2019-05-06;10.725 88 | 2019-05-07;10.714 89 | 2019-05-08;10.749 90 | 2019-05-09;10.797 91 | 2019-05-10;10.810 92 | 2019-05-13;10.832 93 | 2019-05-14;10.779 94 | 2019-05-15;10.768 95 | 2019-05-16;10.759 96 | 2019-05-17;10.766 97 | 2019-05-20;10.766 98 | 2019-05-21;10.774 99 | 2019-05-22;10.760 100 | 2019-05-23;10.737 101 | 2019-05-24;10.709 102 | 2019-05-27;10.714 103 | 2019-05-28;10.686 104 | 2019-05-29;10.706 105 | 2019-05-30;10.632 106 | 2019-05-31;10.639 107 | 2019-06-03;10.618 108 | 2019-06-04;10.626 109 | 2019-06-05;10.625 110 | 2019-06-06;10.617 111 | 2019-06-07;10.656 112 | 2019-06-10;10.645 113 | 2019-06-11;10.682 114 | 2019-06-12;10.680 115 | 2019-06-13;10.696 116 | 2019-06-14;10.639 117 | 2019-06-17;10.649 118 | 2019-06-18;10.641 119 | 2019-06-19;10.686 120 | 2019-06-20;10.634 121 | 2019-06-21;10.630 122 | 2019-06-24;10.607 123 | 2019-06-25;10.532 124 | 2019-06-26;10.543 125 | 2019-06-27;10.548 126 | 2019-06-28;10.563 127 | 2019-07-01;10.545 128 | 2019-07-02;10.556 129 | 2019-07-03;10.515 130 | 2019-07-04;10.520 131 | 2019-07-05;10.557 132 | 2019-07-08;10.597 133 | 2019-07-09;10.633 134 | 2019-07-10;10.609 135 | 2019-07-11;10.580 136 | 2019-07-12;10.551 137 | 2019-07-15;10.556 138 | 2019-07-16;10.540 139 | 2019-07-17;10.516 140 | 2019-07-18;10.504 141 | 2019-07-19;10.519 142 | 2019-07-22;10.544 143 | 2019-07-23;10.569 144 | 2019-07-24;10.529 145 | 2019-07-25;10.494 146 | 2019-07-26;10.558 147 | 2019-07-29;10.577 148 | 2019-07-30;10.645 149 | 2019-07-31;10.664 150 | 2019-08-01;10.686 151 | 2019-08-02;10.722 152 | 2019-08-05;10.760 153 | 2019-08-06;10.726 154 | 2019-08-07;10.767 155 | 2019-08-08;10.753 156 | 2019-08-09;10.697 157 | 2019-08-12;10.731 158 | 2019-08-13;10.708 159 | 2019-08-14;10.731 160 | 2019-08-15;10.730 161 | 2019-08-16;10.712 162 | 2019-08-19;10.726 163 | 2019-08-20;10.765 164 | 2019-08-21;10.698 165 | 2019-08-22;10.718 166 | 2019-08-23;10.716 167 | 2019-08-26;10.751 168 | 2019-08-27;10.705 169 | 2019-08-28;10.754 170 | 2019-08-29;10.779 171 | 2019-08-30;10.839 172 | 2019-09-02;10.747 173 | 2019-09-03;10.812 174 | 2019-09-04;10.753 175 | 2019-09-05;10.682 176 | 2019-09-06;10.635 177 | 2019-09-09;10.659 178 | 2019-09-10;10.744 179 | 2019-09-11;10.656 180 | 2019-09-12;10.631 181 | 2019-09-13;10.648 182 | 2019-09-16;10.670 183 | 2019-09-17;10.699 184 | 2019-09-18;10.729 185 | 2019-09-19;10.722 186 | 2019-09-20;10.711 187 | 2019-09-23;10.714 188 | 2019-09-24;10.676 189 | 2019-09-25;10.682 190 | 2019-09-26;10.659 191 | 2019-09-27;10.701 192 | 2019-09-30;10.695 193 | 2019-10-01;10.804 194 | 2019-10-02;10.811 195 | 2019-10-03;10.833 196 | 2019-10-04;10.810 197 | 2019-10-07;10.891 198 | 2019-10-08;10.870 199 | 2019-10-09;10.917 200 | 2019-10-10;10.841 201 | 2019-10-11;10.844 202 | 2019-10-14;10.852 203 | 2019-10-15;10.822 204 | 2019-10-16;10.835 205 | 2019-10-17;10.810 206 | 2019-10-18;10.774 207 | 2019-10-21;10.731 208 | 2019-10-22;10.730 209 | 2019-10-23;10.738 210 | 2019-10-24;10.696 211 | 2019-10-25;10.744 212 | 2019-10-28;10.750 213 | 2019-10-29;10.792 214 | 2019-10-30;10.801 215 | 2019-10-31;10.749 216 | 2019-11-01;10.699 217 | 2019-11-04;10.703 218 | 2019-11-05;10.694 219 | 2019-11-06;10.644 220 | 2019-11-07;10.625 221 | 2019-11-08;10.702 222 | 2019-11-11;10.708 223 | 2019-11-12;10.700 224 | 2019-11-13;10.735 225 | 2019-11-14;10.694 226 | 2019-11-15;10.651 227 | 2019-11-18;10.660 228 | 2019-11-19;10.647 229 | 2019-11-20;10.693 230 | 2019-11-21;10.656 231 | 2019-11-22;10.626 232 | 2019-11-25;10.615 233 | 2019-11-26;10.580 234 | 2019-11-27;10.558 235 | 2019-11-28;10.546 236 | 2019-11-29;10.499 237 | 2019-12-02;10.538 238 | 2019-12-03;10.565 239 | 2019-12-04;10.552 240 | 2019-12-05;10.541 241 | 2019-12-06;10.518 242 | 2019-12-09;10.543 243 | 2019-12-10;10.556 244 | 2019-12-11;10.459 245 | 2019-12-12;10.449 246 | 2019-12-13;10.449 247 | 2019-12-16;10.421 248 | 2019-12-17;10.471 249 | 2019-12-18;10.448 250 | 2019-12-19;10.478 251 | 2019-12-20;10.434 252 | 2019-12-23;10.447 253 | 2019-12-24;10.455 254 | 2019-12-27;10.436 255 | 2019-12-30;10.440 256 | 2019-12-31;10.446 257 | 2020-01-02;10.472 258 | 2020-01-03;10.485 259 | 2020-01-06;10.530 260 | 2020-01-07;10.542 261 | 2020-01-08;10.510 262 | 2020-01-09;10.533 263 | 2020-01-10;10.551 264 | 2020-01-13;10.559 265 | 2020-01-14;10.524 266 | 2020-01-15;10.559 267 | 2020-01-16;10.567 268 | 2020-01-17;10.545 269 | 2020-01-20;10.554 270 | 2020-01-21;10.552 271 | 2020-01-22;10.552 272 | 2020-01-23;10.547 273 | 2020-01-24;10.536 274 | 2020-01-27;10.579 275 | 2020-01-28;10.599 276 | 2020-01-29;10.575 277 | 2020-01-30;10.639 278 | 2020-01-31;10.676 279 | 2020-02-03;10.680 280 | 2020-02-04;10.627 281 | 2020-02-05;10.545 282 | 2020-02-06;10.555 283 | 2020-02-07;10.545 284 | 2020-02-10;10.572 285 | 2020-02-11;10.537 286 | 2020-02-12;10.496 287 | 2020-02-13;10.482 288 | 2020-02-14;10.508 289 | 2020-02-17;10.532 290 | 2020-02-18;10.549 291 | 2020-02-19;10.574 292 | 2020-02-20;10.598 293 | 2020-02-21;10.569 294 | 2020-02-24;10.583 295 | 2020-02-25;10.568 296 | 2020-02-26;10.581 297 | 2020-02-27;10.575 298 | 2020-02-28;10.673 299 | 2020-03-02;10.606 300 | 2020-03-03;10.559 301 | 2020-03-04;10.555 302 | 2020-03-05;10.591 303 | 2020-03-06;10.614 304 | 2020-03-09;10.720 305 | 2020-03-10;10.801 306 | 2020-03-11;10.723 307 | 2020-03-12;10.894 308 | 2020-03-13;10.845 309 | 2020-03-16;10.899 310 | 2020-03-17;10.959 311 | 2020-03-18;11.022 312 | 2020-03-19;11.152 313 | 2020-03-20;11.059 314 | 2020-03-23;11.071 315 | 2020-03-24;11.088 316 | 2020-03-25;10.963 317 | 2020-03-26;11.007 318 | 2020-03-27;11.015 319 | 2020-03-30;11.037 320 | 2020-03-31;11.061 321 | 2020-04-01;10.936 322 | 2020-04-02;10.926 323 | 2020-04-03;10.952 324 | 2020-04-06;10.978 325 | 2020-04-07;10.878 326 | 2020-04-08;10.938 327 | 2020-04-09;10.945 328 | 2020-04-14;10.915 329 | 2020-04-15;10.932 330 | 2020-04-16;10.889 331 | 2020-04-17;10.854 332 | 2020-04-20;10.862 333 | 2020-04-21;10.954 334 | 2020-04-22;10.942 335 | 2020-04-23;10.888 336 | 2020-04-24;10.872 337 | 2020-04-27;10.874 338 | 2020-04-28;10.748 339 | 2020-04-29;10.733 340 | 2020-04-30;10.663 341 | 2020-05-04;10.811 342 | 2020-05-05;10.698 343 | 2020-05-06;10.627 344 | 2020-05-07;10.620 345 | 2020-05-08;10.587 346 | 2020-05-11;10.599 347 | 2020-05-12;10.596 348 | 2020-05-13;10.584 349 | 2020-05-14;10.641 350 | 2020-05-15;10.669 351 | 2020-05-18;10.610 352 | 2020-05-19;10.568 353 | 2020-05-20;10.556 354 | 2020-05-21;10.530 355 | 2020-05-22;10.537 356 | 2020-05-25;10.549 357 | 2020-05-26;10.556 358 | 2020-05-27;10.560 359 | 2020-05-28;10.548 360 | 2020-05-29;10.487 361 | 2020-06-01;10.463 362 | 2020-06-02;10.452 363 | 2020-06-03;10.458 364 | 2020-06-04;10.417 365 | 2020-06-05;10.425 366 | 2020-06-08;10.397 367 | 2020-06-09;10.418 368 | 2020-06-10;10.460 369 | 2020-06-11;10.501 370 | 2020-06-12;10.510 371 | 2020-06-15;10.539 372 | 2020-06-16;10.513 373 | 2020-06-17;10.512 374 | 2020-06-18;10.552 375 | 2020-06-19;10.567 376 | 2020-06-22;10.552 377 | 2020-06-23;10.517 378 | 2020-06-24;10.514 379 | 2020-06-25;10.486 380 | 2020-06-26;10.477 381 | -------------------------------------------------------------------------------- /Chapter11/circle_evolution.swf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Scientific-Computing-with-Python-Second-Edition/fab030c4283185a66c17692dc202f2e696aacded/Chapter11/circle_evolution.swf -------------------------------------------------------------------------------- /Chapter12/chapter12.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Scientific Computing with Python (Second Edition)\n", 8 | "\n", 9 | "# Chapter 12\n", 10 | "\n", 11 | "This notebook file requires Jupyter notebook version >= 5 as it uses cell tagging to avoid that execution stops when intentionally exceptions are raises in a a cell.\n", 12 | "\n", 13 | "*We start by importing all from Numpy. As explained in Chapter 01 \n", 14 | "the examples are written assuming this import is initially done.*\n", 15 | "\n" 16 | ] 17 | }, 18 | { 19 | "cell_type": "code", 20 | "execution_count": 1, 21 | "metadata": {}, 22 | "outputs": [], 23 | "source": [ 24 | "from numpy import *" 25 | ] 26 | }, 27 | { 28 | "cell_type": "code", 29 | "execution_count": 2, 30 | "metadata": {}, 31 | "outputs": [], 32 | "source": [ 33 | "def f(x):\n", 34 | " return 1/x\n" 35 | ] 36 | }, 37 | { 38 | "cell_type": "code", 39 | "execution_count": 3, 40 | "metadata": {}, 41 | "outputs": [ 42 | { 43 | "data": { 44 | "text/plain": [ 45 | "0.4" 46 | ] 47 | }, 48 | "execution_count": 3, 49 | "metadata": {}, 50 | "output_type": "execute_result" 51 | } 52 | ], 53 | "source": [ 54 | "f(2.5)" 55 | ] 56 | }, 57 | { 58 | "cell_type": "code", 59 | "execution_count": 4, 60 | "metadata": { 61 | "tags": [ 62 | "raises-exception" 63 | ] 64 | }, 65 | "outputs": [ 66 | { 67 | "ename": "ZeroDivisionError", 68 | "evalue": "division by zero", 69 | "output_type": "error", 70 | "traceback": [ 71 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 72 | "\u001b[0;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", 73 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mf\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", 74 | "\u001b[0;32m\u001b[0m in \u001b[0;36mf\u001b[0;34m(x)\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mf\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m/\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", 75 | "\u001b[0;31mZeroDivisionError\u001b[0m: division by zero" 76 | ] 77 | } 78 | ], 79 | "source": [ 80 | "f(0)" 81 | ] 82 | }, 83 | { 84 | "cell_type": "code", 85 | "execution_count": 5, 86 | "metadata": {}, 87 | "outputs": [ 88 | { 89 | "data": { 90 | "text/plain": [ 91 | "array([0., 1., 2., 3., 4., 5., 6., 7.])" 92 | ] 93 | }, 94 | "execution_count": 5, 95 | "metadata": {}, 96 | "output_type": "execute_result" 97 | } 98 | ], 99 | "source": [ 100 | "a = arange(8.0) \n", 101 | "a" 102 | ] 103 | }, 104 | { 105 | "cell_type": "code", 106 | "execution_count": 6, 107 | "metadata": { 108 | "tags": [ 109 | "raises-exception" 110 | ] 111 | }, 112 | "outputs": [ 113 | { 114 | "ename": "ValueError", 115 | "evalue": "could not convert string to float: 'string'", 116 | "output_type": "error", 117 | "traceback": [ 118 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 119 | "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)", 120 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0ma\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m3\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m'string'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", 121 | "\u001b[0;31mValueError\u001b[0m: could not convert string to float: 'string'" 122 | ] 123 | } 124 | ], 125 | "source": [ 126 | "a[3] = 'string'" 127 | ] 128 | }, 129 | { 130 | "cell_type": "markdown", 131 | "metadata": {}, 132 | "source": [ 133 | "### 12.1.1 Basic principles" 134 | ] 135 | }, 136 | { 137 | "cell_type": "code", 138 | "execution_count": 7, 139 | "metadata": { 140 | "tags": [ 141 | "raises-exception" 142 | ] 143 | }, 144 | "outputs": [ 145 | { 146 | "ename": "Exception", 147 | "evalue": "Something went wrong", 148 | "output_type": "error", 149 | "traceback": [ 150 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 151 | "\u001b[0;31mException\u001b[0m Traceback (most recent call last)", 152 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mException\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Something went wrong\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", 153 | "\u001b[0;31mException\u001b[0m: Something went wrong" 154 | ] 155 | } 156 | ], 157 | "source": [ 158 | "raise Exception(\"Something went wrong\")" 159 | ] 160 | }, 161 | { 162 | "cell_type": "code", 163 | "execution_count": 8, 164 | "metadata": {}, 165 | "outputs": [ 166 | { 167 | "name": "stdout", 168 | "output_type": "stream", 169 | "text": [ 170 | "The algorithm did not converge.\n" 171 | ] 172 | } 173 | ], 174 | "source": [ 175 | "print(\"The algorithm did not converge.\")" 176 | ] 177 | }, 178 | { 179 | "cell_type": "code", 180 | "execution_count": 9, 181 | "metadata": { 182 | "tags": [ 183 | "raises-exception" 184 | ] 185 | }, 186 | "outputs": [ 187 | { 188 | "ename": "Exception", 189 | "evalue": "The algorithm did not converge.", 190 | "output_type": "error", 191 | "traceback": [ 192 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 193 | "\u001b[0;31mException\u001b[0m Traceback (most recent call last)", 194 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mException\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"The algorithm did not converge.\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", 195 | "\u001b[0;31mException\u001b[0m: The algorithm did not converge." 196 | ] 197 | } 198 | ], 199 | "source": [ 200 | "raise Exception(\"The algorithm did not converge.\")" 201 | ] 202 | }, 203 | { 204 | "cell_type": "code", 205 | "execution_count": 10, 206 | "metadata": {}, 207 | "outputs": [], 208 | "source": [ 209 | "def factorial(n):\n", 210 | " if not (isinstance(n, (int, int32, int64))):\n", 211 | " raise TypeError(\"An integer is expected\")\n", 212 | " if not (n >=0): \n", 213 | " raise ValueError(\"A positive number is expected\")\n", 214 | " ..." 215 | ] 216 | }, 217 | { 218 | "cell_type": "code", 219 | "execution_count": 11, 220 | "metadata": { 221 | "tags": [ 222 | "raises-exception" 223 | ] 224 | }, 225 | "outputs": [ 226 | { 227 | "ename": "TypeError", 228 | "evalue": "An integer is expected", 229 | "output_type": "error", 230 | "traceback": [ 231 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 232 | "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", 233 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mfactorial\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m5.2\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", 234 | "\u001b[0;32m\u001b[0m in \u001b[0;36mfactorial\u001b[0;34m(n)\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mfactorial\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mn\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0misinstance\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mn\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0mint\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mint32\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mint64\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mTypeError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"An integer is expected\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 4\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0mn\u001b[0m \u001b[0;34m>=\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0;32mraise\u001b[0m \u001b[0mValueError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"A positive number is expected\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 235 | "\u001b[0;31mTypeError\u001b[0m: An integer is expected" 236 | ] 237 | } 238 | ], 239 | "source": [ 240 | "print(factorial(5.2))" 241 | ] 242 | }, 243 | { 244 | "cell_type": "code", 245 | "execution_count": 12, 246 | "metadata": { 247 | "tags": [ 248 | "raises-exception" 249 | ] 250 | }, 251 | "outputs": [ 252 | { 253 | "ename": "ValueError", 254 | "evalue": "A positive number is expected", 255 | "output_type": "error", 256 | "traceback": [ 257 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 258 | "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)", 259 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mfactorial\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0;36m5\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", 260 | "\u001b[0;32m\u001b[0m in \u001b[0;36mfactorial\u001b[0;34m(n)\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;32mraise\u001b[0m \u001b[0mTypeError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"An integer is expected\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0mn\u001b[0m \u001b[0;34m>=\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 5\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mValueError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"A positive number is expected\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 6\u001b[0m \u001b[0;34m...\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 261 | "\u001b[0;31mValueError\u001b[0m: A positive number is expected" 262 | ] 263 | } 264 | ], 265 | "source": [ 266 | "print(factorial(-5))" 267 | ] 268 | }, 269 | { 270 | "cell_type": "code", 271 | "execution_count": 13, 272 | "metadata": { 273 | "tags": [ 274 | "raises-exception" 275 | ] 276 | }, 277 | "outputs": [ 278 | { 279 | "name": "stdout", 280 | "output_type": "stream", 281 | "text": [ 282 | "Could not convert data to float.\n" 283 | ] 284 | } 285 | ], 286 | "source": [ 287 | "try: \n", 288 | " f = open('data.txt', 'r') \n", 289 | " data = f.readline() \n", 290 | " value = float(data) \n", 291 | "except FileNotFoundError as FnF: \n", 292 | " print(f' {FnF.strerror}: {FnF.filename}') \n", 293 | "except ValueError: \n", 294 | " print(\"Could not convert data to float.\")" 295 | ] 296 | }, 297 | { 298 | "cell_type": "markdown", 299 | "metadata": {}, 300 | "source": [ 301 | "### 12.1.2 User-defined exceptions" 302 | ] 303 | }, 304 | { 305 | "cell_type": "code", 306 | "execution_count": 14, 307 | "metadata": { 308 | "tags": [ 309 | "raises-exception" 310 | ] 311 | }, 312 | "outputs": [ 313 | { 314 | "name": "stdout", 315 | "output_type": "stream", 316 | "text": [ 317 | "Random number too small 0.30562532079102633\n" 318 | ] 319 | } 320 | ], 321 | "source": [ 322 | "class MyError(Exception):\n", 323 | " def __init__(self, expr):\n", 324 | " self.expr = expr\n", 325 | " def __str__(self):\n", 326 | " return str(self.expr)\n", 327 | "\n", 328 | "try:\n", 329 | " x = random.rand()\n", 330 | " if x < 0.5:\n", 331 | " raise MyError(x)\n", 332 | "except MyError as e:\n", 333 | " print(\"Random number too small\", e.expr)\n", 334 | "else:\n", 335 | " print(x)" 336 | ] 337 | }, 338 | { 339 | "cell_type": "markdown", 340 | "metadata": {}, 341 | "source": [ 342 | "### 12.1.3 Context managers – the with statement\n" 343 | ] 344 | }, 345 | { 346 | "cell_type": "code", 347 | "execution_count": 15, 348 | "metadata": { 349 | "tags": [ 350 | "raises-exception" 351 | ] 352 | }, 353 | "outputs": [ 354 | { 355 | "ename": "NameError", 356 | "evalue": "name 'process_file_data' is not defined", 357 | "output_type": "error", 358 | "traceback": [ 359 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 360 | "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", 361 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mwith\u001b[0m \u001b[0mopen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'data.txt'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'w'\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mf\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mprocess_file_data\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mf\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", 362 | "\u001b[0;31mNameError\u001b[0m: name 'process_file_data' is not defined" 363 | ] 364 | } 365 | ], 366 | "source": [ 367 | "with open('data.txt', 'w') as f:\n", 368 | " process_file_data(f)" 369 | ] 370 | }, 371 | { 372 | "cell_type": "code", 373 | "execution_count": 16, 374 | "metadata": { 375 | "tags": [ 376 | "raises-exception" 377 | ] 378 | }, 379 | "outputs": [], 380 | "source": [ 381 | "f = open('data.txt', 'w')\n", 382 | "try: \n", 383 | " # some function that does something with the file \n", 384 | " process_file_data(f) \n", 385 | "except:\n", 386 | " ...\n", 387 | "finally:\n", 388 | " f.close()" 389 | ] 390 | }, 391 | { 392 | "cell_type": "code", 393 | "execution_count": 17, 394 | "metadata": { 395 | "tags": [ 396 | "raises-exception" 397 | ] 398 | }, 399 | "outputs": [ 400 | { 401 | "name": "stdout", 402 | "output_type": "stream", 403 | "text": [ 404 | "nan\n", 405 | "nan\n" 406 | ] 407 | }, 408 | { 409 | "name": "stderr", 410 | "output_type": "stream", 411 | "text": [ 412 | "/home/claus/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:7: RuntimeWarning: invalid value encountered in sqrt\n", 413 | " import sys\n" 414 | ] 415 | }, 416 | { 417 | "ename": "FloatingPointError", 418 | "evalue": "invalid value encountered in sqrt", 419 | "output_type": "error", 420 | "traceback": [ 421 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 422 | "\u001b[0;31mFloatingPointError\u001b[0m Traceback (most recent call last)", 423 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 9\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 10\u001b[0m \u001b[0;32mwith\u001b[0m \u001b[0merrstate\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0minvalid\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m'raise'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 11\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mnp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msqrt\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# prints nothing and raises FloatingPointError\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", 424 | "\u001b[0;31mFloatingPointError\u001b[0m: invalid value encountered in sqrt" 425 | ] 426 | } 427 | ], 428 | "source": [ 429 | "import numpy as np # note, sqrt in NumPy and SciPy \n", 430 | " # behave differently in that example\n", 431 | "with errstate(invalid='ignore'):\n", 432 | " print(np.sqrt(-1)) # prints 'nan'\n", 433 | "\n", 434 | "with errstate(invalid='warn'):\n", 435 | " print(np.sqrt(-1)) # prints 'nan' and \n", 436 | " # 'RuntimeWarning: invalid value encountered in sqrt'\n", 437 | "\n", 438 | "with errstate(invalid='raise'):\n", 439 | " print(np.sqrt(-1)) # prints nothing and raises FloatingPointError" 440 | ] 441 | }, 442 | { 443 | "cell_type": "markdown", 444 | "metadata": {}, 445 | "source": [ 446 | "## 12.2 Finding errors: debugging\n", 447 | "### 12.2.1 Bugs\n", 448 | "no code\n", 449 | "### 12.2.2 The stack\n", 450 | "\n" 451 | ] 452 | }, 453 | { 454 | "cell_type": "code", 455 | "execution_count": 18, 456 | "metadata": { 457 | "tags": [ 458 | "raises-exception" 459 | ] 460 | }, 461 | "outputs": [ 462 | { 463 | "ename": "ZeroDivisionError", 464 | "evalue": "integer division or modulo by zero", 465 | "output_type": "error", 466 | "traceback": [ 467 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 468 | "\u001b[0;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", 469 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m//\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 8\u001b[0;31m \u001b[0mf\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", 470 | "\u001b[0;32m\u001b[0m in \u001b[0;36mf\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mf\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mg\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 3\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mg\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0mh\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mh\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 471 | "\u001b[0;32m\u001b[0m in \u001b[0;36mg\u001b[0;34m()\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0mg\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mg\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0mh\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 5\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mh\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m//\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 472 | "\u001b[0;32m\u001b[0m in \u001b[0;36mh\u001b[0;34m()\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0mh\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mh\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 6\u001b[0;31m \u001b[0;36m1\u001b[0m\u001b[0;34m//\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 7\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 8\u001b[0m \u001b[0mf\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 473 | "\u001b[0;31mZeroDivisionError\u001b[0m: integer division or modulo by zero" 474 | ] 475 | } 476 | ], 477 | "source": [ 478 | "def f():\n", 479 | " g()\n", 480 | "def g():\n", 481 | " h()\n", 482 | "def h():\n", 483 | " 1//0\n", 484 | "\n", 485 | "f()" 486 | ] 487 | }, 488 | { 489 | "cell_type": "code", 490 | "execution_count": 19, 491 | "metadata": { 492 | "tags": [ 493 | "raises-exception" 494 | ] 495 | }, 496 | "outputs": [ 497 | { 498 | "ename": "Exception", 499 | "evalue": "An exception just to provoke a strack trace and a value a=23", 500 | "output_type": "error", 501 | "traceback": [ 502 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 503 | "\u001b[0;31mException\u001b[0m Traceback (most recent call last)", 504 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0;32mraise\u001b[0m \u001b[0mException\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34mf'An exception just to provoke a strack trace and a value a={a}'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 8\u001b[0;31m \u001b[0mf\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m23\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", 505 | "\u001b[0;32m\u001b[0m in \u001b[0;36mf\u001b[0;34m(a)\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mf\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mg\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 3\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mg\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0mh\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mh\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 506 | "\u001b[0;32m\u001b[0m in \u001b[0;36mg\u001b[0;34m(a)\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0mg\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mg\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0mh\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 5\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mh\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0;32mraise\u001b[0m \u001b[0mException\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34mf'An exception just to provoke a strack trace and a value a={a}'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 507 | "\u001b[0;32m\u001b[0m in \u001b[0;36mh\u001b[0;34m(a)\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0mh\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mh\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 6\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mException\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34mf'An exception just to provoke a strack trace and a value a={a}'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 7\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 8\u001b[0m \u001b[0mf\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m23\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 508 | "\u001b[0;31mException\u001b[0m: An exception just to provoke a strack trace and a value a=23" 509 | ] 510 | } 511 | ], 512 | "source": [ 513 | "def f(a):\n", 514 | " g(a)\n", 515 | "def g(a):\n", 516 | " h(a)\n", 517 | "def h(a):\n", 518 | " raise Exception(f'An exception just to provoke a strack trace and a value a={a}')\n", 519 | "\n", 520 | "f(23)" 521 | ] 522 | }, 523 | { 524 | "cell_type": "markdown", 525 | "metadata": {}, 526 | "source": [ 527 | "### 12.2.3 The Python debugger\n", 528 | "\n", 529 | "We do not present code here as the section requires interactive user actions.\n", 530 | "\n", 531 | "### 12.2.4 Overview – debug commands\n", 532 | "\n", 533 | "No code in this section.\n", 534 | "\n", 535 | "### 12.2.5 Debugging in IPython\n", 536 | "\n", 537 | "We do not present code here as the section requires interactive user actions.\n", 538 | "\n" 539 | ] 540 | } 541 | ], 542 | "metadata": { 543 | "celltoolbar": "Tags", 544 | "kernelspec": { 545 | "display_name": "Python 3", 546 | "language": "python", 547 | "name": "python3" 548 | }, 549 | "language_info": { 550 | "codemirror_mode": { 551 | "name": "ipython", 552 | "version": 3 553 | }, 554 | "file_extension": ".py", 555 | "mimetype": "text/x-python", 556 | "name": "python", 557 | "nbconvert_exporter": "python", 558 | "pygments_lexer": "ipython3", 559 | "version": "3.7.6" 560 | } 561 | }, 562 | "nbformat": 4, 563 | "nbformat_minor": 4 564 | } 565 | -------------------------------------------------------------------------------- /Chapter13/chapter13.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Scientific Computing with Python (Second Edition)\n", 8 | "# Chapter 13\n", 9 | "\n", 10 | "We start by importing all from Numpy. As explained in Chapter 01 the examples are written assuming this import is initially done." 11 | ] 12 | }, 13 | { 14 | "cell_type": "code", 15 | "execution_count": 1, 16 | "metadata": {}, 17 | "outputs": [], 18 | "source": [ 19 | "from numpy import *" 20 | ] 21 | }, 22 | { 23 | "cell_type": "markdown", 24 | "metadata": {}, 25 | "source": [ 26 | "## 13.1 Namespaces" 27 | ] 28 | }, 29 | { 30 | "cell_type": "code", 31 | "execution_count": 2, 32 | "metadata": {}, 33 | "outputs": [ 34 | { 35 | "data": { 36 | "text/plain": [ 37 | "" 38 | ] 39 | }, 40 | "execution_count": 2, 41 | "metadata": {}, 42 | "output_type": "execute_result" 43 | } 44 | ], 45 | "source": [ 46 | "import math\n", 47 | "import numpy\n", 48 | "math.sin\n", 49 | "numpy.sin" 50 | ] 51 | }, 52 | { 53 | "cell_type": "code", 54 | "execution_count": 3, 55 | "metadata": {}, 56 | "outputs": [ 57 | { 58 | "data": { 59 | "text/plain": [ 60 | "'math'" 61 | ] 62 | }, 63 | "execution_count": 3, 64 | "metadata": {}, 65 | "output_type": "execute_result" 66 | } 67 | ], 68 | "source": [ 69 | "math.__name__ # returns math" 70 | ] 71 | }, 72 | { 73 | "cell_type": "code", 74 | "execution_count": 4, 75 | "metadata": {}, 76 | "outputs": [ 77 | { 78 | "data": { 79 | "text/plain": [ 80 | "'This module provides access to the mathematical functions\\ndefined by the C standard.'" 81 | ] 82 | }, 83 | "execution_count": 4, 84 | "metadata": {}, 85 | "output_type": "execute_result" 86 | } 87 | ], 88 | "source": [ 89 | "math.__doc__ # returns 'This module is always ...'" 90 | ] 91 | }, 92 | { 93 | "cell_type": "code", 94 | "execution_count": 5, 95 | "metadata": {}, 96 | "outputs": [ 97 | { 98 | "data": { 99 | "text/plain": [ 100 | "True" 101 | ] 102 | }, 103 | "execution_count": 5, 104 | "metadata": {}, 105 | "output_type": "execute_result" 106 | } 107 | ], 108 | "source": [ 109 | "'float' in dir(__builtin__) # returns True " 110 | ] 111 | }, 112 | { 113 | "cell_type": "code", 114 | "execution_count": 6, 115 | "metadata": {}, 116 | "outputs": [ 117 | { 118 | "data": { 119 | "text/plain": [ 120 | "True" 121 | ] 122 | }, 123 | "execution_count": 6, 124 | "metadata": {}, 125 | "output_type": "execute_result" 126 | } 127 | ], 128 | "source": [ 129 | "float is __builtin__.float # returns True" 130 | ] 131 | }, 132 | { 133 | "cell_type": "markdown", 134 | "metadata": {}, 135 | "source": [ 136 | "## 13.2 The scope of a variable" 137 | ] 138 | }, 139 | { 140 | "cell_type": "code", 141 | "execution_count": 7, 142 | "metadata": {}, 143 | "outputs": [], 144 | "source": [ 145 | "e = 3\n", 146 | "def my_function(in1):\n", 147 | " a = 2 * e\n", 148 | " b = 3\n", 149 | " in1 = 5\n", 150 | " def other_function():\n", 151 | " c = a\n", 152 | " d = e\n", 153 | " return dir()\n", 154 | " print(f\"\"\"\n", 155 | " my_function's namespace: {dir()} \n", 156 | " other_function's namespace: {other_function()}\n", 157 | " \"\"\")\n", 158 | " return a" 159 | ] 160 | }, 161 | { 162 | "cell_type": "code", 163 | "execution_count": 8, 164 | "metadata": {}, 165 | "outputs": [ 166 | { 167 | "name": "stdout", 168 | "output_type": "stream", 169 | "text": [ 170 | "\n", 171 | " my_function's namespace: ['a', 'b', 'in1', 'other_function'] \n", 172 | " other_function's namespace: ['a', 'c', 'd']\n", 173 | " \n" 174 | ] 175 | }, 176 | { 177 | "data": { 178 | "text/plain": [ 179 | "6" 180 | ] 181 | }, 182 | "execution_count": 8, 183 | "metadata": {}, 184 | "output_type": "execute_result" 185 | } 186 | ], 187 | "source": [ 188 | "my_function(3)" 189 | ] 190 | }, 191 | { 192 | "cell_type": "code", 193 | "execution_count": 9, 194 | "metadata": {}, 195 | "outputs": [], 196 | "source": [ 197 | "e = 3\n", 198 | "def my_function():\n", 199 | " e = 4\n", 200 | " a = 2\n", 201 | " print(f\"my_function's namespace: {dir()}\")" 202 | ] 203 | }, 204 | { 205 | "cell_type": "code", 206 | "execution_count": 10, 207 | "metadata": {}, 208 | "outputs": [ 209 | { 210 | "name": "stdout", 211 | "output_type": "stream", 212 | "text": [ 213 | "my_function's namespace: ['a', 'e']\n" 214 | ] 215 | }, 216 | { 217 | "data": { 218 | "text/plain": [ 219 | "3" 220 | ] 221 | }, 222 | "execution_count": 10, 223 | "metadata": {}, 224 | "output_type": "execute_result" 225 | } 226 | ], 227 | "source": [ 228 | "e = 3\n", 229 | "my_function()\n", 230 | "e # has the value 3" 231 | ] 232 | }, 233 | { 234 | "cell_type": "code", 235 | "execution_count": 11, 236 | "metadata": {}, 237 | "outputs": [ 238 | { 239 | "name": "stdout", 240 | "output_type": "stream", 241 | "text": [ 242 | "3\n", 243 | "2\n" 244 | ] 245 | } 246 | ], 247 | "source": [ 248 | "def fun():\n", 249 | " def fun1():\n", 250 | " global a\n", 251 | " a = 3\n", 252 | " def fun2():\n", 253 | " global b\n", 254 | " b = 2\n", 255 | " print(a)\n", 256 | " fun1()\n", 257 | " fun2() # prints a\n", 258 | " print(b)\n", 259 | "fun()" 260 | ] 261 | }, 262 | { 263 | "cell_type": "markdown", 264 | "metadata": {}, 265 | "source": [ 266 | "## 13.3 Modules\n", 267 | "### 13.3.1 Introduction" 268 | ] 269 | }, 270 | { 271 | "cell_type": "code", 272 | "execution_count": 12, 273 | "metadata": {}, 274 | "outputs": [], 275 | "source": [ 276 | "from numpy import array, vander" 277 | ] 278 | }, 279 | { 280 | "cell_type": "code", 281 | "execution_count": 13, 282 | "metadata": {}, 283 | "outputs": [], 284 | "source": [ 285 | "from numpy import *" 286 | ] 287 | }, 288 | { 289 | "cell_type": "code", 290 | "execution_count": 14, 291 | "metadata": { 292 | "tags": [ 293 | "raises-exception" 294 | ] 295 | }, 296 | "outputs": [ 297 | { 298 | "ename": "TypeError", 299 | "evalue": "'numpy.ndarray' object is not callable", 300 | "output_type": "error", 301 | "traceback": [ 302 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 303 | "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", 304 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;34m...\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0mB\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0mA\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 6\u001b[0;31m \u001b[0;34m(\u001b[0m\u001b[0mc\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0md\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0meig\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mB\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# raises an error\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", 305 | "\u001b[0;31mTypeError\u001b[0m: 'numpy.ndarray' object is not callable" 306 | ] 307 | } 308 | ], 309 | "source": [ 310 | "from scipy.linalg import eig\n", 311 | "A = array([[1,2],[3,4]])\n", 312 | "(eig, eigvec) = eig(A)\n", 313 | "...\n", 314 | "B=2*A\n", 315 | "(c, d) = eig(B) # raises an error" 316 | ] 317 | }, 318 | { 319 | "cell_type": "code", 320 | "execution_count": 15, 321 | "metadata": {}, 322 | "outputs": [], 323 | "source": [ 324 | "import scipy.linalg as sl\n", 325 | "A = array([[1,2],[3,4]])\n", 326 | "(eig, eigvec) = sl.eig(A) # eig and sl.eig are different objects\n", 327 | "...\n", 328 | "B=2*A\n", 329 | "(c, d) = sl.eig(B)" 330 | ] 331 | }, 332 | { 333 | "cell_type": "code", 334 | "execution_count": 16, 335 | "metadata": {}, 336 | "outputs": [], 337 | "source": [ 338 | "from scipy import *" 339 | ] 340 | }, 341 | { 342 | "cell_type": "markdown", 343 | "metadata": {}, 344 | "source": [ 345 | "### 13.3.2 Modules in IPython\n", 346 | "No code.\n", 347 | "### 13.3.3 The variable `__name__`\n", 348 | "No code.\n", 349 | "### 13.3.4 Some useful modules\n", 350 | "No code.\n" 351 | ] 352 | } 353 | ], 354 | "metadata": { 355 | "celltoolbar": "Tags", 356 | "kernelspec": { 357 | "display_name": "Python 3", 358 | "language": "python", 359 | "name": "python3" 360 | }, 361 | "language_info": { 362 | "codemirror_mode": { 363 | "name": "ipython", 364 | "version": 3 365 | }, 366 | "file_extension": ".py", 367 | "mimetype": "text/x-python", 368 | "name": "python", 369 | "nbconvert_exporter": "python", 370 | "pygments_lexer": "ipython3", 371 | "version": "3.7.6" 372 | } 373 | }, 374 | "nbformat": 4, 375 | "nbformat_minor": 4 376 | } 377 | -------------------------------------------------------------------------------- /Chapter14/a_file.dat: -------------------------------------------------------------------------------- 1 | some data -------------------------------------------------------------------------------- /Chapter14/chapter14.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Scientific Computing with Python (Second Edition)\n", 8 | "# Chapter 14\n", 9 | "\n", 10 | "We start by importing all from Numpy. As explained in Chapter 01 the examples are written assuming this import is initially done." 11 | ] 12 | }, 13 | { 14 | "cell_type": "code", 15 | "execution_count": 1, 16 | "metadata": {}, 17 | "outputs": [], 18 | "source": [ 19 | "from numpy import *" 20 | ] 21 | }, 22 | { 23 | "cell_type": "markdown", 24 | "metadata": {}, 25 | "source": [ 26 | "## 14.1 File handling\n", 27 | "### 14.1.1 Interacting with files" 28 | ] 29 | }, 30 | { 31 | "cell_type": "code", 32 | "execution_count": 2, 33 | "metadata": {}, 34 | "outputs": [], 35 | "source": [ 36 | "# creating a new file object from an existing file\n", 37 | "myfile = open('measurement.dat','r')" 38 | ] 39 | }, 40 | { 41 | "cell_type": "code", 42 | "execution_count": 3, 43 | "metadata": {}, 44 | "outputs": [ 45 | { 46 | "name": "stdout", 47 | "output_type": "stream", 48 | "text": [ 49 | "A demonstration file\n", 50 | "\n" 51 | ] 52 | } 53 | ], 54 | "source": [ 55 | "print(myfile.read())" 56 | ] 57 | }, 58 | { 59 | "cell_type": "code", 60 | "execution_count": 4, 61 | "metadata": {}, 62 | "outputs": [], 63 | "source": [ 64 | "myfile.close() # closes the file object" 65 | ] 66 | }, 67 | { 68 | "cell_type": "code", 69 | "execution_count": 5, 70 | "metadata": {}, 71 | "outputs": [ 72 | { 73 | "name": "stdout", 74 | "output_type": "stream", 75 | "text": [ 76 | "A demonstration file\n", 77 | "\n" 78 | ] 79 | } 80 | ], 81 | "source": [ 82 | "with open('measurement.dat','r') as myfile: \n", 83 | " print(myfile.read())" 84 | ] 85 | }, 86 | { 87 | "cell_type": "code", 88 | "execution_count": 6, 89 | "metadata": { 90 | "tags": [ 91 | "raises-exception" 92 | ] 93 | }, 94 | "outputs": [ 95 | { 96 | "ename": "ZeroDivisionError", 97 | "evalue": "division by zero", 98 | "output_type": "error", 99 | "traceback": [ 100 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 101 | "\u001b[0;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", 102 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mmyfile\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mopen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'a_file.dat'\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m'w'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0mmyfile\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mwrite\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'some data'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0ma\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m/\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 4\u001b[0m \u001b[0mmyfile\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mwrite\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'other data'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0mmyfile\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mclose\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 103 | "\u001b[0;31mZeroDivisionError\u001b[0m: division by zero" 104 | ] 105 | } 106 | ], 107 | "source": [ 108 | "myfile = open('a_file.dat','w')\n", 109 | "myfile.write('some data')\n", 110 | "a = 1/0\n", 111 | "myfile.write('other data')\n", 112 | "myfile.close()" 113 | ] 114 | }, 115 | { 116 | "cell_type": "code", 117 | "execution_count": 7, 118 | "metadata": { 119 | "tags": [ 120 | "raises-exception" 121 | ] 122 | }, 123 | "outputs": [ 124 | { 125 | "ename": "ZeroDivisionError", 126 | "evalue": "division by zero", 127 | "output_type": "error", 128 | "traceback": [ 129 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 130 | "\u001b[0;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", 131 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mwith\u001b[0m \u001b[0mopen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'a_file.dat'\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m'w'\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mmyfile\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0mmyfile\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mwrite\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'some data'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0ma\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m/\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 4\u001b[0m \u001b[0mmyfile\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mwrite\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'other data'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 132 | "\u001b[0;31mZeroDivisionError\u001b[0m: division by zero" 133 | ] 134 | } 135 | ], 136 | "source": [ 137 | "with open('a_file.dat','w') as myfile:\n", 138 | " myfile.write('some data')\n", 139 | " a = 1/0\n", 140 | " myfile.write('other data')" 141 | ] 142 | }, 143 | { 144 | "cell_type": "markdown", 145 | "metadata": {}, 146 | "source": [ 147 | "### 14.1.2 Files are iterables" 148 | ] 149 | }, 150 | { 151 | "cell_type": "code", 152 | "execution_count": 8, 153 | "metadata": {}, 154 | "outputs": [ 155 | { 156 | "name": "stdout", 157 | "output_type": "stream", 158 | "text": [ 159 | "time 06:00 sec temperature 12.0\n", 160 | " C\n", 161 | "time 07:00 sec temperature 14.3\n", 162 | " C\n", 163 | "time 08:00 sec temperature 17.7\n", 164 | " C\n", 165 | "time 09:00 sec temperature 20.2\n", 166 | " C\n", 167 | "time 10:00 sec temperature 19.8\n", 168 | " C\n" 169 | ] 170 | } 171 | ], 172 | "source": [ 173 | "with open('temp.dat','r') as myfile:\n", 174 | " for line in myfile:\n", 175 | " data = line.split(';')\n", 176 | " print(f'time {data[0]} sec temperature {data[1]} C')" 177 | ] 178 | }, 179 | { 180 | "cell_type": "code", 181 | "execution_count": 9, 182 | "metadata": {}, 183 | "outputs": [ 184 | { 185 | "data": { 186 | "text/plain": [ 187 | "['aa', 'bb', 'cc', 'dd', 'ee', 'ff', 'gg']" 188 | ] 189 | }, 190 | "execution_count": 9, 191 | "metadata": {}, 192 | "output_type": "execute_result" 193 | } 194 | ], 195 | "source": [ 196 | "data = 'aa;bb;cc;dd;ee;ff;gg'\n", 197 | "data.split(';') # ['aa', 'bb', 'cc', 'dd', 'ee', 'ff', 'gg']\n", 198 | "\n", 199 | "data = 'aa bb cc dd ee ff gg'\n", 200 | "data.split(' ') # ['aa', 'bb', 'cc', 'dd', 'ee', 'ff', 'gg']" 201 | ] 202 | }, 203 | { 204 | "cell_type": "code", 205 | "execution_count": 10, 206 | "metadata": {}, 207 | "outputs": [ 208 | { 209 | "data": { 210 | "text/plain": [ 211 | "['06:00;12.0\\n',\n", 212 | " '07:00;14.3\\n',\n", 213 | " '08:00;17.7\\n',\n", 214 | " '09:00;20.2\\n',\n", 215 | " '10:00;19.8\\n']" 216 | ] 217 | }, 218 | "execution_count": 10, 219 | "metadata": {}, 220 | "output_type": "execute_result" 221 | } 222 | ], 223 | "source": [ 224 | "with open('temp.dat','r') as myfile:\n", 225 | " data = list(myfile)\n", 226 | "data" 227 | ] 228 | }, 229 | { 230 | "cell_type": "markdown", 231 | "metadata": {}, 232 | "source": [ 233 | "### 14.1.3 File modes" 234 | ] 235 | }, 236 | { 237 | "cell_type": "code", 238 | "execution_count": 11, 239 | "metadata": {}, 240 | "outputs": [], 241 | "source": [ 242 | "with open('file3.dat','a') as myfile:\n", 243 | " myfile.write('something new\\n')" 244 | ] 245 | }, 246 | { 247 | "cell_type": "markdown", 248 | "metadata": {}, 249 | "source": [ 250 | "## 14.2 NumPy methods\n", 251 | "### 14.2.1 savetxt" 252 | ] 253 | }, 254 | { 255 | "cell_type": "code", 256 | "execution_count": 12, 257 | "metadata": {}, 258 | "outputs": [], 259 | "source": [ 260 | "x = range(100) # 100 integers\n", 261 | "savetxt('test.txt',x,delimiter=',') # use comma instead of space\n", 262 | "savetxt('test.txt',x,fmt='%d') # integer format instead of float with e" 263 | ] 264 | }, 265 | { 266 | "cell_type": "markdown", 267 | "metadata": {}, 268 | "source": [ 269 | "### 14.2.3 loadtxt" 270 | ] 271 | }, 272 | { 273 | "cell_type": "code", 274 | "execution_count": 13, 275 | "metadata": {}, 276 | "outputs": [], 277 | "source": [ 278 | "filename = 'test.txt'\n", 279 | "data = loadtxt(filename)" 280 | ] 281 | }, 282 | { 283 | "cell_type": "code", 284 | "execution_count": 14, 285 | "metadata": {}, 286 | "outputs": [ 287 | { 288 | "data": { 289 | "text/plain": [ 290 | "True" 291 | ] 292 | }, 293 | "execution_count": 14, 294 | "metadata": {}, 295 | "output_type": "execute_result" 296 | } 297 | ], 298 | "source": [ 299 | "(data == x).all()" 300 | ] 301 | }, 302 | { 303 | "cell_type": "markdown", 304 | "metadata": {}, 305 | "source": [ 306 | "## 14.3 Pickling" 307 | ] 308 | }, 309 | { 310 | "cell_type": "code", 311 | "execution_count": 15, 312 | "metadata": {}, 313 | "outputs": [], 314 | "source": [ 315 | "import pickle\n", 316 | "with open('file.dat','wb') as myfile:\n", 317 | " a = random.rand(20,20)\n", 318 | " b = 'hello world'\n", 319 | " pickle.dump(a,myfile) # first call: first object\n", 320 | " pickle.dump(b,myfile) # second call: second object\n", 321 | "\n", 322 | "import pickle\n", 323 | "with open('file.dat','rb') as myfile:\n", 324 | " numbers = pickle.load(myfile) # restores the array\n", 325 | " text = pickle.load(myfile) # restores the string" 326 | ] 327 | }, 328 | { 329 | "cell_type": "code", 330 | "execution_count": 16, 331 | "metadata": {}, 332 | "outputs": [ 333 | { 334 | "data": { 335 | "text/plain": [ 336 | "b'\\x80\\x03}q\\x00(X\\x01\\x00\\x00\\x00aq\\x01K\\x01X\\x01\\x00\\x00\\x00bq\\x02K\\x02u.'" 337 | ] 338 | }, 339 | "execution_count": 16, 340 | "metadata": {}, 341 | "output_type": "execute_result" 342 | } 343 | ], 344 | "source": [ 345 | "a = [1,2,3,4]\n", 346 | "pickle.dumps(a) # returns a bytes object\n", 347 | "b = {'a':1,'b':2}\n", 348 | "pickle.dumps(b) # returns a bytes object" 349 | ] 350 | }, 351 | { 352 | "cell_type": "markdown", 353 | "metadata": {}, 354 | "source": [ 355 | "## 14.4 Shelves" 356 | ] 357 | }, 358 | { 359 | "cell_type": "code", 360 | "execution_count": 17, 361 | "metadata": {}, 362 | "outputs": [], 363 | "source": [ 364 | "from contextlib import closing\n", 365 | "import shelve as sv\n", 366 | "# opens a data file (creates it before if necessary)\n", 367 | "with closing(sv.open('datafile')) as data:\n", 368 | " A = array([[1,2,3],[4,5,6]]) \n", 369 | " data['my_matrix'] = A # here we created a key" 370 | ] 371 | }, 372 | { 373 | "cell_type": "code", 374 | "execution_count": 18, 375 | "metadata": {}, 376 | "outputs": [], 377 | "source": [ 378 | "from contextlib import closing\n", 379 | "import shelve as sv\n", 380 | "with closing(sv.open('datafile')) as data: # opens a data file\n", 381 | " A = data['my_matrix'] # here we used the key" 382 | ] 383 | }, 384 | { 385 | "cell_type": "markdown", 386 | "metadata": {}, 387 | "source": [ 388 | "## 14.5 Reading and writing Matlab data files\n", 389 | "You need Matlab to generate a *mat file. We skip this part here" 390 | ] 391 | }, 392 | { 393 | "cell_type": "markdown", 394 | "metadata": {}, 395 | "source": [ 396 | "## 14.6 Reading and writing images" 397 | ] 398 | }, 399 | { 400 | "cell_type": "code", 401 | "execution_count": 19, 402 | "metadata": {}, 403 | "outputs": [ 404 | { 405 | "name": "stdout", 406 | "output_type": "stream", 407 | "text": [ 408 | "(1200, 1200)\n", 409 | "(1200, 1200, 3)\n", 410 | "uint8\n" 411 | ] 412 | } 413 | ], 414 | "source": [ 415 | "import PIL.Image as pil # imports the Pillow module\n", 416 | "\n", 417 | "# read image to array\n", 418 | "im=pil.open(\"test.jpg\")\n", 419 | "print(im.size) # (275, 183) \n", 420 | " # Number of pixels in horizontal and vertical directions\n", 421 | "# resize image\n", 422 | "im_big = im.resize((550, 366))\n", 423 | "im_big_gray = im_big.convert(\"L\") # Convert to grayscale\n", 424 | "\n", 425 | "im_array=array(im)\n", 426 | "\n", 427 | "print(im_array.shape)\n", 428 | "print(im_array.dtype) # unint 8\n", 429 | "# write result to new image file\n", 430 | "im_big_gray.save(\"newimage.jpg\")" 431 | ] 432 | } 433 | ], 434 | "metadata": { 435 | "celltoolbar": "Tags", 436 | "kernelspec": { 437 | "display_name": "Python 3", 438 | "language": "python", 439 | "name": "python3" 440 | }, 441 | "language_info": { 442 | "codemirror_mode": { 443 | "name": "ipython", 444 | "version": 3 445 | }, 446 | "file_extension": ".py", 447 | "mimetype": "text/x-python", 448 | "name": "python", 449 | "nbconvert_exporter": "python", 450 | "pygments_lexer": "ipython3", 451 | "version": "3.7.6" 452 | } 453 | }, 454 | "nbformat": 4, 455 | "nbformat_minor": 4 456 | } 457 | -------------------------------------------------------------------------------- /Chapter14/datafile.bak: -------------------------------------------------------------------------------- 1 | 'my_matrix', (0, 205) 2 | -------------------------------------------------------------------------------- /Chapter14/datafile.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Scientific-Computing-with-Python-Second-Edition/fab030c4283185a66c17692dc202f2e696aacded/Chapter14/datafile.dat -------------------------------------------------------------------------------- /Chapter14/datafile.dir: -------------------------------------------------------------------------------- 1 | 'my_matrix', (0, 205) 2 | -------------------------------------------------------------------------------- /Chapter14/file.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Scientific-Computing-with-Python-Second-Edition/fab030c4283185a66c17692dc202f2e696aacded/Chapter14/file.dat -------------------------------------------------------------------------------- /Chapter14/file3.dat: -------------------------------------------------------------------------------- 1 | something new 2 | something new 3 | -------------------------------------------------------------------------------- /Chapter14/measurement.dat: -------------------------------------------------------------------------------- 1 | A demonstration file 2 | -------------------------------------------------------------------------------- /Chapter14/newimage.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Scientific-Computing-with-Python-Second-Edition/fab030c4283185a66c17692dc202f2e696aacded/Chapter14/newimage.jpg -------------------------------------------------------------------------------- /Chapter14/temp.dat: -------------------------------------------------------------------------------- 1 | 06:00;12.0 2 | 07:00;14.3 3 | 08:00;17.7 4 | 09:00;20.2 5 | 10:00;19.8 6 | -------------------------------------------------------------------------------- /Chapter14/test.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Scientific-Computing-with-Python-Second-Edition/fab030c4283185a66c17692dc202f2e696aacded/Chapter14/test.jpg -------------------------------------------------------------------------------- /Chapter14/test.txt: -------------------------------------------------------------------------------- 1 | 0 2 | 1 3 | 2 4 | 3 5 | 4 6 | 5 7 | 6 8 | 7 9 | 8 10 | 9 11 | 10 12 | 11 13 | 12 14 | 13 15 | 14 16 | 15 17 | 16 18 | 17 19 | 18 20 | 19 21 | 20 22 | 21 23 | 22 24 | 23 25 | 24 26 | 25 27 | 26 28 | 27 29 | 28 30 | 29 31 | 30 32 | 31 33 | 32 34 | 33 35 | 34 36 | 35 37 | 36 38 | 37 39 | 38 40 | 39 41 | 40 42 | 41 43 | 42 44 | 43 45 | 44 46 | 45 47 | 46 48 | 47 49 | 48 50 | 49 51 | 50 52 | 51 53 | 52 54 | 53 55 | 54 56 | 55 57 | 56 58 | 57 59 | 58 60 | 59 61 | 60 62 | 61 63 | 62 64 | 63 65 | 64 66 | 65 67 | 66 68 | 67 69 | 68 70 | 69 71 | 70 72 | 71 73 | 72 74 | 73 75 | 74 76 | 75 77 | 76 78 | 77 79 | 78 80 | 79 81 | 80 82 | 81 83 | 82 84 | 83 85 | 84 86 | 85 87 | 86 88 | 87 89 | 88 90 | 89 91 | 90 92 | 91 93 | 92 94 | 93 95 | 94 96 | 95 97 | 96 98 | 97 99 | 98 100 | 99 101 | -------------------------------------------------------------------------------- /Chapter15/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('No root found within the given tolerance {tol}') 20 | -------------------------------------------------------------------------------- /Chapter15/chapter15.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Scientific Computing with Python (Second Edition)\n", 8 | "# Chapter 15\n", 9 | "\n", 10 | "We start by importing all from Numpy. As explained in Chapter 01 the examples are written assuming this import is initially done." 11 | ] 12 | }, 13 | { 14 | "cell_type": "code", 15 | "execution_count": 1, 16 | "metadata": {}, 17 | "outputs": [], 18 | "source": [ 19 | "from numpy import *" 20 | ] 21 | }, 22 | { 23 | "cell_type": "markdown", 24 | "metadata": {}, 25 | "source": [ 26 | "### 15.1 Manual testing\n", 27 | "No code.\n", 28 | "\n", 29 | "## 15.2 Automatic testing\n", 30 | "### 15.2.1 Testing the bisection algorithm" 31 | ] 32 | }, 33 | { 34 | "cell_type": "code", 35 | "execution_count": 2, 36 | "metadata": {}, 37 | "outputs": [], 38 | "source": [ 39 | "def bisect(f, a, b, tol=1.e-8):\n", 40 | " \"\"\"\n", 41 | " Implementation of the bisection algorithm \n", 42 | " f real valued function\n", 43 | " a,b interval boundaries (float) with the property \n", 44 | " f(a) * f(b) <= 0\n", 45 | " tol tolerance (float)\n", 46 | " \"\"\"\n", 47 | " if f(a) * f(b)> 0:\n", 48 | " raise ValueError(\"Incorrect initial interval [a, b]\") \n", 49 | " for i in range(100):\n", 50 | " c = (a + b) / 2.\n", 51 | " if f(a) * f(c) <= 0:\n", 52 | " b = c\n", 53 | " else:\n", 54 | " a = c\n", 55 | " if abs(a - b) < tol:\n", 56 | " return (a + b) / 2\n", 57 | " raise Exception('No root found within the given tolerance {tol}')" 58 | ] 59 | }, 60 | { 61 | "cell_type": "code", 62 | "execution_count": 3, 63 | "metadata": {}, 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": "code", 76 | "execution_count": 4, 77 | "metadata": {}, 78 | "outputs": [], 79 | "source": [ 80 | "def test_badinput():\n", 81 | " try:\n", 82 | " bisect(lambda x: x,0.5,1)\n", 83 | " except ValueError:\n", 84 | " pass\n", 85 | " else:\n", 86 | " raise AssertionError()\n", 87 | "\n", 88 | "test_badinput()" 89 | ] 90 | }, 91 | { 92 | "cell_type": "code", 93 | "execution_count": 5, 94 | "metadata": {}, 95 | "outputs": [], 96 | "source": [ 97 | "def test_equal_boundaries():\n", 98 | " result = bisect(lambda x: x, 0., 0.)\n", 99 | " expected = 0.\n", 100 | " assert allclose(result, expected), \\\n", 101 | " 'test equal interval bounds failed'\n", 102 | "\n", 103 | "def test_reverse_boundaries():\n", 104 | " result = bisect(lambda x: x, 1., -1.)\n", 105 | " expected = 0.\n", 106 | " assert allclose(result, expected),\\\n", 107 | " 'test reverse int_erval bounds failed'\n", 108 | " \n", 109 | "test_equal_boundaries()\n", 110 | "test_reverse_boundaries()\n" 111 | ] 112 | }, 113 | { 114 | "cell_type": "markdown", 115 | "metadata": {}, 116 | "source": [ 117 | "### 15.2.2 Using the unittest module" 118 | ] 119 | }, 120 | { 121 | "cell_type": "markdown", 122 | "metadata": {}, 123 | "source": [ 124 | "The code examples differ here slightly from those in the book because of the notebook environment.\n", 125 | "The difference is in the call \n", 126 | "`unittest.main(argv=[''], verbosity=2, exit=False)`" 127 | ] 128 | }, 129 | { 130 | "cell_type": "code", 131 | "execution_count": 6, 132 | "metadata": {}, 133 | "outputs": [ 134 | { 135 | "name": "stderr", 136 | "output_type": "stream", 137 | "text": [ 138 | "test (__main__.TestIdentity) ... ok\n", 139 | "\n", 140 | "----------------------------------------------------------------------\n", 141 | "Ran 1 test in 0.001s\n", 142 | "\n", 143 | "OK\n" 144 | ] 145 | } 146 | ], 147 | "source": [ 148 | "from bisection import bisect\n", 149 | "import unittest\n", 150 | "\n", 151 | "class TestIdentity(unittest.TestCase):\n", 152 | " def test(self):\n", 153 | " result = bisect(lambda x: x, -1.2, 1.,tol=1.e-8)\n", 154 | " expected = 0.\n", 155 | " self.assertAlmostEqual(result, expected)\n", 156 | "\n", 157 | "if __name__=='__main__':\n", 158 | " unittest.main(argv=[''], verbosity=2, exit=False)" 159 | ] 160 | }, 161 | { 162 | "cell_type": "code", 163 | "execution_count": 7, 164 | "metadata": {}, 165 | "outputs": [ 166 | { 167 | "name": "stderr", 168 | "output_type": "stream", 169 | "text": [ 170 | "test (__main__.TestIdentity) ... FAIL\n", 171 | "\n", 172 | "======================================================================\n", 173 | "FAIL: test (__main__.TestIdentity)\n", 174 | "----------------------------------------------------------------------\n", 175 | "Traceback (most recent call last):\n", 176 | " File \"\", line 8, in test\n", 177 | " self.assertAlmostEqual(result, expected)\n", 178 | "AssertionError: 0.00017089843750002018 != 0.0 within 7 places (0.00017089843750002018 difference)\n", 179 | "\n", 180 | "----------------------------------------------------------------------\n", 181 | "Ran 1 test in 0.001s\n", 182 | "\n", 183 | "FAILED (failures=1)\n" 184 | ] 185 | } 186 | ], 187 | "source": [ 188 | "from bisection import bisect\n", 189 | "import unittest\n", 190 | "\n", 191 | "class TestIdentity(unittest.TestCase):\n", 192 | " def test(self):\n", 193 | " result = bisect(lambda x: x, -1.2, 1.,tol=1.e-3)\n", 194 | " expected = 0.\n", 195 | " self.assertAlmostEqual(result, expected)\n", 196 | "\n", 197 | "if __name__=='__main__':\n", 198 | " unittest.main(argv=[''], verbosity=2, exit=False)" 199 | ] 200 | }, 201 | { 202 | "cell_type": "code", 203 | "execution_count": 8, 204 | "metadata": {}, 205 | "outputs": [ 206 | { 207 | "name": "stderr", 208 | "output_type": "stream", 209 | "text": [ 210 | "test_exceeded_tolerance (__main__.TestIdentity) ... ok\n", 211 | "test_functionality (__main__.TestIdentity) ... ok\n", 212 | "test_reverse_boundaries (__main__.TestIdentity) ... ok\n", 213 | "\n", 214 | "----------------------------------------------------------------------\n", 215 | "Ran 3 tests in 0.002s\n", 216 | "\n", 217 | "OK\n" 218 | ] 219 | } 220 | ], 221 | "source": [ 222 | "import unittest\n", 223 | "from bisection import bisect\n", 224 | "\n", 225 | "class TestIdentity(unittest.TestCase):\n", 226 | " def identity_fcn(self,x):\n", 227 | " return x\n", 228 | " def test_functionality(self):\n", 229 | " result = bisect(self.identity_fcn, -1.2, 1.,tol=1.e-8)\n", 230 | " expected = 0.\n", 231 | " self.assertAlmostEqual(result, expected)\n", 232 | " def test_reverse_boundaries(self):\n", 233 | " result = bisect(self.identity_fcn, 1., -1.)\n", 234 | " expected = 0.\n", 235 | " self.assertAlmostEqual(result, expected)\n", 236 | " def test_exceeded_tolerance(self):\n", 237 | " tol=1.e-80\n", 238 | " self.assertRaises(Exception, bisect, self.identity_fcn,\n", 239 | " -1.2, 1.,tol)\n", 240 | "if __name__=='__main__':\n", 241 | " unittest.main(argv=[''], verbosity=2, exit=False)" 242 | ] 243 | }, 244 | { 245 | "cell_type": "markdown", 246 | "metadata": {}, 247 | "source": [ 248 | "### 15.2.3 Test setUp and tearDown methods" 249 | ] 250 | }, 251 | { 252 | "cell_type": "code", 253 | "execution_count": 9, 254 | "metadata": {}, 255 | "outputs": [], 256 | "source": [ 257 | "class StringNotFoundException(Exception):\n", 258 | " pass\n", 259 | "\n", 260 | "def find_string(file, string):\n", 261 | " for i,lines in enumerate(file.readlines()):\n", 262 | " if string in lines:\n", 263 | " return i\n", 264 | " raise StringNotFoundException(\n", 265 | " f'String {string} not found in File {file.name}.')" 266 | ] 267 | }, 268 | { 269 | "cell_type": "code", 270 | "execution_count": 10, 271 | "metadata": {}, 272 | "outputs": [ 273 | { 274 | "name": "stderr", 275 | "output_type": "stream", 276 | "text": [ 277 | "test_exists (__main__.TestFindInFile) ... ok\n", 278 | "test_not_exists (__main__.TestFindInFile) ... ok\n", 279 | "test_exceeded_tolerance (__main__.TestIdentity) ... ok\n", 280 | "test_functionality (__main__.TestIdentity) ... ok\n", 281 | "test_reverse_boundaries (__main__.TestIdentity) ... ok\n", 282 | "\n", 283 | "----------------------------------------------------------------------\n", 284 | "Ran 5 tests in 0.003s\n", 285 | "\n", 286 | "OK\n" 287 | ] 288 | } 289 | ], 290 | "source": [ 291 | "import unittest\n", 292 | "import os # used for, for example, deleting files\n", 293 | "\n", 294 | "from find_in_file import find_string, StringNotFoundException\n", 295 | "\n", 296 | "class TestFindInFile(unittest.TestCase):\n", 297 | " def setUp(self):\n", 298 | " file = open('test_file.txt', 'w')\n", 299 | " file.write('bird')\n", 300 | " file.close()\n", 301 | " self.file = open('test_file.txt', 'r')\n", 302 | " def tearDown(self):\n", 303 | " self.file.close()\n", 304 | " os.remove(self.file.name)\n", 305 | " def test_exists(self):\n", 306 | " line_no=find_string(self.file, 'bird')\n", 307 | " self.assertEqual(line_no, 0)\n", 308 | " def test_not_exists(self):\n", 309 | " self.assertRaises(StringNotFoundException, find_string,\n", 310 | " self.file, 'tiger')\n", 311 | "\n", 312 | "if __name__=='__main__':\n", 313 | " unittest.main(argv=[''], verbosity=2, exit=False)" 314 | ] 315 | }, 316 | { 317 | "cell_type": "code", 318 | "execution_count": 11, 319 | "metadata": {}, 320 | "outputs": [], 321 | "source": [ 322 | "class Tests(unittest.TestCase):\n", 323 | " def checkifzero(self,fcn_with_zero,interval):\n", 324 | " result = bisect(fcn_with_zero,*interval,tol=1.e-8)\n", 325 | " function_value=fcn_with_zero(result)\n", 326 | " expected=0.\n", 327 | " self.assertAlmostEqual(function_value, expected)" 328 | ] 329 | }, 330 | { 331 | "cell_type": "code", 332 | "execution_count": 12, 333 | "metadata": {}, 334 | "outputs": [ 335 | { 336 | "name": "stderr", 337 | "output_type": "stream", 338 | "text": [ 339 | "test_exists (__main__.TestFindInFile) ... ok\n", 340 | "test_not_exists (__main__.TestFindInFile) ... ok\n", 341 | "test_exceeded_tolerance (__main__.TestIdentity) ... ok\n", 342 | "test_functionality (__main__.TestIdentity) ... ok\n", 343 | "test_reverse_boundaries (__main__.TestIdentity) ... ok\n", 344 | "test_cubic (__main__.Tests) ... ok\n", 345 | "test_identity (__main__.Tests) ... ok\n", 346 | "test_parabola (__main__.Tests) ... ok\n", 347 | "\n", 348 | "----------------------------------------------------------------------\n", 349 | "Ran 8 tests in 0.006s\n", 350 | "\n", 351 | "OK\n" 352 | ] 353 | } 354 | ], 355 | "source": [ 356 | "test_data=[\n", 357 | " {'name':'identity', 'function':lambda x: x,\n", 358 | " 'interval' : [-1.2, 1.]},\n", 359 | " {'name':'parabola', 'function':lambda x: x**2-1,\n", 360 | " 'interval' :[0, 10.]},\n", 361 | " {'name':'cubic', 'function':lambda x: x**3-2*x**2,\n", 362 | " 'interval':[0.1, 5.]},\n", 363 | " ] \n", 364 | "def make_test_function(dic):\n", 365 | " return lambda self :\\\n", 366 | " self.checkifzero(dic['function'],dic['interval'])\n", 367 | "for data in test_data:\n", 368 | " setattr(Tests, f\"test_{data['name']}\", make_test_function(data))\n", 369 | "\n", 370 | "if __name__=='__main__': \n", 371 | " unittest.main(argv=[''], verbosity=2, exit=False)" 372 | ] 373 | }, 374 | { 375 | "cell_type": "markdown", 376 | "metadata": {}, 377 | "source": [ 378 | "### 15.2.5 Assertion tools\n", 379 | "No code.\n", 380 | "### 15.2.6 Float comparisons" 381 | ] 382 | }, 383 | { 384 | "cell_type": "code", 385 | "execution_count": 13, 386 | "metadata": {}, 387 | "outputs": [], 388 | "source": [ 389 | "import numpy.linalg as nla\n", 390 | "A=random.rand(10,10)\n", 391 | "[Q,R]=nla.qr(A)" 392 | ] 393 | }, 394 | { 395 | "cell_type": "code", 396 | "execution_count": 14, 397 | "metadata": {}, 398 | "outputs": [], 399 | "source": [ 400 | "import numpy.testing as npt \n", 401 | "npt.assert_allclose(\n", 402 | " Q.T @ Q,identity(Q.shape[0]),atol=1.e-12)" 403 | ] 404 | }, 405 | { 406 | "cell_type": "code", 407 | "execution_count": 15, 408 | "metadata": {}, 409 | "outputs": [], 410 | "source": [ 411 | "import numpy.testing as npt\n", 412 | "npt.assert_allclose(Q @ R,A)" 413 | ] 414 | }, 415 | { 416 | "cell_type": "code", 417 | "execution_count": 16, 418 | "metadata": {}, 419 | "outputs": [ 420 | { 421 | "name": "stderr", 422 | "output_type": "stream", 423 | "text": [ 424 | "test_exists (__main__.TestFindInFile) ... ok\n", 425 | "test_not_exists (__main__.TestFindInFile) ... ok\n", 426 | "test_exceeded_tolerance (__main__.TestIdentity) ... ok\n", 427 | "test_functionality (__main__.TestIdentity) ... ok\n", 428 | "test_reverse_boundaries (__main__.TestIdentity) ... ok\n", 429 | "test_orthogonal (__main__.TestQR) ... ok\n", 430 | "test_sanity (__main__.TestQR) ... ok\n", 431 | "test_cubic (__main__.Tests) ... ok\n", 432 | "test_identity (__main__.Tests) ... ok\n", 433 | "test_parabola (__main__.Tests) ... ok\n", 434 | "\n", 435 | "----------------------------------------------------------------------\n", 436 | "Ran 10 tests in 0.007s\n", 437 | "\n", 438 | "OK\n" 439 | ] 440 | } 441 | ], 442 | "source": [ 443 | "import unittest\n", 444 | "import numpy.testing as npt\n", 445 | "from numpy.linalg import qr\n", 446 | "\n", 447 | "class TestQR(unittest.TestCase):\n", 448 | " def setUp(self):\n", 449 | " self.A=random.rand(10,10)\n", 450 | " [self.Q,self.R]=qr(self.A)\n", 451 | " def test_orthogonal(self):\n", 452 | " npt.assert_allclose(\n", 453 | " self.Q.T @ self.Q,identity(self.Q.shape[0]),\n", 454 | " atol=1.e-12)\n", 455 | " def test_sanity(self):\n", 456 | " npt.assert_allclose(self.Q @ self.R,self.A)\n", 457 | "\n", 458 | "if __name__=='__main__':\n", 459 | " unittest.main(argv=[''], verbosity=2, exit=False)" 460 | ] 461 | }, 462 | { 463 | "cell_type": "markdown", 464 | "metadata": {}, 465 | "source": [ 466 | "### 15.2.7 Unit and functional tests" 467 | ] 468 | }, 469 | { 470 | "cell_type": "code", 471 | "execution_count": 17, 472 | "metadata": {}, 473 | "outputs": [], 474 | "source": [ 475 | "def bisect_step(f, a, b, n):\n", 476 | " \"\"\"\n", 477 | " Implementation of the bisection algorithm\n", 478 | " f real valued function\n", 479 | " a,b interval boundaries (float) with the property\n", 480 | " f(a) * f(b) <= 0\n", 481 | " tol tolerance (float)\n", 482 | " \"\"\"\n", 483 | " for iteration in range(n):\n", 484 | " if f(a) * f(b)> 0:\n", 485 | " raise ValueError(\"Incorrect initial interval [a, b]\")\n", 486 | " c = (a + b) / 2.\n", 487 | " if f(a) * f(c) <= 0:\n", 488 | " b = c\n", 489 | " else:\n", 490 | " a = c\n", 491 | " return a,b" 492 | ] 493 | }, 494 | { 495 | "cell_type": "code", 496 | "execution_count": 18, 497 | "metadata": {}, 498 | "outputs": [ 499 | { 500 | "name": "stderr", 501 | "output_type": "stream", 502 | "text": [ 503 | "test_exists (__main__.TestFindInFile) ... ok\n", 504 | "test_not_exists (__main__.TestFindInFile) ... ok\n", 505 | "test_exceeded_tolerance (__main__.TestIdentity) ... ok\n", 506 | "test_functionality (__main__.TestIdentity) ... ok\n", 507 | "test_reverse_boundaries (__main__.TestIdentity) ... ok\n", 508 | "test_midpoint (__main__.TestMidpoint) ... ok\n", 509 | "test_orthogonal (__main__.TestQR) ... ok\n", 510 | "test_sanity (__main__.TestQR) ... ok\n", 511 | "test_cubic (__main__.Tests) ... ok\n", 512 | "test_identity (__main__.Tests) ... ok\n", 513 | "test_parabola (__main__.Tests) ... ok\n", 514 | "\n", 515 | "----------------------------------------------------------------------\n", 516 | "Ran 11 tests in 0.012s\n", 517 | "\n", 518 | "OK\n" 519 | ] 520 | } 521 | ], 522 | "source": [ 523 | "import unittest\n", 524 | "\n", 525 | "class TestMidpoint(unittest.TestCase):\n", 526 | " def identity_fcn(self,x):\n", 527 | " return x\n", 528 | " def test_midpoint(self):\n", 529 | " a,b = bisect_step(self.identity_fcn,-2.,1.,1)\n", 530 | " self.assertAlmostEqual(a,-0.5)\n", 531 | " self.assertAlmostEqual(b,1)\n", 532 | "if __name__=='__main__':\n", 533 | " unittest.main(argv=[''], verbosity=2, exit=False)" 534 | ] 535 | }, 536 | { 537 | "cell_type": "markdown", 538 | "metadata": {}, 539 | "source": [ 540 | "### 15.2.8 Debugging" 541 | ] 542 | }, 543 | { 544 | "cell_type": "code", 545 | "execution_count": 19, 546 | "metadata": {}, 547 | "outputs": [], 548 | "source": [ 549 | "test_case = TestIdentity(methodName='test_reverse_boundaries')" 550 | ] 551 | }, 552 | { 553 | "cell_type": "code", 554 | "execution_count": 20, 555 | "metadata": {}, 556 | "outputs": [], 557 | "source": [ 558 | "test_case.debug()" 559 | ] 560 | }, 561 | { 562 | "cell_type": "markdown", 563 | "metadata": {}, 564 | "source": [ 565 | "## 15.3 Measuring execution time\n", 566 | "### 15.3.1 Timing with a magic function" 567 | ] 568 | }, 569 | { 570 | "cell_type": "code", 571 | "execution_count": 21, 572 | "metadata": {}, 573 | "outputs": [], 574 | "source": [ 575 | "A=zeros((1000,1000))\n", 576 | "A[53,67]=10\n", 577 | "\n", 578 | "def find_elements_1(A):\n", 579 | " b = []\n", 580 | " n, m = A.shape\n", 581 | " for i in range(n):\n", 582 | " for j in range(m):\n", 583 | " if abs(A[i, j]) > 1.e-10:\n", 584 | " b.append(A[i, j])\n", 585 | " return b\n", 586 | "\n", 587 | "def find_elements_2(A):\n", 588 | " return [a for a in A.reshape((-1, )) if abs(a) > 1.e-10]\n", 589 | "\n", 590 | "def find_elements_3(A):\n", 591 | " return [a for a in A.flatten() if abs(a) > 1.e-10]\n", 592 | " \n", 593 | "def find_elements_4(A):\n", 594 | " return A[where(0.0 != A)]" 595 | ] 596 | }, 597 | { 598 | "cell_type": "code", 599 | "execution_count": 22, 600 | "metadata": {}, 601 | "outputs": [ 602 | { 603 | "name": "stdout", 604 | "output_type": "stream", 605 | "text": [ 606 | "257 ms ± 123 µs per loop (mean ± std. dev. of 3 runs, 50 loops each)\n" 607 | ] 608 | } 609 | ], 610 | "source": [ 611 | "%timeit -n 50 -r 3 find_elements_1(A)" 612 | ] 613 | }, 614 | { 615 | "cell_type": "code", 616 | "execution_count": 23, 617 | "metadata": {}, 618 | "outputs": [ 619 | { 620 | "name": "stdout", 621 | "output_type": "stream", 622 | "text": [ 623 | "191 ms ± 406 µs per loop (mean ± std. dev. of 3 runs, 50 loops each)\n" 624 | ] 625 | } 626 | ], 627 | "source": [ 628 | "%timeit -n 50 -r 3 find_elements_2(A)" 629 | ] 630 | }, 631 | { 632 | "cell_type": "code", 633 | "execution_count": 24, 634 | "metadata": {}, 635 | "outputs": [ 636 | { 637 | "name": "stdout", 638 | "output_type": "stream", 639 | "text": [ 640 | "205 ms ± 5.67 ms per loop (mean ± std. dev. of 3 runs, 50 loops each)\n" 641 | ] 642 | } 643 | ], 644 | "source": [ 645 | "%timeit -n 50 -r 3 find_elements_3(A)" 646 | ] 647 | }, 648 | { 649 | "cell_type": "code", 650 | "execution_count": 25, 651 | "metadata": {}, 652 | "outputs": [ 653 | { 654 | "name": "stdout", 655 | "output_type": "stream", 656 | "text": [ 657 | "1.78 ms ± 22.4 µs per loop (mean ± std. dev. of 3 runs, 50 loops each)\n" 658 | ] 659 | } 660 | ], 661 | "source": [ 662 | "%timeit -n 50 -r 3 find_elements_4(A)" 663 | ] 664 | }, 665 | { 666 | "cell_type": "markdown", 667 | "metadata": {}, 668 | "source": [ 669 | "### 15.3.2 Timing with the Python module timeit\n" 670 | ] 671 | }, 672 | { 673 | "cell_type": "code", 674 | "execution_count": 26, 675 | "metadata": {}, 676 | "outputs": [], 677 | "source": [ 678 | "import timeit\n", 679 | "setup_statements=\"\"\"\n", 680 | "from scipy import zeros\n", 681 | "from numpy import where\n", 682 | "A=zeros((1000,1000))\n", 683 | "A[57,63]=10.\n", 684 | "\n", 685 | "def find_elements_1(A):\n", 686 | " b = []\n", 687 | " n, m = A.shape\n", 688 | " for i in range(n):\n", 689 | " for j in range(m):\n", 690 | " if abs(A[i, j]) > 1.e-10:\n", 691 | " b.append(A[i, j])\n", 692 | " return b\n", 693 | "\n", 694 | "def find_elements_2(A):\n", 695 | " return [a for a in A.reshape((-1,)) if abs(a) > 1.e-10]\n", 696 | "\n", 697 | "def find_elements_3(A):\n", 698 | " return [a for a in A.flatten() if abs(a) > 1.e-10]\n", 699 | "\n", 700 | "def find_elements_4(A):\n", 701 | " return A[where( 0.0 != A)]\n", 702 | "\"\"\"\n", 703 | "experiment_1 = timeit.Timer(stmt = 'find_elements_1(A)',\n", 704 | " setup = setup_statements)\n", 705 | "experiment_2 = timeit.Timer(stmt = 'find_elements_2(A)',\n", 706 | " setup = setup_statements)\n", 707 | "experiment_3 = timeit.Timer(stmt = 'find_elements_3(A)',\n", 708 | " setup = setup_statements)\n", 709 | "experiment_4 = timeit.Timer(stmt = 'find_elements_4(A)',\n", 710 | " setup = setup_statements)" 711 | ] 712 | }, 713 | { 714 | "cell_type": "code", 715 | "execution_count": 27, 716 | "metadata": {}, 717 | "outputs": [ 718 | { 719 | "data": { 720 | "text/plain": [ 721 | "1.903121208306402" 722 | ] 723 | }, 724 | "execution_count": 27, 725 | "metadata": {}, 726 | "output_type": "execute_result" 727 | } 728 | ], 729 | "source": [ 730 | "t1 = experiment_1.repeat(3,5) \n", 731 | "t2 = experiment_2.repeat(3,5) \n", 732 | "t3 = experiment_3.repeat(3,5) \n", 733 | "t4 = experiment_4.repeat(3,5) \n", 734 | "# Results per loop in ms\n", 735 | "min(t1)*1000/5 # 615 ms\n", 736 | "min(t2)*1000/5 # 543 ms\n", 737 | "min(t3)*1000/5 # 546 ms\n", 738 | "min(t4)*1000/5 # 7.26 ms" 739 | ] 740 | }, 741 | { 742 | "cell_type": "markdown", 743 | "metadata": {}, 744 | "source": [ 745 | "### 15.3.3 Timing with a context manager" 746 | ] 747 | }, 748 | { 749 | "cell_type": "code", 750 | "execution_count": 28, 751 | "metadata": {}, 752 | "outputs": [], 753 | "source": [ 754 | "import time\n", 755 | "class Timer:\n", 756 | " def __enter__(self):\n", 757 | " self.start = time.time()\n", 758 | " # return self\n", 759 | " def __exit__(self, ty, val, tb):\n", 760 | " end = time.time()\n", 761 | " self.elapsed=end-self.start\n", 762 | " print(f'Time elapsed {self.elapsed} seconds') \n", 763 | " return False" 764 | ] 765 | }, 766 | { 767 | "cell_type": "code", 768 | "execution_count": 29, 769 | "metadata": {}, 770 | "outputs": [ 771 | { 772 | "name": "stdout", 773 | "output_type": "stream", 774 | "text": [ 775 | "Time elapsed 0.2798018455505371 seconds\n" 776 | ] 777 | } 778 | ], 779 | "source": [ 780 | "with Timer():\n", 781 | " find_elements_1(A)" 782 | ] 783 | }, 784 | { 785 | "cell_type": "code", 786 | "execution_count": 30, 787 | "metadata": {}, 788 | "outputs": [ 789 | { 790 | "name": "stdout", 791 | "output_type": "stream", 792 | "text": [ 793 | "Time elapsed 0.23056364059448242 seconds\n" 794 | ] 795 | } 796 | ], 797 | "source": [ 798 | "with Timer():\n", 799 | " find_elements_2(A)" 800 | ] 801 | }, 802 | { 803 | "cell_type": "code", 804 | "execution_count": 31, 805 | "metadata": {}, 806 | "outputs": [ 807 | { 808 | "name": "stdout", 809 | "output_type": "stream", 810 | "text": [ 811 | "Time elapsed 0.21068072319030762 seconds\n" 812 | ] 813 | } 814 | ], 815 | "source": [ 816 | "with Timer():\n", 817 | " find_elements_3(A)" 818 | ] 819 | }, 820 | { 821 | "cell_type": "code", 822 | "execution_count": 32, 823 | "metadata": {}, 824 | "outputs": [ 825 | { 826 | "name": "stdout", 827 | "output_type": "stream", 828 | "text": [ 829 | "Time elapsed 0.002699613571166992 seconds\n" 830 | ] 831 | } 832 | ], 833 | "source": [ 834 | "with Timer():\n", 835 | " find_elements_4(A)" 836 | ] 837 | } 838 | ], 839 | "metadata": { 840 | "kernelspec": { 841 | "display_name": "Python 3", 842 | "language": "python", 843 | "name": "python3" 844 | }, 845 | "language_info": { 846 | "codemirror_mode": { 847 | "name": "ipython", 848 | "version": 3 849 | }, 850 | "file_extension": ".py", 851 | "mimetype": "text/x-python", 852 | "name": "python", 853 | "nbconvert_exporter": "python", 854 | "pygments_lexer": "ipython3", 855 | "version": "3.7.6" 856 | } 857 | }, 858 | "nbformat": 4, 859 | "nbformat_minor": 4 860 | } 861 | -------------------------------------------------------------------------------- /Chapter15/find_in_file.py: -------------------------------------------------------------------------------- 1 | class StringNotFoundException(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 StringNotFoundException( 9 | f'String {string} not found in File {file.name}.') 10 | -------------------------------------------------------------------------------- /Chapter18/Untitled.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [], 3 | "metadata": {}, 4 | "nbformat": 4, 5 | "nbformat_minor": 4 6 | } 7 | -------------------------------------------------------------------------------- /Chapter18/ch18.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Scientific Computing with Python (Second Edition)\n", 8 | "\n", 9 | "## Chapter 18: Comprehensive Examples\n", 10 | "\n", 11 | "*We start by importing all from Numpy. As explained in Chapter 01 the examples are written assuming this import is initially done.*\n" 12 | ] 13 | }, 14 | { 15 | "cell_type": "code", 16 | "execution_count": null, 17 | "metadata": {}, 18 | "outputs": [], 19 | "source": [ 20 | "from mpi4py import MPI\n", 21 | "comm=MPI.COMM_WORLD # making a communicator instance\n", 22 | "rank=comm.Get_rank() # querrying for the numeric identifyer of the core \n", 23 | "size=comm.Get_size() # the total number of cores assigned" 24 | ] 25 | }, 26 | { 27 | "cell_type": "code", 28 | "execution_count": null, 29 | "metadata": {}, 30 | "outputs": [], 31 | "source": [ 32 | "from mpi4py import MPI\n", 33 | "comm=MPI.COMM_WORLD # making a communicator instance\n", 34 | "rank=comm.Get_rank() # querrying for the numeric identifyer of the core \n", 35 | "size=comm.Get_size() # the total number of cores assigned \n", 36 | "a=15\n", 37 | "b=2\n", 38 | "if rank==0:\n", 39 | " print(f'Core {rank} computes {a}+{b}={a+b}')\n", 40 | "if rank==1:\n", 41 | " print(f'Core {rank} computes {a}*{b}={a*b}')\n", 42 | "if rank==2:\n", 43 | " print(f'Core {rank} computes {a}**{b}={a**b}')" 44 | ] 45 | }, 46 | { 47 | "cell_type": "code", 48 | "execution_count": 1, 49 | "metadata": {}, 50 | "outputs": [ 51 | { 52 | "name": "stderr", 53 | "output_type": "stream", 54 | "text": [ 55 | "UsageError: Cell magic `%%px` not found.\n" 56 | ] 57 | } 58 | ], 59 | "source": [ 60 | "%%px --targets ::2" 61 | ] 62 | }, 63 | { 64 | "cell_type": "code", 65 | "execution_count": null, 66 | "metadata": {}, 67 | "outputs": [], 68 | "source": [ 69 | "from IPython import *\n", 70 | "from mpi4py import MPI\n", 71 | "comm=MPI.COMM_WORLD # making a communicator instance\n", 72 | "rank=comm.Get_rank() # querying for the numeric identifier of the core \n", 73 | "size=comm.Get_size() # the total number of cores assigned \n", 74 | "if not (size==2):\n", 75 | " raise Exception(f\"This examples requires two processes.\" \\\n", 76 | " f\"{size} processes given.\")" 77 | ] 78 | }, 79 | { 80 | "cell_type": "code", 81 | "execution_count": null, 82 | "metadata": {}, 83 | "outputs": [], 84 | "source": [ 85 | "print(size)" 86 | ] 87 | }, 88 | { 89 | "cell_type": "code", 90 | "execution_count": null, 91 | "metadata": {}, 92 | "outputs": [], 93 | "source": [] 94 | } 95 | ], 96 | "metadata": { 97 | "kernelspec": { 98 | "display_name": "Python 3", 99 | "language": "python", 100 | "name": "python3" 101 | }, 102 | "language_info": { 103 | "codemirror_mode": { 104 | "name": "ipython", 105 | "version": 3 106 | }, 107 | "file_extension": ".py", 108 | "mimetype": "text/x-python", 109 | "name": "python", 110 | "nbconvert_exporter": "python", 111 | "pygments_lexer": "ipython3", 112 | "version": "3.7.6" 113 | } 114 | }, 115 | "nbformat": 4, 116 | "nbformat_minor": 4 117 | } 118 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Packt 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 |

Machine Learning Summit 2025

2 | 3 | ## Machine Learning Summit 2025 4 | **Bridging Theory and Practice: ML Solutions for Today’s Challenges** 5 | 6 | 3 days, 20+ experts, and 25+ tech sessions and talks covering critical aspects of: 7 | - **Agentic and Generative AI** 8 | - **Applied Machine Learning in the Real World** 9 | - **ML Engineering and Optimization** 10 | 11 | 👉 [Book your ticket now >>](https://packt.link/mlsumgh) 12 | 13 | --- 14 | 15 | ## Join Our Newsletters 📬 16 | 17 | ### DataPro 18 | *The future of AI is unfolding. Don’t fall behind.* 19 | 20 |

DataPro QR

21 | 22 | Stay ahead with [**DataPro**](https://landing.packtpub.com/subscribe-datapronewsletter/?link_from_packtlink=yes), the free weekly newsletter for data scientists, AI/ML researchers, and data engineers. 23 | From trending tools like **PyTorch**, **scikit-learn**, **XGBoost**, and **BentoML** to hands-on insights on **database optimization** and real-world **ML workflows**, you’ll get what matters, fast. 24 | 25 | > Stay sharp with [DataPro](https://landing.packtpub.com/subscribe-datapronewsletter/?link_from_packtlink=yes). Join **115K+ data professionals** who never miss a beat. 26 | 27 | --- 28 | 29 | ### BIPro 30 | *Business runs on data. Make sure yours tells the right story.* 31 | 32 |

BIPro QR

33 | 34 | [**BIPro**](https://landing.packtpub.com/subscribe-bipro-newsletter/?link_from_packtlink=yes) is your free weekly newsletter for BI professionals, analysts, and data leaders. 35 | Get practical tips on **dashboarding**, **data visualization**, and **analytics strategy** with tools like **Power BI**, **Tableau**, **Looker**, **SQL**, and **dbt**. 36 | 37 | > Get smarter with [BIPro](https://landing.packtpub.com/subscribe-bipro-newsletter/?link_from_packtlink=yes). Trusted by **35K+ BI professionals**, see what you’re missing. 38 | 39 | 40 | 41 | 42 | # Scientific Computing with Python - Second Edition 43 | 44 | Scientific Computing with Python - Second Edition 45 | 46 | This is the code repository for [Scientific Computing with Python - Second Edition](https://www.packtpub.com/product/Scientific-Computing-with-Python-Second-Edition/9781838822323?utm_source=github&utm_medium=repository&utm_campaign=9781838822323), published by Packt. 47 | 48 | **High-performance scientific computing with NumPy, SciPy, and pandas** 49 | 50 | ## What is this book about? 51 | Python has tremendous potential within the scientific computing domain. This updated edition of Scientific Computing with Python features new chapters on graphical user interfaces, efficient data processing, and parallel computing to help you perform mathematical and scientific computing efficiently using Python. 52 | 53 | This book will help you to explore new Python syntax features and create different models using scientific computing principles. The book presents Python alongside mathematical applications and demonstrates how to apply Python concepts in computing with the help of examples involving Python 3.8. You'll use pandas for basic data analysis to understand the modern needs of scientific computing, and cover data module improvements and built-in features. You'll also explore numerical computation modules such as NumPy and SciPy, which enable fast access to highly efficient numerical algorithms. By learning to use the plotting module Matplotlib, you will be able to represent your computational results in talks and publications. A special chapter is devoted to SymPy, a tool for bridging symbolic and numerical computations. 54 | 55 | By the end of this Python book, you'll have gained a solid understanding of task automation and how to implement and test mathematical algorithms within the realm of scientific computing. 56 | 57 | This book covers the following exciting features: 58 | * Understand the building blocks of computational mathematics, linear algebra, and related Python objects 59 | * Use Matplotlib to create high-quality figures and graphics to draw and visualize results 60 | * Apply object-oriented programming (OOP) to scientific computing in Python 61 | * Discover how to use pandas to enter the world of data processing 62 | * Handle exceptions for writing reliable and usable code 63 | * Cover manual and automatic aspects of testing for scientific programming 64 | * Get to grips with parallel computing to increase computation speed 65 | 66 | If you feel this book is for you, get your [copy](https://www.amazon.com/dp/1838822321) today! 67 | 68 | https://www.packtpub.com/ 69 | 70 | ## Instructions and Navigations 71 | All of the code is organized into folders. 72 | 73 | The code will look like the following: 74 | ``` 75 | t=symbols('t') 76 | x=[0,t,1] 77 | 78 | # The Vandermonde Matrix 79 | V = Matrix([[0, 0, 1], [t**2, t, 1], [1, 1,1]]) 80 | y = Matrix([0,1,-1]) # the data vector 81 | a = simplify(V.LUsolve(y)) # the coefficients 82 | # the leading coefficient as a function of the parameter 83 | a2 = Lambda(t,a[0]) 84 | 85 | ``` 86 | 87 | **Following is what you need for this book:** 88 | This book is for students with a mathematical background, university teachers designing modern courses in programming, data scientists, researchers, developers, and anyone who wants to perform scientific computation in Python. The book evolved from 13 years of Python teaching in undergraduate science and engineering programs, as special industry in-house courses and specialization courses for high school teachers. The typical reader has the need to use Python in areas like mathematics, big data processings, machine learning and simulation. Therefore a basic knowledge of vectors and matrices as well of notions like convergence and iterative processes is beneficial. 89 | 90 | This book is intended for beginners or readers who have some experience in programming. You can read the book either from the first page to the last, or by picking the bits that seem most interesting. Prior knowledge of Python is not mandatory. 91 | 92 | With the following software and hardware list you can run all code files present in the book (Chapter 1-9). 93 | 94 | ### Software and Hardware List 95 | 96 | | Chapter | Software required | OS required | 97 | | -------- | -------------------------------------------------------------------------------------| -----------------------------------| 98 | | 1 - 19 | Anaconda, Python 3.8, JupyterLab | Windows, Mac OS X, and Linux (Any) | 99 | 100 | We also provide a PDF file that has color images of the screenshots/diagrams used in this book. [Click here to download it](https://static.packt-cdn.com/downloads/9781838822323_ColorImages.pdf). 101 | 102 | 103 | ### Related products 104 | * Learn Amazon SageMaker [[Packt]](https://www.packtpub.com/product/learn-amazon-sagemaker/9781800208919) [[Amazon]](https://www.amazon.com/dp/180020891X) 105 | 106 | * Python Data Cleaning Cookbook [[Packt]](https://www.packtpub.com/product/python-data-cleaning-cookbook/9781800565661) [[Amazon]](https://www.amazon.com/dp/1800565666) 107 | 108 | ## Get to Know the Author 109 | **Claus Führer** is a professor of scientific computations at Lund University, Sweden. He has an extensive teaching record that includes intensive programming courses in numerical analysis and engineering mathematics across various levels in many different countries and teaching environments. Claus also develops numerical software in research collaboration with industry and received Lund University’s Faculty of Engineering Best Teacher Award in 2016. 110 | 111 | **Olivier Verdier** began using Python for scientific computing back in 2007 and received a PhD in mathematics from Lund University in 2009. He has held post-doctoral positions in Cologne, Trondheim, Bergen, and Ume and is now an associate professor of mathematics at Bergen University College, Norway. 112 | 113 | **Jan Erik Solem** is a Python enthusiast, former associate professor, and computer vision entrepreneur. He co-founded several computer vision startups, most recently Mapillary, a street imagery computer vision company, and has worked in the tech industry for two decades. Jan Erik is a World Economic Forum technology pioneer and won the Best Nordic Thesis Award 2005-2006 for his dissertation on image analysis and pattern recognition. He is also the author of "Programming Computer Vision with Python" (O'Reilly 2012). 114 | 115 | ### Download a free PDF 116 | 117 | 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.
118 |

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

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