├── HighPerformance ├── Rectangle │ ├── __init__.py │ ├── Rectangle.h │ ├── setup.py │ ├── rectangle.pyx │ └── Rectangle.cpp ├── pythran_example1.py ├── pythran_example2.py ├── ipython_cell_input.py ├── README.md ├── OtherThingsToTry.ipynb ├── Stage3_NumpyOptimisation.ipynb ├── Stage5_Numba.ipynb ├── Stage2_UsingAppropriateDataStructures.ipynb ├── Example2.ipynb ├── Pythran.ipynb └── Stage4_Cython.ipynb ├── .gitignore ├── example_file.txt ├── CLI_exmple ├── example_file.csv ├── first.py ├── second.py ├── python_wc ├── third.py └── README.md ├── sklearn_cheatsheet.png ├── BestModel_CaliforniaHousing.joblib ├── Python_App ├── tic_tac_toe_stage_1.ipynb ├── tic_tac_toe_stage_2.ipynb ├── tic_tac_toe_stage_3.ipynb ├── tic_tac_toe_stage_4.ipynb └── tic_tac_toe_stage_5.ipynb ├── README.md ├── conda_package_list.txt └── LICENSE /HighPerformance/Rectangle/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | HighPerformance/.ipynb_checkpoints/* 2 | .ipynb_checkpoints/ 3 | -------------------------------------------------------------------------------- /example_file.txt: -------------------------------------------------------------------------------- 1 | This is the first line 2 | An additional line (no.2) 3 | line 3: Tokyo Drift -------------------------------------------------------------------------------- /CLI_exmple/example_file.csv: -------------------------------------------------------------------------------- 1 | col1, col2, col3 2 | 12, 123, 543 3 | 2,3, 4 4 | 4, 66, 6 5 | 2, 5, 999 6 | 123, 5, 6 7 | -------------------------------------------------------------------------------- /sklearn_cheatsheet.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LukeRoantree4815162342/QUB_DW_HighPerformancePython/HEAD/sklearn_cheatsheet.png -------------------------------------------------------------------------------- /BestModel_CaliforniaHousing.joblib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LukeRoantree4815162342/QUB_DW_HighPerformancePython/HEAD/BestModel_CaliforniaHousing.joblib -------------------------------------------------------------------------------- /HighPerformance/pythran_example1.py: -------------------------------------------------------------------------------- 1 | #pythran export min_product(float32 list, float32 list) 2 | def min_product(arr1, arr2): 3 | assert (len(arr1) == len(arr2)), 'mismatch in dimensions' 4 | return min([a*b for a,b in zip(arr1,arr2)]) 5 | 6 | -------------------------------------------------------------------------------- /HighPerformance/Rectangle/Rectangle.h: -------------------------------------------------------------------------------- 1 | namespace shapes { 2 | class Rectangle { 3 | public: 4 | int x0, y0, x1, y1; 5 | Rectangle(); 6 | Rectangle(int x0, int y0, int x1, int y1); 7 | ~Rectangle(); 8 | int getArea(); 9 | }; 10 | } 11 | -------------------------------------------------------------------------------- /HighPerformance/pythran_example2.py: -------------------------------------------------------------------------------- 1 | #pythran export arc_dist(float[], float[], float[], float[]) 2 | 3 | import numpy as np 4 | 5 | def arc_dist(theta1, phi1, theta2, phi2): 6 | temp = (np.sin((theta2-theta1)/2)**2 + 7 | (np.cos(theta1)*np.cos(theta2)) * np.sin((phi2-phi1)/2)**2) 8 | return 2 * np.arctan2(np.sqrt(temp), np.sqrt(1-temp)) 9 | -------------------------------------------------------------------------------- /HighPerformance/Rectangle/setup.py: -------------------------------------------------------------------------------- 1 | from distutils.core import setup 2 | from distutils.extension import Extension 3 | from Cython.Distutils import build_ext 4 | 5 | setup(ext_modules = [Extension("rectangle", 6 | ["rectangle.pyx", 7 | "Rectangle.cpp"], 8 | language="c++", 9 | ) 10 | ], 11 | cmdclass = {'build_ext': build_ext}) 12 | -------------------------------------------------------------------------------- /HighPerformance/ipython_cell_input.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | big_number = 500 3 | is_prime=lambda x: all(x % i != 0 for i in range(int(x))[2:]) 4 | 5 | def bad_np(): 6 | global big_number 7 | primes = np.array([]) 8 | for i in range(big_number): 9 | if is_prime(i): 10 | primes = np.append(primes,i) 11 | return primes 12 | 13 | def normal_list(): 14 | global big_number 15 | primes = [] 16 | for i in range(big_number): 17 | if is_prime(i): 18 | primes.append(i) 19 | return primes 20 | 21 | #bad_np() 22 | normal_list() -------------------------------------------------------------------------------- /HighPerformance/Rectangle/rectangle.pyx: -------------------------------------------------------------------------------- 1 | # rectangle.pyx 2 | cdef extern from "Rectangle.h" namespace "shapes": 3 | cdef cppclass Rectangle: 4 | Rectangle(int, int, int, int) 5 | int x0, y0, x1, y1 6 | int getArea() 7 | 8 | cdef class PyRectangle: 9 | cdef Rectangle *thisptr # hold a C++ instance which we're wrapping 10 | def __cinit__(self, int x0, int y0, int x1, int y1): 11 | self.thisptr = new Rectangle(x0, y0, x1, y1) 12 | def __dealloc__(self): 13 | del self.thisptr 14 | def getArea(self): 15 | return self.thisptr.getArea() -------------------------------------------------------------------------------- /HighPerformance/README.md: -------------------------------------------------------------------------------- 1 | # Order of working through these notebooks: 2 | 3 | > Stage1 4 | 5 | 6 | > Stage2 7 | 8 | 9 | > Example1 10 | 11 | 12 | > Stage3 13 | 14 | 15 | > Stage4 16 | 17 | 18 | > Stage5 19 | 20 | 21 | > Example2 22 | 23 | 24 | > OtherThingsToTry 25 | 26 | 27 | 28 | ![alt text](https://blogs.qub.ac.uk/footnotesqub/files/2015/03/QUBLogo.gif "QUB") 29 | 30 | 31 | 32 | **Team Members** 33 | 34 | | First Name | Last Name | 35 | | ------------- |:-------------:| 36 | | Conor | Duffy | 37 | | Silas | O'Toole | 38 | | Luke | Roantree | 39 | -------------------------------------------------------------------------------- /CLI_exmple/first.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env/python 2 | 3 | import sys 4 | 5 | """ 6 | Internally, sys.argv is used by all cli building tools to access the arguments passed 7 | when calling the CLI program. 8 | 9 | This example shows how to use it directly. 10 | 11 | As shown below, the first element of sys.argv is the command used (python program called), 12 | and the remaining ones are the extra arguments passed to the script 13 | """ 14 | 15 | command = sys.argv[0] 16 | arg1 = sys.argv[1] 17 | arg2 = sys.argv[2] 18 | 19 | 20 | print('the command {} was used, with the arguments {} and {}'.format(command,arg1,arg2)) 21 | 22 | 23 | -------------------------------------------------------------------------------- /HighPerformance/Rectangle/Rectangle.cpp: -------------------------------------------------------------------------------- 1 | #include "Rectangle.h" 2 | 3 | namespace shapes{ 4 | 5 | // Default constructor 6 | Rectangle::Rectangle () {} 7 | 8 | // Overloaded constructor 9 | Rectangle::Rectangle (int x0, int y0, int x1, int y1) { 10 | this->x0 = x0; 11 | this->y0 = y0; 12 | this->x1 = x1; 13 | this->y1 = y1; 14 | } 15 | 16 | // Destructor 17 | Rectangle::~Rectangle () {} 18 | 19 | // Return the area of the rectangle 20 | int Rectangle::getArea () { 21 | return (this->x1 - this->x0) * (this->y1 - this->y0); 22 | } 23 | }; 24 | 25 | -------------------------------------------------------------------------------- /HighPerformance/OtherThingsToTry.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "* threading\n", 8 | "* parallelisation\n", 9 | "* iterators\n", 10 | "* generators" 11 | ] 12 | }, 13 | { 14 | "cell_type": "code", 15 | "execution_count": null, 16 | "metadata": { 17 | "collapsed": true 18 | }, 19 | "outputs": [], 20 | "source": [] 21 | } 22 | ], 23 | "metadata": { 24 | "kernelspec": { 25 | "display_name": "Python 3", 26 | "language": "python", 27 | "name": "python3" 28 | }, 29 | "language_info": { 30 | "codemirror_mode": { 31 | "name": "ipython", 32 | "version": 3 33 | }, 34 | "file_extension": ".py", 35 | "mimetype": "text/x-python", 36 | "name": "python", 37 | "nbconvert_exporter": "python", 38 | "pygments_lexer": "ipython3", 39 | "version": "3.6.1" 40 | } 41 | }, 42 | "nbformat": 4, 43 | "nbformat_minor": 2 44 | } 45 | -------------------------------------------------------------------------------- /CLI_exmple/second.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | # The shebang (above) is used to tell the computer what to use to run the program 4 | # when it is made executable. This may change slightly depending on operating system 5 | 6 | import argparse, time 7 | 8 | """ 9 | An easier way of making CLI apps is to use the 'argparse' module (part of the stdlib). 10 | 11 | It lets you easily specify and name arguments, and also automatically builds a --help 12 | usage guide based on the argument specifications. 13 | 14 | Additionally, each argument can be given a description with the 'help' parameter, 15 | a type to be interpreted as (default is string), and a default can be given (optional 16 | arguments only). 17 | """ 18 | 19 | parser = argparse.ArgumentParser() 20 | # Create a parser object 21 | 22 | parser.add_argument('person') 23 | # all parameters after the name are optional. 24 | 25 | parser.add_argument('note', help='enter a note', type=str) 26 | # you can specify types and help 27 | 28 | parser.add_argument('--delay', '-d', help='enter a delay in seconds', type=int, default=5) 29 | # arguments are made optional by starting the name with --, and can be given a shorter alias 30 | # immediately after, starting with a single -. 31 | # optional arguments can be given a default value. 32 | 33 | args = parser.parse_args() 34 | 35 | time.sleep(args.delay) 36 | print('{}: {}'.format(args.person, args.note)) 37 | 38 | 39 | -------------------------------------------------------------------------------- /CLI_exmple/python_wc: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | """ 4 | 'wc' is a bash command for getting line,word, and character counts 5 | in a file. It can be called either directly; 6 | $ wc 7 | or accept input from a pipe; 8 | $ cat | wc 9 | and prints out 10 | 11 | 12 | Here we recreate this with python. 13 | 14 | On Linux/Mac(/Windows via bash terminal) you can make it an executable file 15 | (allowing you to run it without typing python first), by ensuring the 16 | shebang at the top is correct for your system, then running 17 | $ chmod +x python_wc 18 | 19 | Additionally adding this directory to your $PATH variable will allow 20 | you to use python_wc from anywhere without needing to give the full/relative 21 | path to it. 22 | """ 23 | 24 | import argparse as ap 25 | import sys 26 | 27 | parser = ap.ArgumentParser() 28 | 29 | parser.add_argument('input_file', nargs='?', type=ap.FileType('r'), default=sys.stdin) 30 | # We only need one argument - the name of / path to the input file. 31 | # We give it a special type; argparse.FileTye - telling argparse 32 | # to open it as a file instead of taking the name/path as a string. 33 | 34 | args = parser.parse_args() 35 | 36 | line_count, word_count, char_count = 0, 0, 0 37 | 38 | with args.input_file as input_file: 39 | for line in input_file: 40 | line_count += 1 41 | 42 | for word in line.split(): 43 | word_count += 1 44 | 45 | for char in word: 46 | char_count += 1 47 | 48 | char_count += (word_count - line_count) # account for spaces 49 | 50 | print('{} {} {}'.format(line_count, word_count, char_count)) 51 | 52 | 53 | -------------------------------------------------------------------------------- /CLI_exmple/third.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import argparse 4 | 5 | """ 6 | argparse allows you to do a lot of extra logic with input 7 | arguments - such as treating arguments as flags, making 8 | arguments mutually exclusive, count how many times an 9 | argument is specified, and more. This example will show 10 | a few common usages of these more specialised options 11 | """ 12 | 13 | parser = argparse.ArgumentParser() 14 | 15 | parser.add_argument('num1',type=float, help='first number') 16 | 17 | group = parser.add_mutually_exclusive_group(required=True) 18 | # make a mutually exlusive group - only one parameter may 19 | # be specified from the ones we add here 20 | 21 | group.add_argument('--multiply','-m', help='multiply num1 by num2', action='store_true') 22 | # the action='store_true' part tells the program that this 23 | # argument won't be given a value in the command line, but 24 | # if it is present, assign it a value of True 25 | 26 | group.add_argument('--divide','-d', help='divide num1 by num2', action='store_true') 27 | group.add_argument('--subtract','-s', help='subtract num1 from num2', action='store_true') 28 | group.add_argument('--add','-a', help='add num1 to num2', action='store_true') 29 | 30 | parser.add_argument('num2',type=float, help='second number') 31 | 32 | parser.add_argument('--sigfigs', '-f', help='how many significant figures to display [-f = 1, -fff = 3]', action='count') 33 | 34 | args = parser.parse_args() 35 | 36 | if not args.sigfigs: 37 | sf = 5 38 | else: 39 | sf = args.sigfigs 40 | 41 | if args.multiply: 42 | print("{0:.{1}g}".format(args.num1*args.num2,sf)) 43 | # string formatting; second argument specifying number 44 | # of sig figs to display for the first argument 45 | if args.divide: 46 | print("{0:.{1}g}".format(args.num1/args.num2,sf)) 47 | if args.subtract: 48 | print("{0:.{1}g}".format(args.num1-args.num2,sf)) 49 | if args.add: 50 | print("{0:.{1}g}".format(args.num1+args.num2,sf)) 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /CLI_exmple/README.md: -------------------------------------------------------------------------------- 1 | ## What's a CLI? 2 | 3 | ##### A 'CLI' is a 'Command Line Interface' for a program/tool. They're commonly used by programmers who enjoy working from a terminal (or don't enjoy it but need to anyway), and are much easier to build than graphical user interfaces (GUIs) or web-apps. As they're much easier to build, they're often used for prototyping tools/ideas in order to get the main bulk processing and such figured out before worrying about how it should look to a user. 4 | --- 5 | 6 | ## What CLI programs might I have used before? 7 | 8 | ##### If you use a version of Linux, you'll almost certainly have used some in the terminal - most common shell commands are technically CLI interfaces to programs, e.g. 'grep' for searching a file for keywords / regular expressions, or 'wc' for counting lines, words, and characters in a file. In the last example here, we make 'python\_wc' - a python implementation of the wc tool. Other than a few small differences when given unusual input (and processing speed for large files), it should be roughly interchangeable for the standard wc command. 9 | 10 | -------------------------------------------------------------------------------------------- 11 | 12 | ## Examples Order: 13 | > first.py 14 | 15 | > second.py 16 | 17 | > third.py 18 | 19 | > python\_wc 20 | 21 | ![QUB Logo](https://blogs.qub.ac.uk/footnotesqub/files/2015/03/QUBLogo.gif) 22 | 23 | ## I want to make CLIs but sys/argparse are too bare-bones, what should I do? 24 | 25 | There're other libraries and frameworks for making CLIs in Python, for example 26 | [Click](https://click.palletsprojects.com/en/7.x/) which is installable with 27 | pip, and is easy to get started with. I have used it and would recommend it. 28 | 29 | Another option is [Fire](https://github.com/google/python-fire), made by Google, 30 | which focuses on taking as little effort as possible to give a python program a 31 | command line interface, and is also available for installation on pip, and on conda. 32 | I haven't yet used this one, although from scanning their examples, it looks nice. 33 | -------------------------------------------------------------------------------- /Python_App/tic_tac_toe_stage_1.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "import numpy as np " 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": 3, 15 | "metadata": {}, 16 | "outputs": [], 17 | "source": [ 18 | "symbols = [' ', 'X', 'O']\n", 19 | "#Generate Grid [as list] (Hint: 'for' loop)" 20 | ] 21 | }, 22 | { 23 | "cell_type": "code", 24 | "execution_count": 4, 25 | "metadata": {}, 26 | "outputs": [], 27 | "source": [ 28 | "def draw_board(grid):\n", 29 | " print(\"\"\"\n", 30 | " {} | {} | {} \n", 31 | " -----------\n", 32 | " {} | {} | {} \n", 33 | " -----------\n", 34 | " {} | {} | {}\n", 35 | " \"\"\".format(grid[0],grid[1],grid[2],grid[3],grid[4],grid[5],grid[6],grid[7],grid[8]))" 36 | ] 37 | }, 38 | { 39 | "cell_type": "code", 40 | "execution_count": 5, 41 | "metadata": {}, 42 | "outputs": [], 43 | "source": [ 44 | "grid = None\n", 45 | "\"\"\"\n", 46 | "code for grid here\n", 47 | "\"\"\"" 48 | ] 49 | }, 50 | { 51 | "cell_type": "code", 52 | "execution_count": 6, 53 | "metadata": {}, 54 | "outputs": [], 55 | "source": [ 56 | "'''\n", 57 | "Now See if you can plot an X in position 4 of the Grid, print grid. \n", 58 | "'''" 59 | ] 60 | }, 61 | { 62 | "cell_type": "code", 63 | "execution_count": 7, 64 | "metadata": {}, 65 | "outputs": [], 66 | "source": [] 67 | }, 68 | { 69 | "cell_type": "code", 70 | "execution_count": null, 71 | "metadata": {}, 72 | "outputs": [], 73 | "source": [] 74 | }, 75 | { 76 | "cell_type": "code", 77 | "execution_count": null, 78 | "metadata": {}, 79 | "outputs": [], 80 | "source": [] 81 | } 82 | ], 83 | "metadata": { 84 | "kernelspec": { 85 | "display_name": "Python 3", 86 | "language": "python", 87 | "name": "python3" 88 | }, 89 | "language_info": { 90 | "codemirror_mode": { 91 | "name": "ipython", 92 | "version": 3 93 | }, 94 | "file_extension": ".py", 95 | "mimetype": "text/x-python", 96 | "name": "python", 97 | "nbconvert_exporter": "python", 98 | "pygments_lexer": "ipython3", 99 | "version": "3.6.4" 100 | } 101 | }, 102 | "nbformat": 4, 103 | "nbformat_minor": 2 104 | } 105 | -------------------------------------------------------------------------------- /HighPerformance/Stage3_NumpyOptimisation.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "

\n", 8 | "Numpy Optimisation:\n", 9 | "

" 10 | ] 11 | }, 12 | { 13 | "cell_type": "markdown", 14 | "metadata": {}, 15 | "source": [ 16 | "## We actually covered most of the important things in the last notebook, in this one there's only one other thing that I want to cover:" 17 | ] 18 | }, 19 | { 20 | "cell_type": "code", 21 | "execution_count": 5, 22 | "metadata": {}, 23 | "outputs": [ 24 | { 25 | "name": "stdout", 26 | "output_type": "stream", 27 | "text": [ 28 | "QUB_test.pdf\n", 29 | "QUB_['file1.txt', 'file2.csv']\n" 30 | ] 31 | } 32 | ], 33 | "source": [ 34 | "\"\"\"\n", 35 | "Vectorisation -\n", 36 | "\n", 37 | "You've seen before that Numpy has lots of very nice functions, and can perform their respective\n", 38 | "operations on each element of an array at once. \n", 39 | "\n", 40 | "However;\n", 41 | "If we want to use a function we've defined ourselves on a list-type structure (including np.array), \n", 42 | "it won't be able to perform it element-wise.\n", 43 | "Instead, the obvious thing to do would be to loop over the array and call our function on each element explicitly.\n", 44 | "Clearly, this is a lot slower than we would like\n", 45 | "\"\"\"\n", 46 | "import numpy as np\n", 47 | "\n", 48 | "def add_QUB_prefix(filename):\n", 49 | " return \"QUB_{}\".format(filename)\n", 50 | "\n", 51 | "print(add_QUB_prefix('test.pdf'))\n", 52 | "print(add_QUB_prefix(['file1.txt', 'file2.csv']))" 53 | ] 54 | }, 55 | { 56 | "cell_type": "code", 57 | "execution_count": 4, 58 | "metadata": {}, 59 | "outputs": [ 60 | { 61 | "name": "stdout", 62 | "output_type": "stream", 63 | "text": [ 64 | "['QUB_file1.txt' 'QUB_file2.csv']\n", 65 | "['QUB_file1.txt' 'QUB_file2.csv']\n" 66 | ] 67 | } 68 | ], 69 | "source": [ 70 | "\"\"\"\n", 71 | "Numpy provides us with a way to take an (almost) arbitrary function, and 'vectorise' it to make it work element-wise.\n", 72 | "\n", 73 | "You can convert an existing function with it directly, or use it as a decorator when making a function -\n", 74 | "\"\"\"\n", 75 | "\n", 76 | "add_QUB_prefix_1 = np.vectorize(add_QUB_prefix)\n", 77 | "\n", 78 | "@np.vectorize\n", 79 | "def add_QUB_prefix_2(filename):\n", 80 | " return \"QUB_{}\".format(filename)\n", 81 | "\n", 82 | "print(add_QUB_prefix_1(['file1.txt', 'file2.csv']))\n", 83 | "print(add_QUB_prefix_2(['file1.txt', 'file2.csv']))" 84 | ] 85 | }, 86 | { 87 | "cell_type": "markdown", 88 | "metadata": {}, 89 | "source": [ 90 | "#### In the above example, we didn't save much time as it wasn't computationally heavy to start with - but it was a lot easier than looping plus it's easy to see how to apply the concepts to other, computationally heavier, functions for serious time improvements" 91 | ] 92 | } 93 | ], 94 | "metadata": { 95 | "kernelspec": { 96 | "display_name": "Python 3", 97 | "language": "python", 98 | "name": "python3" 99 | }, 100 | "language_info": { 101 | "codemirror_mode": { 102 | "name": "ipython", 103 | "version": 3 104 | }, 105 | "file_extension": ".py", 106 | "mimetype": "text/x-python", 107 | "name": "python", 108 | "nbconvert_exporter": "python", 109 | "pygments_lexer": "ipython3", 110 | "version": "3.6.1" 111 | } 112 | }, 113 | "nbformat": 4, 114 | "nbformat_minor": 2 115 | } 116 | -------------------------------------------------------------------------------- /Python_App/tic_tac_toe_stage_2.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "import numpy as np " 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": 2, 15 | "metadata": {}, 16 | "outputs": [], 17 | "source": [ 18 | "symbols = [' ', 'X', 'O']\n" 19 | ] 20 | }, 21 | { 22 | "cell_type": "code", 23 | "execution_count": 3, 24 | "metadata": {}, 25 | "outputs": [], 26 | "source": [ 27 | "def draw_board(grid):\n", 28 | " print(\"\"\"\n", 29 | " {} | {} | {} \n", 30 | " -----------\n", 31 | " {} | {} | {} \n", 32 | " -----------\n", 33 | " {} | {} | {}\n", 34 | " \"\"\".format(grid[0],grid[1],grid[2],grid[3],grid[4],grid[5],grid[6],grid[7],grid[8]))" 35 | ] 36 | }, 37 | { 38 | "cell_type": "code", 39 | "execution_count": 4, 40 | "metadata": {}, 41 | "outputs": [], 42 | "source": [ 43 | "def initialise_moves():\n", 44 | " grid=[]\n", 45 | " for i in range(9):\n", 46 | " grid.append(0)\n", 47 | " return grid" 48 | ] 49 | }, 50 | { 51 | "cell_type": "code", 52 | "execution_count": 5, 53 | "metadata": {}, 54 | "outputs": [ 55 | { 56 | "name": "stdout", 57 | "output_type": "stream", 58 | "text": [ 59 | "[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']\n" 60 | ] 61 | } 62 | ], 63 | "source": [ 64 | "grid=[symbols[s] for s in initialise_moves()]\n", 65 | "print(grid)" 66 | ] 67 | }, 68 | { 69 | "cell_type": "code", 70 | "execution_count": 6, 71 | "metadata": {}, 72 | "outputs": [], 73 | "source": [ 74 | "def who_goes_first():\n", 75 | " player=input(\"Who goes first: user or computer: \")\n", 76 | " return player.lower()" 77 | ] 78 | }, 79 | { 80 | "cell_type": "code", 81 | "execution_count": 7, 82 | "metadata": {}, 83 | "outputs": [], 84 | "source": [ 85 | "def symbol_from_player(player):\n", 86 | " if player == 'user':\n", 87 | " return 1\n", 88 | " else:\n", 89 | " return 2" 90 | ] 91 | }, 92 | { 93 | "cell_type": "code", 94 | "execution_count": 8, 95 | "metadata": {}, 96 | "outputs": [], 97 | "source": [ 98 | "def first_go(grid):\n", 99 | " current_player=None\n", 100 | " if who_goes_first() == \"user\":\n", 101 | " current_player=\"user\"\n", 102 | " turn=int(input(\"Choose Sqaure on grid from 0 to 8: \"))\n", 103 | " grid[turn]=symbols[symbol_from_player(current_player)]\n", 104 | " else:\n", 105 | " current_player=\"computer\"\n", 106 | " turn=np.random.randint(9)\n", 107 | " grid[turn]=symbols[symbol_from_player(current_player)]\n", 108 | " draw_board(grid)" 109 | ] 110 | }, 111 | { 112 | "cell_type": "code", 113 | "execution_count": 9, 114 | "metadata": {}, 115 | "outputs": [ 116 | { 117 | "name": "stdout", 118 | "output_type": "stream", 119 | "text": [ 120 | "Who goes first: user or computer: user\n", 121 | "Choose Sqaure on grid from 0 to 8: 1\n", 122 | "\n", 123 | " | X | \n", 124 | " -----------\n", 125 | " | | \n", 126 | " -----------\n", 127 | " | | \n", 128 | " \n" 129 | ] 130 | } 131 | ], 132 | "source": [ 133 | "first_go(grid)\n" 134 | ] 135 | }, 136 | { 137 | "cell_type": "code", 138 | "execution_count": null, 139 | "metadata": {}, 140 | "outputs": [], 141 | "source": [] 142 | } 143 | ], 144 | "metadata": { 145 | "kernelspec": { 146 | "display_name": "Python 3", 147 | "language": "python", 148 | "name": "python3" 149 | }, 150 | "language_info": { 151 | "codemirror_mode": { 152 | "name": "ipython", 153 | "version": 3 154 | }, 155 | "file_extension": ".py", 156 | "mimetype": "text/x-python", 157 | "name": "python", 158 | "nbconvert_exporter": "python", 159 | "pygments_lexer": "ipython3", 160 | "version": "3.6.4" 161 | } 162 | }, 163 | "nbformat": 4, 164 | "nbformat_minor": 2 165 | } 166 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # QUB Development Weeks: High Performance Python 2 | Code and more for the QUB Development Weeks event 'High Performance Python' 3 | 4 | --- 5 | ## Getting Started: 6 | 7 | 1) Check if Anaconda is installed - this isn't essential in general for using Python, as there is other ways to set up and use Python, but 8 | to avoid runing into versioning problems between different Python / library distributions I'm standardising this course with conda 9 | environments. 10 | 11 | This means you'll be installing the same version of Python as I'm using as I give this course, as well as the same 12 | versions of the same external packages that I use - in a temporary virtual environment that won't mess up any other Python installs you have. 13 | 14 | To check if anaconda is installed properly, open a terminal (Windows - search Command Prompt or git-bash, MacOS - search terminal, linux - you know how) 15 | 16 | In the terminal run "conda list". If you get a list of packages, or even anything other than "no command found" or similar - you're all good! 17 | 18 | Close the terminal now. 19 | 20 | 2) If not already installed, download and install [Anaconda](https://www.anaconda.com/distribution/) 21 | 22 | 3) At this point I'll assume I've shown you how to download / clone this repository (or you already knew how and did it yourself). Open a terminal 23 | in this directory (where this repository is): 24 | 25 | > Windows - in file manager, navigate to this repo, right click anywhere and click 'command prompt here' 26 | 27 | > MacOS - in Finder, navigate to this repo, then (top left of screen) click 'Finder'-\>Services-\>'new Terminal at Folder' 28 | 29 | > Linux - cd to this repo 30 | 31 | and run "conda create --name qubcourse --file conda\_package\_list.txt python=3.7.5", which will create a new virtual environment, with a specific version of Python, 32 | and will install the same versions of the same packages I had installed when I made this course. 33 | 34 | This will take a while, so I'll probably have started going through the earlier parts of the course during these downloading and installing. 35 | 36 | 4) In your terminal, run "conda activate qubcourse". This tells it to use the virtual environment we made a minute ago. When we're done, we can run "conda deactivate" 37 | to go back to the way things were before. 38 | 39 | 5) In your terminal, still in this directory, run "jupyter notebook" - this should cause a webpage to open, with a list of what's in this directory. To start with, 40 | click on the 'PythonRefresher.ipynb' link. 41 | 42 | 43 | That's us fully set up and started! 44 | 45 | --- 46 | 47 | *Note: In 2019 split into 'Python Refresher Course' (winter) and 'High Performance Python' (summer) due to length of additional content* 48 | 49 | ### Stable: [Python Refresher](PythonRefresher.ipynb) 50 | 51 | ### Unstable / Untidy: [High Performance Sections (mostly tidy enough)](HighPerformance) 52 | --------------------------------------------------------------------------------------------- 53 | 54 | # 2019 Updates Now Out 55 | 56 | -------------------------------------------------------------------------------------------- 57 | 58 | ## Python Refresher Course Overview: 59 | > Commenting 60 | 61 | > Basic Data Types 62 | 63 | > Conditional Logic & Basic Loops 64 | 65 | > Comprehensions 66 | 67 | > Functions & Lambdas 68 | 69 | > Intro to OOP Python 70 | 71 | > Generators & Iterators 72 | 73 | > Handling Files 74 | 75 | > Numpy & Scipy 76 | 77 | > Pandas 78 | 79 | > Matplotlib 80 | 81 | > Scikit-Learn 82 | 83 | > Free External Resources (IDEs, Books, Library / Domain-Specific Tutorials, List of Useful Libraries) 84 | 85 | 86 | ![QUB Logo](https://blogs.qub.ac.uk/footnotesqub/files/2015/03/QUBLogo.gif) 87 | 88 | 89 | 90 | **Team Members** 91 | 92 | | First Name | Last Name | 2018 | 2019 | 93 | | ------------- |:-------------:|:----:|:----:| 94 | | Conor | Duffy | Y | N | 95 | | Silas | O'Toole | Y | N | 96 | | Luke | Roantree | Y | Y | 97 | 98 | Special thanks to: 99 | 100 | 101 | * Dr. Garbriele De Chiara - for helping organise the event and booking the computer suites 102 | 103 | 104 | * Victoria Coulter - for obtaining funding, setting up the registration, and more 105 | 106 | 107 | 108 | 109 | -------------------------------------------------------- 110 | ## **What This Doesn't Cover:** 111 | 112 | ### Python Refresher: 113 | 114 | > Interacting with computer via os and sys (2019 Updates touch on some) 115 | 116 | 117 | > Installing extra libraries 118 | 119 | 120 | > Machine learning libraries other than Sklearn 121 | 122 | ------------------------------------------------------- 123 | ## High Performance Python summer-2019 release updates to include: 124 | > Multi-Threading 125 | 126 | 127 | > Parallel Processing (joblib and mpi4py) 128 | 129 | 130 | > Cython other than via Jupyter Notebook 131 | 132 | 133 | > Pythran 134 | 135 | 136 | > f2py 137 | -------------------------------------------------------------------------------- /HighPerformance/Stage5_Numba.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "

\n", 8 | "Numba\n", 9 | "

" 10 | ] 11 | }, 12 | { 13 | "cell_type": "markdown", 14 | "metadata": {}, 15 | "source": [ 16 | "## What is Numba?\n", 17 | "\n", 18 | "\"A JIT Compiler for Python Functions\"\n", 19 | "\n", 20 | "It tries to 'intelligently' optimise things, supports many kinds of optimisations, including CPU and GPU optimisations" 21 | ] 22 | }, 23 | { 24 | "cell_type": "markdown", 25 | "metadata": {}, 26 | "source": [ 27 | "Here's a terrifying picture to describe how it works. You can ignore it if you want, we'll only be using a couple of functions, and hoping it's smart enough to do all the hard work itself;\n", 28 | "\n", 29 | "" 30 | ] 31 | }, 32 | { 33 | "cell_type": "markdown", 34 | "metadata": {}, 35 | "source": [ 36 | "Make sense? I joke, although that image is actually a good overview of how it works, and googling 'numba' + the content of each cell leads you to find a good explanation of that part, which hopefully improves your overall underdstanding of how numba works (if you want a more in-depth understanding that is).\n", 37 | "\n", 38 | "Below we'll show the couple of the main functions we found useful and a couple of examples." 39 | ] 40 | }, 41 | { 42 | "cell_type": "code", 43 | "execution_count": 4, 44 | "metadata": { 45 | "collapsed": true 46 | }, 47 | "outputs": [], 48 | "source": [ 49 | "from numba import jit, autojit\n", 50 | "import numpy as np\n", 51 | "\n", 52 | "# These examples are taken from the 'Examples' section on Numba's official website\n", 53 | "\n", 54 | "\"\"\"\n", 55 | "@jit decorator:\n", 56 | "Tells Numba to do just-in-time compilation for this function\n", 57 | "\"\"\"\n", 58 | "\n", 59 | "@jit\n", 60 | "def mandel(x, y, max_iters):\n", 61 | " \"\"\"\n", 62 | " Given the real and imaginary parts of a complex number,\n", 63 | " determine if it is a candidate for membership in the Mandelbrot\n", 64 | " set given a fixed number of iterations.\n", 65 | " \"\"\"\n", 66 | " i = 0\n", 67 | " c = complex(x,y)\n", 68 | " z = 0.0j\n", 69 | " for i in range(max_iters):\n", 70 | " z = z*z + c\n", 71 | " if (z.real*z.real + z.imag*z.imag) >= 4:\n", 72 | " return i\n", 73 | "\n", 74 | " return 255\n", 75 | "\n", 76 | "\n", 77 | "\"\"\"\n", 78 | "You can give the JIT compiler clues to make the optimisation better;\n", 79 | "> You can tell it output type (void here), input type (three arrays of floating point numbers here)\n", 80 | "> You can tell it to compile in 'nopython' mode rather than object mode - apparently this is faster,\n", 81 | " but has limitations. \n", 82 | "> You can tell it that you're only using native types (rather than python objects), and so it can \n", 83 | " turn off the Global Interpretr Lock (GIL)\n", 84 | "\"\"\"\n", 85 | "\n", 86 | "@jit('void(double[:], double[:], double[:])', nopython=True, nogil=True)\n", 87 | "def inner_func_nb(result, a, b):\n", 88 | " \"\"\"\n", 89 | " Function under test.\n", 90 | " \"\"\"\n", 91 | " for i in range(len(result)):\n", 92 | " result[i] = np.exp(2.1 * a[i] + 3.2 * b[i])\n", 93 | "\n", 94 | "\n", 95 | "\"\"\"\n", 96 | "Another function Numpy offers is 'autojit'. \n", 97 | "It used to be the case that @jit required tpyes to be able to optimise it,\n", 98 | "and @autojit would try and guess the types as well as otimise it. Now, @jit can do\n", 99 | "this as well, and so @autojit is redundant. It still works though;\n", 100 | "\n", 101 | "\"\"\"\n", 102 | "\n", 103 | "@autojit\n", 104 | "def inner_func_nb(result, a, b):\n", 105 | " \"\"\"\n", 106 | " Function under test.\n", 107 | " \"\"\"\n", 108 | " for i in range(len(result)):\n", 109 | " result[i] = np.exp(2.1 * a[i] + 3.2 * b[i])" 110 | ] 111 | }, 112 | { 113 | "cell_type": "markdown", 114 | "metadata": { 115 | "collapsed": true 116 | }, 117 | "source": [ 118 | "## For more documentation and examples, see below:\n", 119 | "\n", 120 | "## [Numba](https://numba.pydata.org/numba-doc/0.17.0/user/jit.html)" 121 | ] 122 | } 123 | ], 124 | "metadata": { 125 | "kernelspec": { 126 | "display_name": "Python 3", 127 | "language": "python", 128 | "name": "python3" 129 | }, 130 | "language_info": { 131 | "codemirror_mode": { 132 | "name": "ipython", 133 | "version": 3 134 | }, 135 | "file_extension": ".py", 136 | "mimetype": "text/x-python", 137 | "name": "python", 138 | "nbconvert_exporter": "python", 139 | "pygments_lexer": "ipython3", 140 | "version": "3.6.1" 141 | } 142 | }, 143 | "nbformat": 4, 144 | "nbformat_minor": 2 145 | } 146 | -------------------------------------------------------------------------------- /Python_App/tic_tac_toe_stage_3.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 33, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "import numpy as np " 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": 34, 15 | "metadata": {}, 16 | "outputs": [], 17 | "source": [ 18 | "symbols = [' ', 'X', 'O']\n" 19 | ] 20 | }, 21 | { 22 | "cell_type": "code", 23 | "execution_count": 35, 24 | "metadata": {}, 25 | "outputs": [], 26 | "source": [ 27 | "def draw_board(grid):\n", 28 | " print(\"\"\"\n", 29 | " {} | {} | {} \n", 30 | " -----------\n", 31 | " {} | {} | {} \n", 32 | " -----------\n", 33 | " {} | {} | {}\n", 34 | " \"\"\".format(grid[0],grid[1],grid[2],grid[3],grid[4],grid[5],grid[6],grid[7],grid[8]))" 35 | ] 36 | }, 37 | { 38 | "cell_type": "code", 39 | "execution_count": 45, 40 | "metadata": {}, 41 | "outputs": [], 42 | "source": [ 43 | "def initialise_moves():\n", 44 | " grid=[]\n", 45 | " for i in range(9):\n", 46 | " grid.append(0)\n", 47 | " return grid\n" 48 | ] 49 | }, 50 | { 51 | "cell_type": "code", 52 | "execution_count": 46, 53 | "metadata": {}, 54 | "outputs": [ 55 | { 56 | "name": "stdout", 57 | "output_type": "stream", 58 | "text": [ 59 | "[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']\n" 60 | ] 61 | } 62 | ], 63 | "source": [ 64 | "grid=[symbols[s] for s in initialise_moves()]\n", 65 | "print(grid)" 66 | ] 67 | }, 68 | { 69 | "cell_type": "code", 70 | "execution_count": 47, 71 | "metadata": {}, 72 | "outputs": [], 73 | "source": [ 74 | "def symbol_from_player(player):\n", 75 | " if player == 'user':\n", 76 | " return 1\n", 77 | " else:\n", 78 | " return 2" 79 | ] 80 | }, 81 | { 82 | "cell_type": "code", 83 | "execution_count": 48, 84 | "metadata": {}, 85 | "outputs": [], 86 | "source": [ 87 | "def who_goes_first():\n", 88 | " player=input(\"Who goes first: user or computer: \")\n", 89 | " return player.lower()" 90 | ] 91 | }, 92 | { 93 | "cell_type": "code", 94 | "execution_count": 49, 95 | "metadata": {}, 96 | "outputs": [], 97 | "source": [ 98 | "# Make Function to change Current player" 99 | ] 100 | }, 101 | { 102 | "cell_type": "code", 103 | "execution_count": 50, 104 | "metadata": {}, 105 | "outputs": [], 106 | "source": [ 107 | "def update_player(current_player):\n", 108 | " if current_player == 'user':\n", 109 | " return 'computer'\n", 110 | " else:\n", 111 | " return 'user'" 112 | ] 113 | }, 114 | { 115 | "cell_type": "code", 116 | "execution_count": 51, 117 | "metadata": {}, 118 | "outputs": [], 119 | "source": [ 120 | "def update_grid(grid,player):\n", 121 | " if player == \"user\":\n", 122 | " square = int(input(\"Select square on Grid (from 0 to 8): \"))\n", 123 | " \n", 124 | " else:\n", 125 | " sqaure = np.random.randint(9)\n", 126 | " \n", 127 | " grid[square] = symbols[symbol_from_player(player)]" 128 | ] 129 | }, 130 | { 131 | "cell_type": "code", 132 | "execution_count": 52, 133 | "metadata": {}, 134 | "outputs": [], 135 | "source": [ 136 | "def start_game(grid):\n", 137 | " draw_board(grid)\n", 138 | " current_player = None # as we are just starting the game \n", 139 | " is_first_go = True\n", 140 | " if is_first_go:\n", 141 | " current_player = who_goes_first()\n", 142 | " is_first_go = False\n", 143 | " else:\n", 144 | " pass # just as no loop yet \n", 145 | " update_grid(grid,current_player)\n", 146 | " \n", 147 | " \n", 148 | " \n", 149 | " \n", 150 | " " 151 | ] 152 | }, 153 | { 154 | "cell_type": "code", 155 | "execution_count": 53, 156 | "metadata": {}, 157 | "outputs": [ 158 | { 159 | "name": "stdout", 160 | "output_type": "stream", 161 | "text": [ 162 | "\n", 163 | " | | \n", 164 | " -----------\n", 165 | " | | \n", 166 | " -----------\n", 167 | " | | \n", 168 | " \n", 169 | "Who goes first: user or computer: user\n", 170 | "Select square on Grid (from 0 to 8): 1\n", 171 | "\n", 172 | " | X | \n", 173 | " -----------\n", 174 | " | | \n", 175 | " -----------\n", 176 | " | | \n", 177 | " \n" 178 | ] 179 | } 180 | ], 181 | "source": [ 182 | "start_game(grid)\n", 183 | "draw_board(grid)" 184 | ] 185 | }, 186 | { 187 | "cell_type": "code", 188 | "execution_count": null, 189 | "metadata": {}, 190 | "outputs": [], 191 | "source": [] 192 | } 193 | ], 194 | "metadata": { 195 | "kernelspec": { 196 | "display_name": "Python 3", 197 | "language": "python", 198 | "name": "python3" 199 | }, 200 | "language_info": { 201 | "codemirror_mode": { 202 | "name": "ipython", 203 | "version": 3 204 | }, 205 | "file_extension": ".py", 206 | "mimetype": "text/x-python", 207 | "name": "python", 208 | "nbconvert_exporter": "python", 209 | "pygments_lexer": "ipython3", 210 | "version": "3.6.4" 211 | } 212 | }, 213 | "nbformat": 4, 214 | "nbformat_minor": 2 215 | } 216 | -------------------------------------------------------------------------------- /HighPerformance/Stage2_UsingAppropriateDataStructures.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "

\n", 8 | "Using Appropriate Data Structures\n", 9 | "

" 10 | ] 11 | }, 12 | { 13 | "cell_type": "markdown", 14 | "metadata": {}, 15 | "source": [ 16 | "### For any given problem that you know how to solve with code, you can probably think of a few different ways of solving it.\n", 17 | "### For example, you might know you could use a numpy array or a list for one part, or a for-loop or list-comprehension for another\n", 18 | "\n", 19 | "### This notebook will focus on heuristics for choosing the 'best' approach for a given problem" 20 | ] 21 | }, 22 | { 23 | "cell_type": "code", 24 | "execution_count": 4, 25 | "metadata": {}, 26 | "outputs": [ 27 | { 28 | "name": "stdout", 29 | "output_type": "stream", 30 | "text": [ 31 | "build_list, build_array;\n", 32 | "100 loops, best of 3: 2.26 ms per loop\n", 33 | "10 loops, best of 3: 156 ms per loop\n", 34 | "\n", 35 | "\n", 36 | "square_all_list, square_all_array;\n", 37 | "10000 loops, best of 3: 78.9 µs per loop\n", 38 | "The slowest run took 8.60 times longer than the fastest. This could mean that an intermediate result is being cached.\n", 39 | "100000 loops, best of 3: 5.11 µs per loop\n" 40 | ] 41 | } 42 | ], 43 | "source": [ 44 | "\"\"\"\n", 45 | "1st) Lists vs. numpy arrays -\n", 46 | "\n", 47 | "General:\n", 48 | " Lists -> \n", 49 | " mutable, can insert / remove elements efficiently, cannot operate on all elements at once\n", 50 | " \n", 51 | " np.arrays -> \n", 52 | " mutable (other than size), must create new array to insert / remove elements,\n", 53 | " can operate on all elements at once.\n", 54 | " \n", 55 | "Heuristics:\n", 56 | " > If you want to gradually build up a list-like structure (and don't know final size), use a list\n", 57 | " > If you have already know what your elements are (or at least how many you'll have),\n", 58 | " and want to do operations on them all, use a np.array\n", 59 | "\"\"\"\n", 60 | "\n", 61 | "import numpy as np\n", 62 | "import timeit\n", 63 | "\n", 64 | "def build_list(count):\n", 65 | " out = []\n", 66 | " for i in range(count):\n", 67 | " out.append(i)\n", 68 | " return out\n", 69 | "\n", 70 | "def build_array(count):\n", 71 | " out = np.array([])\n", 72 | " for i in range(count):\n", 73 | " out = np.append(out,i)\n", 74 | " return out\n", 75 | "\n", 76 | "print('build_list, build_array;')\n", 77 | "%timeit build_list(5000)\n", 78 | "%timeit build_array(5000)\n", 79 | "\n", 80 | "prebuilt_array = np.linspace(0,5000)\n", 81 | "prebuilt_list = list(prebuilt_array)\n", 82 | "\n", 83 | "def square_all_array(list_struct):\n", 84 | " return list_struct**2\n", 85 | "\n", 86 | "def square_all_list(list_struct):\n", 87 | " out = []\n", 88 | " for i in list_struct:\n", 89 | " out.append(i**2)\n", 90 | " return out\n", 91 | "\n", 92 | "print('\\n\\nsquare_all_list, square_all_array;')\n", 93 | "%timeit square_all_list(prebuilt_list)\n", 94 | "%timeit square_all_array(prebuilt_array)" 95 | ] 96 | }, 97 | { 98 | "cell_type": "markdown", 99 | "metadata": {}, 100 | "source": [ 101 | "### Note: An argument could be made that I've compared apples with oranges here, but that's kind of the point; the structures aren't the same, and don't support the same types of operations sometimes. I've tried to be fair and implement each as optimally as possible for that data type in each case." 102 | ] 103 | }, 104 | { 105 | "cell_type": "code", 106 | "execution_count": 5, 107 | "metadata": {}, 108 | "outputs": [ 109 | { 110 | "name": "stdout", 111 | "output_type": "stream", 112 | "text": [ 113 | "square_list_FL, square_list_LC;\n", 114 | "10000 loops, best of 3: 88.1 µs per loop\n", 115 | "10000 loops, best of 3: 68.8 µs per loop\n" 116 | ] 117 | } 118 | ], 119 | "source": [ 120 | "\"\"\"\n", 121 | "2nd) For loops vs. List comprehensions -\n", 122 | "\n", 123 | "General:\n", 124 | " Less extreme differences in speed.\n", 125 | " Main advantages of each are;\n", 126 | " LC - shorter, quicker to write, slightly faster\n", 127 | " FL - easier to read, can edit multiple variables in the loop\n", 128 | " \n", 129 | "Heuristics:\n", 130 | " > if your for loop changes one variable, and you care about speed, do it as a list comprehension\n", 131 | " > if it does more than one thing, and/or changes more than one variable, keep it as a for loop\n", 132 | " \n", 133 | "Note: This heuristic is more to do with readability than speed, other than the small benefit of using LCs\n", 134 | "Also Note: Nesting is supported in list comprehensions.\n", 135 | "\"\"\"\n", 136 | "\n", 137 | "# Using prebuilt_list from last example\n", 138 | "def square_list_FL(list_struct):\n", 139 | " out = []\n", 140 | " for element in list_struct:\n", 141 | " out.append(element**2)\n", 142 | " return out\n", 143 | "\n", 144 | "def square_list_LC(list_struct):\n", 145 | " return [element**2 for element in list_struct]\n", 146 | "\n", 147 | "print('square_list_FL, square_list_LC;')\n", 148 | "%timeit square_list_FL(prebuilt_list)\n", 149 | "%timeit square_list_LC(prebuilt_list)" 150 | ] 151 | }, 152 | { 153 | "cell_type": "code", 154 | "execution_count": 8, 155 | "metadata": {}, 156 | "outputs": [ 157 | { 158 | "name": "stdout", 159 | "output_type": "stream", 160 | "text": [ 161 | "1 loop, best of 3: 1.36 s per loop\n", 162 | "1 loop, best of 3: 186 ms per loop\n" 163 | ] 164 | } 165 | ], 166 | "source": [ 167 | "\"\"\"\n", 168 | "3rd) np.ndarray vs. np.matrix - \n", 169 | "\n", 170 | "General:\n", 171 | " np.matrix may be deprecated soon\n", 172 | " np.array can be used instead of np.matrix in almost all cases\n", 173 | " Development on np.matrix has slowed (or stopped?) and so np.array can be a few times faster in some cases\n", 174 | " \n", 175 | "Heuristic:\n", 176 | " Always prefer np.ndarray to np.matrix\n", 177 | "\"\"\"\n", 178 | "\n", 179 | "def generate_dense_matrix(N, density=0.2):\n", 180 | " real = np.random.rand(N, N) > density/2\n", 181 | " imaginary =(np.random.rand(N, N) > density/2)*1j\n", 182 | " return real+imaginary\n", 183 | "\n", 184 | "big_ndarray = generate_dense_matrix(500)\n", 185 | "big_matrix = np.matrix(generate_dense_matrix(500))\n", 186 | "\n", 187 | "%timeit big_matrix**300\n", 188 | "%timeit big_ndarray**300" 189 | ] 190 | }, 191 | { 192 | "cell_type": "code", 193 | "execution_count": null, 194 | "metadata": { 195 | "collapsed": true 196 | }, 197 | "outputs": [], 198 | "source": [] 199 | } 200 | ], 201 | "metadata": { 202 | "kernelspec": { 203 | "display_name": "Python 3", 204 | "language": "python", 205 | "name": "python3" 206 | }, 207 | "language_info": { 208 | "codemirror_mode": { 209 | "name": "ipython", 210 | "version": 3 211 | }, 212 | "file_extension": ".py", 213 | "mimetype": "text/x-python", 214 | "name": "python", 215 | "nbconvert_exporter": "python", 216 | "pygments_lexer": "ipython3", 217 | "version": "3.6.1" 218 | } 219 | }, 220 | "nbformat": 4, 221 | "nbformat_minor": 2 222 | } 223 | -------------------------------------------------------------------------------- /Python_App/tic_tac_toe_stage_4.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 13, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "import numpy as np " 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": 14, 15 | "metadata": {}, 16 | "outputs": [], 17 | "source": [ 18 | "symbols = [' ', 'X', 'O']" 19 | ] 20 | }, 21 | { 22 | "cell_type": "code", 23 | "execution_count": 15, 24 | "metadata": {}, 25 | "outputs": [], 26 | "source": [ 27 | "def draw_board(grid):\n", 28 | " print(\"\"\"\n", 29 | " {} | {} | {} \n", 30 | " -----------\n", 31 | " {} | {} | {} \n", 32 | " -----------\n", 33 | " {} | {} | {}\n", 34 | " \"\"\".format(grid[0],grid[1],grid[2],grid[3],grid[4],grid[5],grid[6],grid[7],grid[8]))" 35 | ] 36 | }, 37 | { 38 | "cell_type": "code", 39 | "execution_count": 16, 40 | "metadata": {}, 41 | "outputs": [], 42 | "source": [ 43 | "def initialise_moves():\n", 44 | " grid=[]\n", 45 | " for i in range(9):\n", 46 | " grid.append(0)\n", 47 | " return grid\n" 48 | ] 49 | }, 50 | { 51 | "cell_type": "code", 52 | "execution_count": 17, 53 | "metadata": {}, 54 | "outputs": [ 55 | { 56 | "name": "stdout", 57 | "output_type": "stream", 58 | "text": [ 59 | "[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']\n" 60 | ] 61 | } 62 | ], 63 | "source": [ 64 | "grid=[symbols[s] for s in initialise_moves()]\n", 65 | "print(grid)" 66 | ] 67 | }, 68 | { 69 | "cell_type": "code", 70 | "execution_count": 18, 71 | "metadata": {}, 72 | "outputs": [], 73 | "source": [ 74 | "def symbol_from_player(player):\n", 75 | " if player == 'user':\n", 76 | " return 1\n", 77 | " else:\n", 78 | " return 2" 79 | ] 80 | }, 81 | { 82 | "cell_type": "code", 83 | "execution_count": 19, 84 | "metadata": {}, 85 | "outputs": [], 86 | "source": [ 87 | "def who_goes_first():\n", 88 | " player=input(\"Who goes first: user or computer: \")\n", 89 | " return player.lower()" 90 | ] 91 | }, 92 | { 93 | "cell_type": "code", 94 | "execution_count": 20, 95 | "metadata": {}, 96 | "outputs": [], 97 | "source": [ 98 | "# Make Function to change Current player" 99 | ] 100 | }, 101 | { 102 | "cell_type": "code", 103 | "execution_count": 21, 104 | "metadata": {}, 105 | "outputs": [], 106 | "source": [ 107 | "def update_player(current_player):\n", 108 | " if current_player == 'user':\n", 109 | " return 'computer'\n", 110 | " else:\n", 111 | " return 'user'" 112 | ] 113 | }, 114 | { 115 | "cell_type": "code", 116 | "execution_count": 22, 117 | "metadata": {}, 118 | "outputs": [], 119 | "source": [ 120 | "def update_grid(grid,player):\n", 121 | " if player == \"user\":\n", 122 | " square = int(input(\"Select square on Grid (from 0 to 8): \"))\n", 123 | " \n", 124 | " else:\n", 125 | " square = np.random.randint(9)\n", 126 | " \n", 127 | " if grid[square] != ' ':\n", 128 | " print('Square taken, try again, ')\n", 129 | " update_grid(grid, player)\n", 130 | " else:\n", 131 | " grid[square] = symbols[symbol_from_player(player)]\n", 132 | " " 133 | ] 134 | }, 135 | { 136 | "cell_type": "code", 137 | "execution_count": 23, 138 | "metadata": {}, 139 | "outputs": [], 140 | "source": [ 141 | "def start_game(grid):\n", 142 | " current_player = None # as we are just starting the game \n", 143 | " is_first_go = True\n", 144 | " while True:\n", 145 | " draw_board(grid)\n", 146 | " if ' ' not in grid:\n", 147 | " print('board full')\n", 148 | " break \n", 149 | " if is_first_go:\n", 150 | " current_player = who_goes_first()\n", 151 | " is_first_go = False\n", 152 | " \n", 153 | " update_grid(grid,current_player)\n", 154 | " current_player = update_player(current_player)" 155 | ] 156 | }, 157 | { 158 | "cell_type": "code", 159 | "execution_count": 24, 160 | "metadata": {}, 161 | "outputs": [ 162 | { 163 | "name": "stdout", 164 | "output_type": "stream", 165 | "text": [ 166 | "\n", 167 | " | | \n", 168 | " -----------\n", 169 | " | | \n", 170 | " -----------\n", 171 | " | | \n", 172 | " \n", 173 | "Who goes first: user or computer: user\n", 174 | "Select square on Grid (from 0 to 8): 1\n", 175 | "\n", 176 | " | X | \n", 177 | " -----------\n", 178 | " | | \n", 179 | " -----------\n", 180 | " | | \n", 181 | " \n", 182 | "\n", 183 | " | X | \n", 184 | " -----------\n", 185 | " O | | \n", 186 | " -----------\n", 187 | " | | \n", 188 | " \n", 189 | "Select square on Grid (from 0 to 8): 1\n", 190 | "Aye, cheat much?\n", 191 | "Select square on Grid (from 0 to 8): 3\n", 192 | "Aye, cheat much?\n", 193 | "Select square on Grid (from 0 to 8): 4\n", 194 | "\n", 195 | " | X | \n", 196 | " -----------\n", 197 | " O | X | \n", 198 | " -----------\n", 199 | " | | \n", 200 | " \n", 201 | "\n", 202 | " | X | O \n", 203 | " -----------\n", 204 | " O | X | \n", 205 | " -----------\n", 206 | " | | \n", 207 | " \n", 208 | "Select square on Grid (from 0 to 8): 5\n", 209 | "\n", 210 | " | X | O \n", 211 | " -----------\n", 212 | " O | X | X \n", 213 | " -----------\n", 214 | " | | \n", 215 | " \n", 216 | "Aye, cheat much?\n", 217 | "\n", 218 | " | X | O \n", 219 | " -----------\n", 220 | " O | X | X \n", 221 | " -----------\n", 222 | " | O | \n", 223 | " \n", 224 | "Select square on Grid (from 0 to 8): 1\n", 225 | "Aye, cheat much?\n", 226 | "Select square on Grid (from 0 to 8): 0\n", 227 | "\n", 228 | " X | X | O \n", 229 | " -----------\n", 230 | " O | X | X \n", 231 | " -----------\n", 232 | " | O | \n", 233 | " \n", 234 | "Aye, cheat much?\n", 235 | "Aye, cheat much?\n", 236 | "\n", 237 | " X | X | O \n", 238 | " -----------\n", 239 | " O | X | X \n", 240 | " -----------\n", 241 | " O | O | \n", 242 | " \n", 243 | "Select square on Grid (from 0 to 8): 8\n", 244 | "\n", 245 | " X | X | O \n", 246 | " -----------\n", 247 | " O | X | X \n", 248 | " -----------\n", 249 | " O | O | X\n", 250 | " \n", 251 | "board full\n", 252 | "\n", 253 | " X | X | O \n", 254 | " -----------\n", 255 | " O | X | X \n", 256 | " -----------\n", 257 | " O | O | X\n", 258 | " \n" 259 | ] 260 | } 261 | ], 262 | "source": [ 263 | "start_game(grid)\n", 264 | "draw_board(grid)" 265 | ] 266 | }, 267 | { 268 | "cell_type": "code", 269 | "execution_count": null, 270 | "metadata": {}, 271 | "outputs": [], 272 | "source": [] 273 | } 274 | ], 275 | "metadata": { 276 | "kernelspec": { 277 | "display_name": "Python 3", 278 | "language": "python", 279 | "name": "python3" 280 | }, 281 | "language_info": { 282 | "codemirror_mode": { 283 | "name": "ipython", 284 | "version": 3 285 | }, 286 | "file_extension": ".py", 287 | "mimetype": "text/x-python", 288 | "name": "python", 289 | "nbconvert_exporter": "python", 290 | "pygments_lexer": "ipython3", 291 | "version": "3.6.4" 292 | } 293 | }, 294 | "nbformat": 4, 295 | "nbformat_minor": 2 296 | } 297 | -------------------------------------------------------------------------------- /Python_App/tic_tac_toe_stage_5.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "import numpy as np " 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": 2, 15 | "metadata": {}, 16 | "outputs": [], 17 | "source": [ 18 | "symbols = [' ', 'X', 'O']" 19 | ] 20 | }, 21 | { 22 | "cell_type": "code", 23 | "execution_count": 3, 24 | "metadata": {}, 25 | "outputs": [], 26 | "source": [ 27 | "def draw_board(grid):\n", 28 | " print(\"\"\"\n", 29 | " {} | {} | {} \n", 30 | " -----------\n", 31 | " {} | {} | {} \n", 32 | " -----------\n", 33 | " {} | {} | {}\n", 34 | " \"\"\".format(grid[0],grid[1],grid[2],grid[3],grid[4],grid[5],grid[6],grid[7],grid[8]))" 35 | ] 36 | }, 37 | { 38 | "cell_type": "code", 39 | "execution_count": 4, 40 | "metadata": {}, 41 | "outputs": [], 42 | "source": [ 43 | "def initialise_moves():\n", 44 | " grid=[]\n", 45 | " for i in range(9):\n", 46 | " grid.append(0)\n", 47 | " return grid\n" 48 | ] 49 | }, 50 | { 51 | "cell_type": "code", 52 | "execution_count": 5, 53 | "metadata": {}, 54 | "outputs": [ 55 | { 56 | "name": "stdout", 57 | "output_type": "stream", 58 | "text": [ 59 | "[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']\n" 60 | ] 61 | } 62 | ], 63 | "source": [ 64 | "grid=[symbols[s] for s in initialise_moves()]\n", 65 | "print(grid)" 66 | ] 67 | }, 68 | { 69 | "cell_type": "code", 70 | "execution_count": 6, 71 | "metadata": {}, 72 | "outputs": [], 73 | "source": [ 74 | "def symbol_from_player(player):\n", 75 | " if player == 'user':\n", 76 | " return 1\n", 77 | " else:\n", 78 | " return 2" 79 | ] 80 | }, 81 | { 82 | "cell_type": "code", 83 | "execution_count": 7, 84 | "metadata": {}, 85 | "outputs": [], 86 | "source": [ 87 | "def who_goes_first():\n", 88 | " player=input(\"Who goes first: user or computer: \")\n", 89 | " return player.lower()" 90 | ] 91 | }, 92 | { 93 | "cell_type": "code", 94 | "execution_count": 8, 95 | "metadata": {}, 96 | "outputs": [], 97 | "source": [ 98 | "# Make Function to change Current player" 99 | ] 100 | }, 101 | { 102 | "cell_type": "code", 103 | "execution_count": 9, 104 | "metadata": {}, 105 | "outputs": [], 106 | "source": [ 107 | "def update_player(current_player):\n", 108 | " if current_player == 'user':\n", 109 | " return 'computer'\n", 110 | " else:\n", 111 | " return 'user'" 112 | ] 113 | }, 114 | { 115 | "cell_type": "code", 116 | "execution_count": 10, 117 | "metadata": {}, 118 | "outputs": [], 119 | "source": [ 120 | "def update_grid(grid,player):\n", 121 | " if player == \"user\":\n", 122 | " square = int(input(\"Select square on Grid (from 0 to 8): \"))\n", 123 | " \n", 124 | " else:\n", 125 | " square = np.random.randint(9)\n", 126 | " \n", 127 | " if grid[square] != ' ':\n", 128 | " print('Square taken, try again, ')\n", 129 | " update_grid(grid, player)\n", 130 | " else:\n", 131 | " grid[square] = symbols[symbol_from_player(player)]\n", 132 | " " 133 | ] 134 | }, 135 | { 136 | "cell_type": "code", 137 | "execution_count": 11, 138 | "metadata": {}, 139 | "outputs": [], 140 | "source": [ 141 | "def game_over():\n", 142 | " if grid[0] == grid[1] == grid[2] != symbols[0]:\n", 143 | " #print(current_player \" Wins\")\n", 144 | " return True\n", 145 | " \n", 146 | " elif grid[3] == grid[4] == grid[5] != symbols[0]:\n", 147 | " #print(current_player \" Wins\")\n", 148 | " return True\n", 149 | " \n", 150 | " elif grid[6] == grid[7] == grid[8] != symbols[0]:\n", 151 | " #print(current_player \" Wins\")\n", 152 | " return True\n", 153 | " \n", 154 | " elif grid[0] == grid[3] ==grid[6] != symbols[0]:\n", 155 | " #print(current_player \" Wins\")\n", 156 | " return True\n", 157 | " \n", 158 | " elif grid[1] == grid[4] == grid[7] != symbols[0]:\n", 159 | " #print(currrent_player \" Wins\")\n", 160 | " return True \n", 161 | " \n", 162 | " elif grid[2] == grid[5] == grid[8] != symbols[0]:\n", 163 | " #print(current_player \" Wins\")\n", 164 | " return True\n", 165 | " \n", 166 | " elif grid[0] == grid[4] == grid[8] != symbols[0]:\n", 167 | " #print(current_player \" Wins\")\n", 168 | " return True\n", 169 | " \n", 170 | " elif grid[2] == grid[4] == grid[6] != symbols[0]:\n", 171 | " #print(current_player \" Wins\")\n", 172 | " return True\n", 173 | " \n", 174 | " else:\n", 175 | " return False" 176 | ] 177 | }, 178 | { 179 | "cell_type": "code", 180 | "execution_count": 12, 181 | "metadata": {}, 182 | "outputs": [], 183 | "source": [ 184 | "def start_game(grid):\n", 185 | " current_player = None # as we are just starting the game \n", 186 | " finished=False\n", 187 | " is_first_go = True\n", 188 | " while True:\n", 189 | " draw_board(grid)\n", 190 | " finished=game_over()\n", 191 | " if finished:\n", 192 | " print(\"Game over: '\" + update_player(current_player) + \"' Wins\")\n", 193 | " return 1\n", 194 | " \n", 195 | " if ' ' not in grid:\n", 196 | " print('board full')\n", 197 | " break \n", 198 | " if is_first_go:\n", 199 | " current_player = who_goes_first()\n", 200 | " is_first_go = False\n", 201 | " \n", 202 | " update_grid(grid,current_player)\n", 203 | " current_player = update_player(current_player)" 204 | ] 205 | }, 206 | { 207 | "cell_type": "code", 208 | "execution_count": 13, 209 | "metadata": {}, 210 | "outputs": [ 211 | { 212 | "name": "stdout", 213 | "output_type": "stream", 214 | "text": [ 215 | "\n", 216 | " | | \n", 217 | " -----------\n", 218 | " | | \n", 219 | " -----------\n", 220 | " | | \n", 221 | " \n", 222 | "Who goes first: user or computer: user\n", 223 | "Select square on Grid (from 0 to 8): 0\n", 224 | "\n", 225 | " X | | \n", 226 | " -----------\n", 227 | " | | \n", 228 | " -----------\n", 229 | " | | \n", 230 | " \n", 231 | "\n", 232 | " X | | \n", 233 | " -----------\n", 234 | " O | | \n", 235 | " -----------\n", 236 | " | | \n", 237 | " \n", 238 | "Select square on Grid (from 0 to 8): 4\n", 239 | "\n", 240 | " X | | \n", 241 | " -----------\n", 242 | " O | X | \n", 243 | " -----------\n", 244 | " | | \n", 245 | " \n", 246 | "\n", 247 | " X | | \n", 248 | " -----------\n", 249 | " O | X | \n", 250 | " -----------\n", 251 | " O | | \n", 252 | " \n", 253 | "Select square on Grid (from 0 to 8): 8\n", 254 | "\n", 255 | " X | | \n", 256 | " -----------\n", 257 | " O | X | \n", 258 | " -----------\n", 259 | " O | | X\n", 260 | " \n", 261 | "Game over: 'computer' Wins\n", 262 | "\n", 263 | " X | | \n", 264 | " -----------\n", 265 | " O | X | \n", 266 | " -----------\n", 267 | " O | | X\n", 268 | " \n" 269 | ] 270 | } 271 | ], 272 | "source": [ 273 | "start_game(grid)\n", 274 | "draw_board(grid)" 275 | ] 276 | }, 277 | { 278 | "cell_type": "code", 279 | "execution_count": null, 280 | "metadata": {}, 281 | "outputs": [], 282 | "source": [] 283 | } 284 | ], 285 | "metadata": { 286 | "kernelspec": { 287 | "display_name": "Python 3", 288 | "language": "python", 289 | "name": "python3" 290 | }, 291 | "language_info": { 292 | "codemirror_mode": { 293 | "name": "ipython", 294 | "version": 3 295 | }, 296 | "file_extension": ".py", 297 | "mimetype": "text/x-python", 298 | "name": "python", 299 | "nbconvert_exporter": "python", 300 | "pygments_lexer": "ipython3", 301 | "version": "3.6.4" 302 | } 303 | }, 304 | "nbformat": 4, 305 | "nbformat_minor": 2 306 | } 307 | -------------------------------------------------------------------------------- /conda_package_list.txt: -------------------------------------------------------------------------------- 1 | # This file may be used to create an environment using: 2 | # $ conda create --name --file 3 | # platform: osx-64 4 | @EXPLICIT 5 | https://repo.anaconda.com/pkgs/main/osx-64/libcxxabi-4.0.1-hcfea43d_1.conda 6 | https://conda.anaconda.org/anaconda/osx-64/blas-1.0-mkl.tar.bz2 7 | https://conda.anaconda.org/anaconda/osx-64/ca-certificates-2019.10.16-0.tar.bz2 8 | https://conda.anaconda.org/anaconda/osx-64/intel-openmp-2019.5-281.tar.bz2 9 | https://conda.anaconda.org/anaconda/osx-64/jpeg-9b-he5867d9_2.tar.bz2 10 | https://conda.anaconda.org/conda-forge/osx-64/libcxx-9.0.0-h89e68fa_1.tar.bz2 11 | https://conda.anaconda.org/anaconda/osx-64/libgfortran-3.0.1-h93005f0_2.tar.bz2 12 | https://conda.anaconda.org/anaconda/osx-64/libiconv-1.15-hdd342a3_7.tar.bz2 13 | https://conda.anaconda.org/anaconda/osx-64/libsodium-1.0.16-h3efe00b_0.tar.bz2 14 | https://conda.anaconda.org/anaconda/osx-64/llvm-openmp-4.0.1-hcfea43d_1.tar.bz2 15 | https://conda.anaconda.org/anaconda/osx-64/pandoc-2.2.3.2-0.tar.bz2 16 | https://repo.anaconda.com/pkgs/main/osx-64/xz-5.2.4-h1de35cc_4.conda 17 | https://repo.anaconda.com/pkgs/main/osx-64/zlib-1.2.11-h1de35cc_3.conda 18 | https://conda.anaconda.org/anaconda/osx-64/expat-2.2.6-h0a44026_0.tar.bz2 19 | https://conda.anaconda.org/anaconda/osx-64/icu-58.2-h4b95b61_1.tar.bz2 20 | https://repo.anaconda.com/pkgs/main/osx-64/libffi-3.2.1-h475c297_4.conda 21 | https://conda.anaconda.org/conda-forge/osx-64/libllvm9-9.0.0-h770b8ee_3.tar.bz2 22 | https://conda.anaconda.org/anaconda/osx-64/libpng-1.6.37-ha441bb4_0.tar.bz2 23 | https://conda.anaconda.org/anaconda/osx-64/mkl-2019.5-281.tar.bz2 24 | https://repo.anaconda.com/pkgs/main/osx-64/ncurses-6.1-h0a44026_1.conda 25 | https://conda.anaconda.org/anaconda/osx-64/openssl-1.1.1-h1de35cc_0.tar.bz2 26 | https://conda.anaconda.org/anaconda/osx-64/pcre-8.43-h0a44026_0.tar.bz2 27 | https://conda.anaconda.org/conda-forge/osx-64/tapi-1000.10.8-ha1b3eb9_4.tar.bz2 28 | https://repo.anaconda.com/pkgs/main/osx-64/tbb-2019.8-h04f5b5a_0.conda 29 | https://repo.anaconda.com/pkgs/main/osx-64/tk-8.6.8-ha441bb4_0.conda 30 | https://conda.anaconda.org/conda-forge/osx-64/xsimd-7.2.2-h770b8ee_0.tar.bz2 31 | https://conda.anaconda.org/anaconda/osx-64/zeromq-4.3.1-h0a44026_3.tar.bz2 32 | https://conda.anaconda.org/conda-forge/osx-64/clang-9.0.0-default_hf57f61e_4.tar.bz2 33 | https://conda.anaconda.org/conda-forge/osx-64/freetype-2.10.0-h24853df_1.tar.bz2 34 | https://conda.anaconda.org/anaconda/osx-64/gettext-0.19.8.1-h15daf44_3.tar.bz2 35 | https://conda.anaconda.org/conda-forge/osx-64/ld64-450.3-h3c32e8a_0.tar.bz2 36 | https://repo.anaconda.com/pkgs/main/osx-64/libedit-3.1.20181209-hb402a30_0.conda 37 | https://repo.anaconda.com/pkgs/main/osx-64/readline-7.0-h1de35cc_5.conda 38 | https://conda.anaconda.org/conda-forge/osx-64/cctools-927.0.2-h5ba7a2e_0.tar.bz2 39 | https://conda.anaconda.org/conda-forge/osx-64/clangxx-9.0.0-default_hf57f61e_4.tar.bz2 40 | https://conda.anaconda.org/anaconda/osx-64/glib-2.56.2-hd9629dc_0.tar.bz2 41 | https://repo.anaconda.com/pkgs/main/osx-64/sqlite-3.30.1-ha441bb4_0.tar.bz2 42 | https://conda.anaconda.org/conda-forge/noarch/compiler-rt_osx-64-9.0.0-ha700673_2.tar.bz2 43 | https://conda.anaconda.org/anaconda/osx-64/dbus-1.13.12-h90a0687_0.tar.bz2 44 | https://repo.anaconda.com/pkgs/main/osx-64/python-3.7.5-h359304d_0.conda 45 | https://conda.anaconda.org/anaconda/osx-64/qt-5.9.7-h468cd18_1.tar.bz2 46 | https://conda.anaconda.org/anaconda/osx-64/appnope-0.1.0-py37_0.tar.bz2 47 | https://conda.anaconda.org/anaconda/noarch/attrs-19.3.0-py_0.tar.bz2 48 | https://conda.anaconda.org/anaconda/osx-64/backcall-0.1.0-py37_0.tar.bz2 49 | https://conda.anaconda.org/anaconda/osx-64/certifi-2019.9.11-py37_0.tar.bz2 50 | https://conda.anaconda.org/conda-forge/osx-64/compiler-rt-9.0.0-ha700673_2.tar.bz2 51 | https://conda.anaconda.org/anaconda/noarch/decorator-4.4.1-py_0.tar.bz2 52 | https://conda.anaconda.org/anaconda/noarch/defusedxml-0.6.0-py_0.tar.bz2 53 | https://conda.anaconda.org/anaconda/osx-64/entrypoints-0.3-py37_0.tar.bz2 54 | https://conda.anaconda.org/conda-forge/noarch/gast-0.3.2-py_0.tar.bz2 55 | https://conda.anaconda.org/anaconda/osx-64/ipython_genutils-0.2.0-py37_0.tar.bz2 56 | https://conda.anaconda.org/conda-forge/osx-64/kiwisolver-1.1.0-py37ha1b3eb9_0.tar.bz2 57 | https://conda.anaconda.org/numba/osx-64/llvmlite-0.31.0dev0-py37_0.tar.bz2 58 | https://conda.anaconda.org/anaconda/osx-64/markupsafe-1.1.1-py37h1de35cc_0.tar.bz2 59 | https://conda.anaconda.org/anaconda/osx-64/mistune-0.8.4-py37h1de35cc_0.tar.bz2 60 | https://conda.anaconda.org/anaconda/osx-64/more-itertools-7.2.0-py37_0.tar.bz2 61 | https://conda.anaconda.org/anaconda/osx-64/pandocfilters-1.4.2-py37_1.tar.bz2 62 | https://conda.anaconda.org/anaconda/noarch/parso-0.5.1-py_0.tar.bz2 63 | https://conda.anaconda.org/anaconda/osx-64/pickleshare-0.7.5-py37_0.tar.bz2 64 | https://conda.anaconda.org/conda-forge/noarch/ply-3.11-py_1.tar.bz2 65 | https://conda.anaconda.org/anaconda/noarch/prometheus_client-0.7.1-py_0.tar.bz2 66 | https://conda.anaconda.org/anaconda/osx-64/ptyprocess-0.6.0-py37_0.tar.bz2 67 | https://conda.anaconda.org/conda-forge/noarch/pyparsing-2.4.5-py_0.tar.bz2 68 | https://conda.anaconda.org/anaconda/noarch/pytz-2019.3-py_0.tar.bz2 69 | https://conda.anaconda.org/anaconda/osx-64/pyzmq-18.1.0-py37h0a44026_0.tar.bz2 70 | https://conda.anaconda.org/anaconda/osx-64/send2trash-1.5.0-py37_0.tar.bz2 71 | https://conda.anaconda.org/anaconda/osx-64/sip-4.19.13-py37h0a44026_0.tar.bz2 72 | https://conda.anaconda.org/anaconda/osx-64/six-1.13.0-py37_0.tar.bz2 73 | https://conda.anaconda.org/anaconda/noarch/testpath-0.4.4-py_0.tar.bz2 74 | https://conda.anaconda.org/anaconda/osx-64/tornado-6.0.3-py37h1de35cc_0.tar.bz2 75 | https://conda.anaconda.org/anaconda/osx-64/wcwidth-0.1.7-py37_0.tar.bz2 76 | https://conda.anaconda.org/anaconda/osx-64/webencodings-0.5.1-py37_1.tar.bz2 77 | https://conda.anaconda.org/conda-forge/noarch/beniget-0.2.0-py_0.tar.bz2 78 | https://conda.anaconda.org/conda-forge/osx-64/clang_osx-64-9.0.0-h05bbb7f_6.tar.bz2 79 | https://conda.anaconda.org/conda-forge/noarch/cycler-0.10.0-py_2.tar.bz2 80 | https://conda.anaconda.org/anaconda/osx-64/jedi-0.15.1-py37_0.tar.bz2 81 | https://conda.anaconda.org/anaconda/osx-64/mkl-service-2.3.0-py37hfbe908c_0.tar.bz2 82 | https://conda.anaconda.org/anaconda/osx-64/pexpect-4.7.0-py37_0.tar.bz2 83 | https://conda.anaconda.org/anaconda/osx-64/pyqt-5.9.2-py37h655552a_0.tar.bz2 84 | https://conda.anaconda.org/anaconda/osx-64/pyrsistent-0.15.5-py37h1de35cc_0.tar.bz2 85 | https://conda.anaconda.org/anaconda/noarch/python-dateutil-2.8.1-py_0.tar.bz2 86 | https://repo.anaconda.com/pkgs/main/osx-64/setuptools-41.6.0-py37_0.tar.bz2 87 | https://conda.anaconda.org/anaconda/osx-64/terminado-0.8.3-py37_0.tar.bz2 88 | https://conda.anaconda.org/anaconda/osx-64/traitlets-4.3.3-py37_0.tar.bz2 89 | https://conda.anaconda.org/anaconda/noarch/zipp-0.6.0-py_0.tar.bz2 90 | https://conda.anaconda.org/anaconda/osx-64/bleach-3.1.0-py37_0.tar.bz2 91 | https://conda.anaconda.org/conda-forge/osx-64/clangxx_osx-64-9.0.0-h05bbb7f_6.tar.bz2 92 | https://conda.anaconda.org/anaconda/osx-64/cython-0.29.14-py37h0a44026_0.tar.bz2 93 | https://conda.anaconda.org/anaconda/osx-64/importlib_metadata-0.23-py37_0.tar.bz2 94 | https://conda.anaconda.org/anaconda/noarch/jinja2-2.10.3-py_0.tar.bz2 95 | https://conda.anaconda.org/anaconda/noarch/joblib-0.14.0-py_0.tar.bz2 96 | https://conda.anaconda.org/anaconda/osx-64/jupyter_core-4.6.1-py37_0.tar.bz2 97 | https://conda.anaconda.org/conda-forge/noarch/networkx-2.4-py_0.tar.bz2 98 | https://conda.anaconda.org/anaconda/osx-64/numpy-base-1.17.3-py37h6575580_0.tar.bz2 99 | https://conda.anaconda.org/anaconda/noarch/pygments-2.4.2-py_0.tar.bz2 100 | https://repo.anaconda.com/pkgs/main/osx-64/wheel-0.33.6-py37_0.tar.bz2 101 | https://conda.anaconda.org/anaconda/osx-64/jsonschema-3.2.0-py37_0.tar.bz2 102 | https://conda.anaconda.org/anaconda/osx-64/jupyter_client-5.3.4-py37_0.tar.bz2 103 | https://repo.anaconda.com/pkgs/main/osx-64/pip-19.3.1-py37_0.tar.bz2 104 | https://conda.anaconda.org/anaconda/noarch/prompt_toolkit-2.0.10-py_0.tar.bz2 105 | https://conda.anaconda.org/anaconda/osx-64/ipython-7.9.0-py37h39e3cac_0.tar.bz2 106 | https://conda.anaconda.org/anaconda/osx-64/nbformat-4.4.0-py37_0.tar.bz2 107 | https://conda.anaconda.org/anaconda/osx-64/ipykernel-5.1.3-py37h39e3cac_0.tar.bz2 108 | https://conda.anaconda.org/anaconda/osx-64/line_profiler-2.1.2-py37h1de35cc_0.tar.bz2 109 | https://conda.anaconda.org/anaconda/osx-64/nbconvert-5.6.1-py37_0.tar.bz2 110 | https://conda.anaconda.org/anaconda/osx-64/jupyter_console-6.0.0-py37_0.tar.bz2 111 | https://conda.anaconda.org/anaconda/osx-64/notebook-6.0.2-py37_0.tar.bz2 112 | https://conda.anaconda.org/anaconda/noarch/qtconsole-4.6.0-py_0.tar.bz2 113 | https://conda.anaconda.org/anaconda/osx-64/widgetsnbextension-3.5.1-py37_0.tar.bz2 114 | https://conda.anaconda.org/anaconda/noarch/ipywidgets-7.5.1-py_0.tar.bz2 115 | https://conda.anaconda.org/anaconda/osx-64/jupyter-1.0.0-py37_7.tar.bz2 116 | https://conda.anaconda.org/anaconda/osx-64/mkl_fft-1.0.15-py37h5e564d8_0.tar.bz2 117 | https://conda.anaconda.org/anaconda/osx-64/mkl_random-1.1.0-py37ha771720_0.tar.bz2 118 | https://conda.anaconda.org/anaconda/osx-64/numpy-1.17.3-py37h4174a10_0.tar.bz2 119 | https://conda.anaconda.org/conda-forge/osx-64/matplotlib-base-3.1.2-py37h11da6c2_1.tar.bz2 120 | https://repo.anaconda.com/pkgs/main/osx-64/numba-0.46.0-py37h6440ff4_0.tar.bz2 121 | https://conda.anaconda.org/anaconda/osx-64/pandas-0.25.3-py37h0a44026_0.tar.bz2 122 | https://conda.anaconda.org/conda-forge/osx-64/pythran-0.9.4.post1-py37ha1b3eb9_0.tar.bz2 123 | https://conda.anaconda.org/anaconda/osx-64/scipy-1.3.1-py37h1410ff5_0.tar.bz2 124 | https://conda.anaconda.org/conda-forge/osx-64/matplotlib-3.1.2-py37_1.tar.bz2 125 | https://conda.anaconda.org/anaconda/osx-64/patsy-0.5.1-py37_0.tar.bz2 126 | https://conda.anaconda.org/anaconda/osx-64/scikit-learn-0.21.3-py37h27c97d8_0.tar.bz2 127 | https://conda.anaconda.org/anaconda/osx-64/statsmodels-0.10.1-py37h1d22016_0.tar.bz2 128 | https://conda.anaconda.org/anaconda/noarch/seaborn-0.9.0-pyh91ea838_1.tar.bz2 129 | -------------------------------------------------------------------------------- /HighPerformance/Example2.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "

\n", 8 | "Speed-Optimisation for Scientific Python\n", 9 | "

" 10 | ] 11 | }, 12 | { 13 | "cell_type": "markdown", 14 | "metadata": {}, 15 | "source": [ 16 | "# Target Audience:\n", 17 | "\n", 18 | "### People with -\n", 19 | "* Basic working knowledge of python and common maths/science libraries (numpy, scipy)\n", 20 | "\n", 21 | "* A functioning Python3 installation. (Python 2 should also be fine but may require minor changes to some parts of the code)\n", 22 | "\n", 23 | "* Ability to install the following modules/libraries\n", 24 | "\n", 25 | "> \"pip install timeit\"\n", 26 | "\n", 27 | "> \"pip install cython\" <- not needed with Anaconda\n", 28 | "\n", 29 | "> \"pip install py-heat-magic\"\n", 30 | "\n", 31 | "> \"pip install line_profiler\"\n", 32 | "\n", 33 | "> \"pip install numba\"\n", 34 | "\n", 35 | "* (preferably) basic knowledge of Jupyter Notebooks. (Some slight differences in some techniques if replicated on the REPL or in a script)" 36 | ] 37 | }, 38 | { 39 | "cell_type": "code", 40 | "execution_count": 1, 41 | "metadata": {}, 42 | "outputs": [ 43 | { 44 | "name": "stderr", 45 | "output_type": "stream", 46 | "text": [ 47 | "WARNING: Disabling color, you really want to install colorlog.\n" 48 | ] 49 | } 50 | ], 51 | "source": [ 52 | "%load_ext Cython\n", 53 | "#%load_ext line_profiler\n", 54 | "#%load_ext heat\n", 55 | "import timeit\n", 56 | "from functools import lru_cache as cache\n", 57 | "from numba import jit, autojit, int64\n", 58 | "import numpy as np\n", 59 | "from numpy import linalg as LA" 60 | ] 61 | }, 62 | { 63 | "cell_type": "markdown", 64 | "metadata": {}, 65 | "source": [ 66 | "

\n", 67 | "Example 2: An inefficient fibonacci generator\n", 68 | "

\n", 69 | "### First a look at the base case; what we will be trying to improve" 70 | ] 71 | }, 72 | { 73 | "cell_type": "code", 74 | "execution_count": 2, 75 | "metadata": { 76 | "collapsed": true 77 | }, 78 | "outputs": [], 79 | "source": [ 80 | "def regular_fib(n):\n", 81 | " if n<2:\n", 82 | " return n\n", 83 | " return regular_fib(n-1)+regular_fib(n-2)" 84 | ] 85 | }, 86 | { 87 | "cell_type": "markdown", 88 | "metadata": {}, 89 | "source": [ 90 | "### Now we see if compiling it in C and using static typing improves the speed" 91 | ] 92 | }, 93 | { 94 | "cell_type": "code", 95 | "execution_count": 3, 96 | "metadata": { 97 | "collapsed": true 98 | }, 99 | "outputs": [], 100 | "source": [ 101 | "%%cython\n", 102 | "\n", 103 | "cpdef long cython_fib(long n):\n", 104 | " if n<2:\n", 105 | " return n\n", 106 | " return cython_fib(n-1)+cython_fib(n-2)" 107 | ] 108 | }, 109 | { 110 | "cell_type": "markdown", 111 | "metadata": {}, 112 | "source": [ 113 | "### Here we try using 'cacheing / memoization' - remembering the results of previous evaluations. \n", 114 | "### $\\therefore$ fib($n$) will only be calculated once $\\forall n \\leq 30$" 115 | ] 116 | }, 117 | { 118 | "cell_type": "code", 119 | "execution_count": 2, 120 | "metadata": {}, 121 | "outputs": [], 122 | "source": [ 123 | "@cache(maxsize=None)\n", 124 | "def cacheing_fib(n):\n", 125 | " if n<2:\n", 126 | " return n\n", 127 | " return cacheing_fib(n-1)+cacheing_fib(n-2)" 128 | ] 129 | }, 130 | { 131 | "cell_type": "markdown", 132 | "metadata": {}, 133 | "source": [ 134 | "### Finally, we try using Numba's just-in-time compiler - this attempts to convert array / complex mathematical expressions into optimised machine code" 135 | ] 136 | }, 137 | { 138 | "cell_type": "code", 139 | "execution_count": 5, 140 | "metadata": { 141 | "collapsed": true 142 | }, 143 | "outputs": [], 144 | "source": [ 145 | "@autojit\n", 146 | "def jit_fib(n):\n", 147 | " if n<2:\n", 148 | " return n\n", 149 | " return jit_fib(n-1)+jit_fib(n-2)" 150 | ] 151 | }, 152 | { 153 | "cell_type": "markdown", 154 | "metadata": { 155 | "collapsed": true 156 | }, 157 | "source": [ 158 | "## Results:" 159 | ] 160 | }, 161 | { 162 | "cell_type": "code", 163 | "execution_count": 6, 164 | "metadata": {}, 165 | "outputs": [ 166 | { 167 | "name": "stdout", 168 | "output_type": "stream", 169 | "text": [ 170 | "1 loop, best of 1: 1.57 s per loop\n", 171 | "\n", 172 | "\n", 173 | "\n", 174 | "1 loop, best of 1: 1.29 s per loop\n", 175 | "\n", 176 | "\n", 177 | "\n", 178 | "1 loop, best of 1: 12.6 ms per loop\n", 179 | "\n", 180 | "\n", 181 | "\n", 182 | "1 loop, best of 1: 75.5 µs per loop\n" 183 | ] 184 | } 185 | ], 186 | "source": [ 187 | "%timeit -n1 -r1 regular_fib(30)\n", 188 | "print('\\n\\n')\n", 189 | "%timeit -n1 -r1 jit_fib(30)\n", 190 | "print('\\n\\n')\n", 191 | "%timeit -n1 -r1 cython_fib(30)\n", 192 | "print('\\n\\n')\n", 193 | "%timeit -n1 -r1 cacheing_fib(30)" 194 | ] 195 | }, 196 | { 197 | "cell_type": "markdown", 198 | "metadata": {}, 199 | "source": [ 200 | "## Comments:\n" 201 | ] 202 | }, 203 | { 204 | "cell_type": "code", 205 | "execution_count": 7, 206 | "metadata": {}, 207 | "outputs": [ 208 | { 209 | "name": "stdout", 210 | "output_type": "stream", 211 | "text": [ 212 | "jit improvement ~ 1,000%\n", 213 | "cython improvement ~ 14,100%\n", 214 | "cacheing improvement ~ 2,410,000%\n" 215 | ] 216 | } 217 | ], 218 | "source": [ 219 | "# TODO: re-evaluate the times\n", 220 | "print(\"jit improvement ~ {:,.0f}%\".format(round(100*(1.74 / 175e-3),-2)))\n", 221 | "print(\"cython improvement ~ {:,.0f}%\".format(round(100*(1.74 / 12.3e-3),-2)))\n", 222 | "print(\"cacheing improvement ~ {:,.0f}%\".format(round(100*(1.74 / 72.3e-6),-4)))" 223 | ] 224 | }, 225 | { 226 | "cell_type": "code", 227 | "execution_count": 8, 228 | "metadata": { 229 | "collapsed": true 230 | }, 231 | "outputs": [], 232 | "source": [ 233 | "%lprun -f regular_fib regular_fib(30)\n", 234 | "# Just showing the line profiler being used" 235 | ] 236 | }, 237 | { 238 | "cell_type": "code", 239 | "execution_count": 3, 240 | "metadata": {}, 241 | "outputs": [], 242 | "source": [ 243 | "# Here's my attempt at a maximally optimised version, mixes in some mathematical optimisation with computational optimisation\n", 244 | "# This isn't what this talk is focusing on, just showing that you don't need to choose between one method or the other\n", 245 | "\n", 246 | "@cache(maxsize=None)\n", 247 | "def luke_fib(n):\n", 248 | " if (n<2):\n", 249 | " return n\n", 250 | " if n%2!=0:\n", 251 | " return luke_fib((n+1)//2)**2 + luke_fib((n-1)//2)**2\n", 252 | " half = luke_fib(n//2)\n", 253 | " return half**2 + 2*half*luke_fib(n//2 -1)" 254 | ] 255 | }, 256 | { 257 | "cell_type": "code", 258 | "execution_count": 4, 259 | "metadata": {}, 260 | "outputs": [ 261 | { 262 | "name": "stdout", 263 | "output_type": "stream", 264 | "text": [ 265 | "36.1 µs ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)\n", 266 | "1.09 ms ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)\n" 267 | ] 268 | } 269 | ], 270 | "source": [ 271 | "%timeit -n1 -r1 luke_fib(900)\n", 272 | "%timeit -n1 -r1 cacheing_fib(900) \n", 273 | "# Comparing to the other 'most efficient' one\n", 274 | "# we see that optimizing mathematically as well as in the code lets us go ~20 times faster again" 275 | ] 276 | }, 277 | { 278 | "cell_type": "code", 279 | "execution_count": 11, 280 | "metadata": { 281 | "collapsed": true 282 | }, 283 | "outputs": [], 284 | "source": [ 285 | "%%cython\n", 286 | "\n", 287 | "# Here we check if using a non-recursive method would have helped much\n", 288 | "\n", 289 | "cpdef long long non_recursive_fib(long n):\n", 290 | " a,b = 0,1\n", 291 | " for i in range(n-2):\n", 292 | " a,b = b,b+a\n", 293 | " return b" 294 | ] 295 | }, 296 | { 297 | "cell_type": "code", 298 | "execution_count": 20, 299 | "metadata": {}, 300 | "outputs": [ 301 | { 302 | "name": "stdout", 303 | "output_type": "stream", 304 | "text": [ 305 | "1 loop, best of 1: 783 µs per loop\n" 306 | ] 307 | }, 308 | { 309 | "name": "stderr", 310 | "output_type": "stream", 311 | "text": [ 312 | "Exception ignored in: '_cython_magic_b59f27d2215fefd63ec9f4a8d04c6d50.non_recursive_fib'\n", 313 | "OverflowError: int too big to convert\n" 314 | ] 315 | } 316 | ], 317 | "source": [ 318 | "%timeit -n1 -r1 non_recursive_fib(1000)" 319 | ] 320 | }, 321 | { 322 | "cell_type": "code", 323 | "execution_count": 16, 324 | "metadata": {}, 325 | "outputs": [ 326 | { 327 | "name": "stderr", 328 | "output_type": "stream", 329 | "text": [ 330 | "Exception ignored in: '_cython_magic_b59f27d2215fefd63ec9f4a8d04c6d50.non_recursive_fib'\n", 331 | "OverflowError: int too big to convert\n" 332 | ] 333 | }, 334 | { 335 | "data": { 336 | "text/plain": [ 337 | "0" 338 | ] 339 | }, 340 | "execution_count": 16, 341 | "metadata": {}, 342 | "output_type": "execute_result" 343 | } 344 | ], 345 | "source": [ 346 | "# That seems pretty fast, but what is that 'OverflowError' talking about?\n", 347 | "\n", 348 | "non_recursive_fib(1000)" 349 | ] 350 | }, 351 | { 352 | "cell_type": "code", 353 | "execution_count": 17, 354 | "metadata": {}, 355 | "outputs": [ 356 | { 357 | "data": { 358 | "text/plain": [ 359 | "43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875" 360 | ] 361 | }, 362 | "execution_count": 17, 363 | "metadata": {}, 364 | "output_type": "execute_result" 365 | } 366 | ], 367 | "source": [ 368 | "# We told cython to expect to output a 'long long' which is it's largest default type for an integer; so it allocated memory \n", 369 | "# for this output at the start. \n", 370 | "# However, the 1000th fibonacci number is far too big to fit into even this large pre-allocated memory, and so gave the above\n", 371 | "# OverflowError. \n", 372 | "# This is one place python has an advantage over strongly typed languages; it can allocate more memory as it \n", 373 | "# needs to, letting us evaluate the 1000th fibonacci number without complaining; \n", 374 | "\n", 375 | "luke_fib(1000)" 376 | ] 377 | } 378 | ], 379 | "metadata": { 380 | "kernelspec": { 381 | "display_name": "Python 3", 382 | "language": "python", 383 | "name": "python3" 384 | }, 385 | "language_info": { 386 | "codemirror_mode": { 387 | "name": "ipython", 388 | "version": 3 389 | }, 390 | "file_extension": ".py", 391 | "mimetype": "text/x-python", 392 | "name": "python", 393 | "nbconvert_exporter": "python", 394 | "pygments_lexer": "ipython3", 395 | "version": "3.6.7" 396 | } 397 | }, 398 | "nbformat": 4, 399 | "nbformat_minor": 2 400 | } 401 | -------------------------------------------------------------------------------- /HighPerformance/Pythran.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## Before using this notebook:\n", 8 | "\n", 9 | "### run \n", 10 | "```\n", 11 | "$ pythran pythran_example1.py\n", 12 | "```\n", 13 | "in order to convert the python code in 'pythran_example.py' to C++. (will generate a .so file)\n", 14 | "\n", 15 | "### What's in this file?\n", 16 | "Just one function, for finding the minimum product of pairs in two lists, with a comment to tell pythran the data types;\n", 17 | "\n", 18 | "```\n", 19 | "#pythran export min_product(float32 list, float32 list)\n", 20 | "def min_product(arr1, arr2):\n", 21 | " assert (len(arr1) == len(arr2)), 'mismatch in dimensions'\n", 22 | " return min([a*b for a,b in zip(arr1,arr2)])\n", 23 | "\n", 24 | "```" 25 | ] 26 | }, 27 | { 28 | "cell_type": "code", 29 | "execution_count": 1, 30 | "metadata": {}, 31 | "outputs": [], 32 | "source": [ 33 | "import numpy as np\n", 34 | "import pythran_example1 as pe1" 35 | ] 36 | }, 37 | { 38 | "cell_type": "markdown", 39 | "metadata": {}, 40 | "source": [ 41 | "### Let's test our pythranized function;" 42 | ] 43 | }, 44 | { 45 | "cell_type": "code", 46 | "execution_count": 5, 47 | "metadata": {}, 48 | "outputs": [ 49 | { 50 | "ename": "TypeError", 51 | "evalue": "Invalid call to pythranized function `min_product(list, list)'\nCandidates are:\n min_product(float32 list,float32 list)\n", 52 | "output_type": "error", 53 | "traceback": [ 54 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 55 | "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", 56 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mpe\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmin_product\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m1.2\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m1.4\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m99\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m55\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m1.00000002\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m88\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m77\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m66\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m55\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m44\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", 57 | "\u001b[0;31mTypeError\u001b[0m: Invalid call to pythranized function `min_product(list, list)'\nCandidates are:\n min_product(float32 list,float32 list)\n" 58 | ] 59 | } 60 | ], 61 | "source": [ 62 | "pe1.min_product([1.2,1.4,99,55,1.00000002],[88,77,66,55,44])" 63 | ] 64 | }, 65 | { 66 | "cell_type": "markdown", 67 | "metadata": {}, 68 | "source": [ 69 | "### Not ideal, what happened?\n", 70 | "\n", 71 | "We told pythran to expect float32 variables, but some of our elements were lists. In pure Python that's fine, but not with pythran. Can we still use the function though?" 72 | ] 73 | }, 74 | { 75 | "cell_type": "code", 76 | "execution_count": 6, 77 | "metadata": {}, 78 | "outputs": [ 79 | { 80 | "data": { 81 | "text/plain": [ 82 | "44.0" 83 | ] 84 | }, 85 | "execution_count": 6, 86 | "metadata": {}, 87 | "output_type": "execute_result" 88 | } 89 | ], 90 | "source": [ 91 | "pe1.min_product([1.2,1.4,99.,55.,1.00000002],[88.,77.,66.,55.,44.]) # Note: added '.' after each int element" 92 | ] 93 | }, 94 | { 95 | "cell_type": "markdown", 96 | "metadata": {}, 97 | "source": [ 98 | "### Yay, so as long as we type carefully / cast beforehand we're grand.\n", 99 | "### Now let's see how much faster the pythranized one is:" 100 | ] 101 | }, 102 | { 103 | "cell_type": "code", 104 | "execution_count": 7, 105 | "metadata": {}, 106 | "outputs": [ 107 | { 108 | "name": "stdout", 109 | "output_type": "stream", 110 | "text": [ 111 | "1.12 µs ± 21.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n", 112 | "1.3 µs ± 7.31 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n" 113 | ] 114 | } 115 | ], 116 | "source": [ 117 | "import timeit\n", 118 | "\n", 119 | "def min_product_pure_python(arr1, arr2):\n", 120 | " assert (len(arr1) == len(arr2)), 'mismatch in dimensions'\n", 121 | " return min([a*b for a,b in zip(arr1,arr2)])\n", 122 | "\n", 123 | "%timeit pe1.min_product([1.2,1.4,99.,55.,1.00000002],[88.,77.,66.,55.,44.]) \n", 124 | "%timeit min_product_pure_python([1.2,1.4,99.,55.,1.00000002],[88.,77.,66.,55.,44.]) " 125 | ] 126 | }, 127 | { 128 | "cell_type": "markdown", 129 | "metadata": {}, 130 | "source": [ 131 | "### Barely a difference; let's try with some much bigger lists;" 132 | ] 133 | }, 134 | { 135 | "cell_type": "code", 136 | "execution_count": 10, 137 | "metadata": {}, 138 | "outputs": [ 139 | { 140 | "name": "stdout", 141 | "output_type": "stream", 142 | "text": [ 143 | "30.1 ms ± 367 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n", 144 | "128 ms ± 186 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n" 145 | ] 146 | } 147 | ], 148 | "source": [ 149 | "import numpy as np\n", 150 | "\n", 151 | "test_a = [i for i in np.random.rand(1000000)] # we can't pass a numpy a pythran TypeError - we said we'd use a list\n", 152 | "test_b = [i for i in np.random.rand(1000000)]\n", 153 | "\n", 154 | "%timeit pe.min_product(test_a, test_b) \n", 155 | "%timeit min_product_pure_python(test_a, test_b) " 156 | ] 157 | }, 158 | { 159 | "cell_type": "markdown", 160 | "metadata": {}, 161 | "source": [ 162 | "### That's a bit more like it - over 4 times as fast, and with only adding a comment to tell pythran the types" 163 | ] 164 | }, 165 | { 166 | "cell_type": "markdown", 167 | "metadata": {}, 168 | "source": [ 169 | "### So, useful - but nothing we couldn't do easily already with Cython. \n", 170 | "### Let's do something that's a bit trickier with Cython - using Numpy stuff as well" 171 | ] 172 | }, 173 | { 174 | "cell_type": "code", 175 | "execution_count": 2, 176 | "metadata": {}, 177 | "outputs": [], 178 | "source": [ 179 | "# I've borrowed this example from Pythran's documentation\n", 180 | "# We'll ake the pure python version first:\n", 181 | "\n", 182 | "import numpy as np\n", 183 | "def arc_dist(theta1, phi1, theta2, phi2):\n", 184 | " temp = (np.sin((theta2-theta1)/2)**2 + \n", 185 | " (np.cos(theta1)*np.cos(theta2)) * np.sin((phi2-phi1)/2)**2)\n", 186 | " return 2 * np.arctan2(np.sqrt(temp), np.sqrt(1-temp))\n", 187 | "\n", 188 | "'''\n", 189 | "And our pythran version (will be pretty much the exact same:\n", 190 | "\n", 191 | "#pythran export arc_dist(float[], float[], float[], float[])\n", 192 | "import numpy as np\n", 193 | "def arc_dist(theta1, phi1, theta2, phi2):\n", 194 | " temp = (np.sin((theta2-theta1)/2)**2 + \n", 195 | " (np.cos(theta1)*np.cos(theta2)) * np.sin((phi2-phi1)/2)**2)\n", 196 | " return 2 * np.arctan2(np.sqrt(temp), np.sqrt(1-temp))\n", 197 | "''';" 198 | ] 199 | }, 200 | { 201 | "cell_type": "markdown", 202 | "metadata": {}, 203 | "source": [ 204 | "### Okay, run \n", 205 | "```\n", 206 | "$ pythran pythran_example2.py\n", 207 | "```\n", 208 | "### to compile this one, then let's compare them;" 209 | ] 210 | }, 211 | { 212 | "cell_type": "code", 213 | "execution_count": 3, 214 | "metadata": {}, 215 | "outputs": [ 216 | { 217 | "name": "stdout", 218 | "output_type": "stream", 219 | "text": [ 220 | "11.2 ms ± 551 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n", 221 | "18.9 ms ± 397 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n" 222 | ] 223 | } 224 | ], 225 | "source": [ 226 | "import pythran_example2 as pe2\n", 227 | "\n", 228 | "theta_1 = np.random.rand(100000)*np.pi # we can't pass a numpy a pythran TypeError - we said we'd use a list\n", 229 | "theta_2 = np.random.rand(100000)*np.pi # we can't pass a numpy a pythran TypeError - we said we'd use a list\n", 230 | "\n", 231 | "phi_1 = np.random.rand(100000)*np.pi*2 - np.pi\n", 232 | "phi_2 = np.random.rand(100000)*np.pi*2 - np.pi\n", 233 | "\n", 234 | "%timeit pe2.arc_dist(theta_1,phi_1,theta_2,phi_2) \n", 235 | "%timeit arc_dist(theta_1,phi_1,theta_2,phi_2) " 236 | ] 237 | }, 238 | { 239 | "cell_type": "markdown", 240 | "metadata": {}, 241 | "source": [ 242 | "### A bit of an improvement, but can we do better?\n", 243 | "### We can! we can tell pythran to try to vectorize and parallelise the loops;\n", 244 | "\n", 245 | "We've already got a pythran_example2 module created and imported so we're going to give this version a new name with the '-o' flag in the pythran command; run\n", 246 | "```\n", 247 | "$ pythran -O5 -fopenmp -march=native pythran_example2.py -o pythran_example2_opt.so\n", 248 | "```\n", 249 | "*flags*\n", 250 | "* -O5 : optimisation level 5\n", 251 | "* -fopenmp : use openmp to parallelise\n", 252 | "* -march=native : target archietecture compatability for whatever chip you're currently using\n", 253 | "\n", 254 | "And let's test it now;" 255 | ] 256 | }, 257 | { 258 | "cell_type": "code", 259 | "execution_count": 4, 260 | "metadata": {}, 261 | "outputs": [ 262 | { 263 | "name": "stdout", 264 | "output_type": "stream", 265 | "text": [ 266 | "5.25 ms ± 324 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n" 267 | ] 268 | } 269 | ], 270 | "source": [ 271 | "import pythran_example2_opt as pe2opt\n", 272 | "%timeit pe2opt.arc_dist(theta_1,phi_1,theta_2,phi_2) " 273 | ] 274 | }, 275 | { 276 | "cell_type": "markdown", 277 | "metadata": {}, 278 | "source": [ 279 | "### Twice as fast! And if you have a better processor than my laptop does (or access to a server cluster) you'll see a much bigger improvement.\n", 280 | "\n", 281 | "### So far this has mostly been using external files and commands, but pythran does have some jupyter-specific functionalities, similar to cython - we'll quickly look at them now." 282 | ] 283 | }, 284 | { 285 | "cell_type": "code", 286 | "execution_count": 5, 287 | "metadata": {}, 288 | "outputs": [ 289 | { 290 | "name": "stderr", 291 | "output_type": "stream", 292 | "text": [ 293 | "WARNING: Disabling color, you really want to install colorlog.\n" 294 | ] 295 | } 296 | ], 297 | "source": [ 298 | "%load_ext pythran.magic " 299 | ] 300 | }, 301 | { 302 | "cell_type": "code", 303 | "execution_count": 14, 304 | "metadata": {}, 305 | "outputs": [], 306 | "source": [ 307 | "%%pythran -O2 -fopenmp # pass arguments like this (note no brackets - unlike some tutorials)\n", 308 | " # This is a python3 update / change I *think*, python2 may still use\n", 309 | " # %%pythran(-O2 -fopenmp) type syntax\n", 310 | "\n", 311 | "#pythran export average(float[]) # .so file generated named 'pythranised_.so'\n", 312 | "def average(nums): \n", 313 | " running_total = 0\n", 314 | " for num in nums:\n", 315 | " running_total += num\n", 316 | " return running_total/len(nums)" 317 | ] 318 | }, 319 | { 320 | "cell_type": "code", 321 | "execution_count": 15, 322 | "metadata": {}, 323 | "outputs": [], 324 | "source": [ 325 | "def average_pure_python(nums): \n", 326 | " running_total = 0\n", 327 | " for num in nums:\n", 328 | " running_total += num\n", 329 | " return running_total/len(nums)" 330 | ] 331 | }, 332 | { 333 | "cell_type": "code", 334 | "execution_count": 16, 335 | "metadata": {}, 336 | "outputs": [ 337 | { 338 | "name": "stdout", 339 | "output_type": "stream", 340 | "text": [ 341 | "98.2 µs ± 2.31 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n", 342 | "9.43 ms ± 96.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n" 343 | ] 344 | } 345 | ], 346 | "source": [ 347 | "test_list = np.random.rand(100000)\n", 348 | "\n", 349 | "%timeit average(test_list)\n", 350 | "%timeit average_pure_python(test_list)" 351 | ] 352 | }, 353 | { 354 | "cell_type": "markdown", 355 | "metadata": {}, 356 | "source": [ 357 | "### As always, this is a massive, complicated tool that has a lot more to offer than I've shown, as well as other limitations I've not mentioned. This guide is only intended as an introduction / something to try to quickly get some speedups cheaply" 358 | ] 359 | }, 360 | { 361 | "cell_type": "code", 362 | "execution_count": null, 363 | "metadata": {}, 364 | "outputs": [], 365 | "source": [] 366 | } 367 | ], 368 | "metadata": { 369 | "kernelspec": { 370 | "display_name": "Python 3", 371 | "language": "python", 372 | "name": "python3" 373 | }, 374 | "language_info": { 375 | "codemirror_mode": { 376 | "name": "ipython", 377 | "version": 3 378 | }, 379 | "file_extension": ".py", 380 | "mimetype": "text/x-python", 381 | "name": "python", 382 | "nbconvert_exporter": "python", 383 | "pygments_lexer": "ipython3", 384 | "version": "3.6.7" 385 | } 386 | }, 387 | "nbformat": 4, 388 | "nbformat_minor": 2 389 | } 390 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /HighPerformance/Stage4_Cython.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "

\n", 8 | "Cython:\n", 9 | "

\n", 10 | "\n", 11 | "#### From Cython's documentation;\n", 12 | "***\"Cython is Python with C data types.\"***\n", 13 | "\n", 14 | "#### There are a few different ways to use Cython;\n", 15 | "#### > From a Jupyter Notebook using Jupyter Magic\n", 16 | "#### > Writing a .pyx file to be compiled by Cython\n", 17 | "\n", 18 | "#### Resources for a much better understanding of usage / inner workings of Cython will be at the bottom of this notebook, but in this notebook (and talk) we will only focus on using Cython with Jupyter magic, and we will only learn the basics of it enough to achieve some easy performance boosts." 19 | ] 20 | }, 21 | { 22 | "cell_type": "markdown", 23 | "metadata": {}, 24 | "source": [ 25 | "## Official Website: http://cython.org/" 26 | ] 27 | }, 28 | { 29 | "cell_type": "code", 30 | "execution_count": 9, 31 | "metadata": {}, 32 | "outputs": [ 33 | { 34 | "name": "stdout", 35 | "output_type": "stream", 36 | "text": [ 37 | "The cython extension is already loaded. To reload it, use:\n", 38 | " %reload_ext cython\n" 39 | ] 40 | } 41 | ], 42 | "source": [ 43 | "\"\"\"\n", 44 | "We're just going to jump straight in;\n", 45 | "\"\"\"\n", 46 | "\n", 47 | "%load_ext cython\n", 48 | "import numpy as np\n", 49 | "import math\n", 50 | "import timeit" 51 | ] 52 | }, 53 | { 54 | "cell_type": "code", 55 | "execution_count": null, 56 | "metadata": { 57 | "collapsed": true 58 | }, 59 | "outputs": [], 60 | "source": [ 61 | "\"\"\"\n", 62 | "There are a few different ways to declare a Cython-y function:\n", 63 | "\n", 64 | "def func1():\n", 65 | " # Will be visible in pure python and in cython, can implement C/Cython functions\n", 66 | "\n", 67 | "cdef func2():\n", 68 | " # Will *NOT* be visible in pure python, only to other cython functions, can implement C/Cython and/or pure Python\n", 69 | " \n", 70 | "cpdef func3():\n", 71 | " # Will be visible from both pure python and cython code, is itself compiled as cython, can imlplement everything\n", 72 | "\n", 73 | "\"\"\"" 74 | ] 75 | }, 76 | { 77 | "cell_type": "code", 78 | "execution_count": 27, 79 | "metadata": {}, 80 | "outputs": [ 81 | { 82 | "data": { 83 | "text/html": [ 84 | "\n", 85 | "\n", 86 | "\n", 87 | "\n", 88 | " \n", 89 | " Cython: _cython_magic_af3ca03e45eaf85e8add19a459cc9263.pyx\n", 90 | " \n", 442 | " \n", 449 | "\n", 450 | "\n", 451 | "

Generated by Cython 0.25.2

\n", 452 | "

\n", 453 | " Yellow lines hint at Python interaction.
\n", 454 | " Click on a line that starts with a \"+\" to see the C code that Cython generated for it.\n", 455 | "

\n", 456 | "
 01: # -a flag tells it to show us the C that Cython generates for our code, we don't usually care
\n", 457 | "
 02: 
\n", 458 | "
 03: # This example shows that we can access the C standard library easily wth Cython 
\n", 459 | "
 04: 
\n", 460 | "
 05: from libc.math cimport sin
\n", 461 | "
 06: # Note: to import C/C++ functions, we use 'cimport' rather than 'import'
\n", 462 | "
 07: 
\n", 463 | "
 08: # Note in the example below that cython allows us to specify types of variables; this helps it know 
\n", 464 | "
 09: # how to speed things up. We'll make one function directly in C with types specified, and another 
\n", 465 | "
 10: # in python without specifying types, but still calling the C function 'sin' -
\n", 466 | "
 11: 
\n", 467 | "
+12: cpdef double cython_func(double x):
\n", 468 | "
static PyObject *__pyx_pw_46_cython_magic_af3ca03e45eaf85e8add19a459cc9263_1cython_func(PyObject *__pyx_self, PyObject *__pyx_arg_x); /*proto*/\n",
469 |        "static double __pyx_f_46_cython_magic_af3ca03e45eaf85e8add19a459cc9263_cython_func(double __pyx_v_x, CYTHON_UNUSED int __pyx_skip_dispatch) {\n",
470 |        "  double __pyx_r;\n",
471 |        "  __Pyx_RefNannyDeclarations\n",
472 |        "  __Pyx_RefNannySetupContext(\"cython_func\", 0);\n",
473 |        "/* … */\n",
474 |        "  /* function exit code */\n",
475 |        "  __pyx_L0:;\n",
476 |        "  __Pyx_RefNannyFinishContext();\n",
477 |        "  return __pyx_r;\n",
478 |        "}\n",
479 |        "\n",
480 |        "/* Python wrapper */\n",
481 |        "static PyObject *__pyx_pw_46_cython_magic_af3ca03e45eaf85e8add19a459cc9263_1cython_func(PyObject *__pyx_self, PyObject *__pyx_arg_x); /*proto*/\n",
482 |        "static PyObject *__pyx_pw_46_cython_magic_af3ca03e45eaf85e8add19a459cc9263_1cython_func(PyObject *__pyx_self, PyObject *__pyx_arg_x) {\n",
483 |        "  double __pyx_v_x;\n",
484 |        "  PyObject *__pyx_r = 0;\n",
485 |        "  __Pyx_RefNannyDeclarations\n",
486 |        "  __Pyx_RefNannySetupContext(\"cython_func (wrapper)\", 0);\n",
487 |        "  assert(__pyx_arg_x); {\n",
488 |        "    __pyx_v_x = __pyx_PyFloat_AsDouble(__pyx_arg_x); if (unlikely((__pyx_v_x == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 12, __pyx_L3_error)\n",
489 |        "  }\n",
490 |        "  goto __pyx_L4_argument_unpacking_done;\n",
491 |        "  __pyx_L3_error:;\n",
492 |        "  __Pyx_AddTraceback(\"_cython_magic_af3ca03e45eaf85e8add19a459cc9263.cython_func\", __pyx_clineno, __pyx_lineno, __pyx_filename);\n",
493 |        "  __Pyx_RefNannyFinishContext();\n",
494 |        "  return NULL;\n",
495 |        "  __pyx_L4_argument_unpacking_done:;\n",
496 |        "  __pyx_r = __pyx_pf_46_cython_magic_af3ca03e45eaf85e8add19a459cc9263_cython_func(__pyx_self, ((double)__pyx_v_x));\n",
497 |        "\n",
498 |        "  /* function exit code */\n",
499 |        "  __Pyx_RefNannyFinishContext();\n",
500 |        "  return __pyx_r;\n",
501 |        "}\n",
502 |        "\n",
503 |        "static PyObject *__pyx_pf_46_cython_magic_af3ca03e45eaf85e8add19a459cc9263_cython_func(CYTHON_UNUSED PyObject *__pyx_self, double __pyx_v_x) {\n",
504 |        "  PyObject *__pyx_r = NULL;\n",
505 |        "  __Pyx_RefNannyDeclarations\n",
506 |        "  __Pyx_RefNannySetupContext(\"cython_func\", 0);\n",
507 |        "  __Pyx_XDECREF(__pyx_r);\n",
508 |        "  __pyx_t_1 = PyFloat_FromDouble(__pyx_f_46_cython_magic_af3ca03e45eaf85e8add19a459cc9263_cython_func(__pyx_v_x, 0)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 12, __pyx_L1_error)\n",
509 |        "  __Pyx_GOTREF(__pyx_t_1);\n",
510 |        "  __pyx_r = __pyx_t_1;\n",
511 |        "  __pyx_t_1 = 0;\n",
512 |        "  goto __pyx_L0;\n",
513 |        "\n",
514 |        "  /* function exit code */\n",
515 |        "  __pyx_L1_error:;\n",
516 |        "  __Pyx_XDECREF(__pyx_t_1);\n",
517 |        "  __Pyx_AddTraceback(\"_cython_magic_af3ca03e45eaf85e8add19a459cc9263.cython_func\", __pyx_clineno, __pyx_lineno, __pyx_filename);\n",
518 |        "  __pyx_r = NULL;\n",
519 |        "  __pyx_L0:;\n",
520 |        "  __Pyx_XGIVEREF(__pyx_r);\n",
521 |        "  __Pyx_RefNannyFinishContext();\n",
522 |        "  return __pyx_r;\n",
523 |        "}\n",
524 |        "
+13:     return sin(x*x)
\n", 525 | "
  __pyx_r = sin((__pyx_v_x * __pyx_v_x));\n",
526 |        "  goto __pyx_L0;\n",
527 |        "
 14: 
\n", 528 | "
+15: def python_func(x):
\n", 529 | "
/* Python wrapper */\n",
530 |        "static PyObject *__pyx_pw_46_cython_magic_af3ca03e45eaf85e8add19a459cc9263_3python_func(PyObject *__pyx_self, PyObject *__pyx_v_x); /*proto*/\n",
531 |        "static PyMethodDef __pyx_mdef_46_cython_magic_af3ca03e45eaf85e8add19a459cc9263_3python_func = {\"python_func\", (PyCFunction)__pyx_pw_46_cython_magic_af3ca03e45eaf85e8add19a459cc9263_3python_func, METH_O, 0};\n",
532 |        "static PyObject *__pyx_pw_46_cython_magic_af3ca03e45eaf85e8add19a459cc9263_3python_func(PyObject *__pyx_self, PyObject *__pyx_v_x) {\n",
533 |        "  PyObject *__pyx_r = 0;\n",
534 |        "  __Pyx_RefNannyDeclarations\n",
535 |        "  __Pyx_RefNannySetupContext(\"python_func (wrapper)\", 0);\n",
536 |        "  __pyx_r = __pyx_pf_46_cython_magic_af3ca03e45eaf85e8add19a459cc9263_2python_func(__pyx_self, ((PyObject *)__pyx_v_x));\n",
537 |        "\n",
538 |        "  /* function exit code */\n",
539 |        "  __Pyx_RefNannyFinishContext();\n",
540 |        "  return __pyx_r;\n",
541 |        "}\n",
542 |        "\n",
543 |        "static PyObject *__pyx_pf_46_cython_magic_af3ca03e45eaf85e8add19a459cc9263_2python_func(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_x) {\n",
544 |        "  PyObject *__pyx_r = NULL;\n",
545 |        "  __Pyx_RefNannyDeclarations\n",
546 |        "  __Pyx_RefNannySetupContext(\"python_func\", 0);\n",
547 |        "/* … */\n",
548 |        "  /* function exit code */\n",
549 |        "  __pyx_L1_error:;\n",
550 |        "  __Pyx_XDECREF(__pyx_t_1);\n",
551 |        "  __Pyx_AddTraceback(\"_cython_magic_af3ca03e45eaf85e8add19a459cc9263.python_func\", __pyx_clineno, __pyx_lineno, __pyx_filename);\n",
552 |        "  __pyx_r = NULL;\n",
553 |        "  __pyx_L0:;\n",
554 |        "  __Pyx_XGIVEREF(__pyx_r);\n",
555 |        "  __Pyx_RefNannyFinishContext();\n",
556 |        "  return __pyx_r;\n",
557 |        "}\n",
558 |        "/* … */\n",
559 |        "  __pyx_tuple_ = PyTuple_Pack(1, __pyx_n_s_x); if (unlikely(!__pyx_tuple_)) __PYX_ERR(0, 15, __pyx_L1_error)\n",
560 |        "  __Pyx_GOTREF(__pyx_tuple_);\n",
561 |        "  __Pyx_GIVEREF(__pyx_tuple_);\n",
562 |        "/* … */\n",
563 |        "  __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_46_cython_magic_af3ca03e45eaf85e8add19a459cc9263_3python_func, NULL, __pyx_n_s_cython_magic_af3ca03e45eaf85e8a); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 15, __pyx_L1_error)\n",
564 |        "  __Pyx_GOTREF(__pyx_t_1);\n",
565 |        "  if (PyDict_SetItem(__pyx_d, __pyx_n_s_python_func, __pyx_t_1) < 0) __PYX_ERR(0, 15, __pyx_L1_error)\n",
566 |        "  __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;\n",
567 |        "
+16:     return sin(x*x)
\n", 568 | "
  __Pyx_XDECREF(__pyx_r);\n",
569 |        "  __pyx_t_1 = PyNumber_Multiply(__pyx_v_x, __pyx_v_x); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 16, __pyx_L1_error)\n",
570 |        "  __Pyx_GOTREF(__pyx_t_1);\n",
571 |        "  __pyx_t_2 = __pyx_PyFloat_AsDouble(__pyx_t_1); if (unlikely((__pyx_t_2 == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 16, __pyx_L1_error)\n",
572 |        "  __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;\n",
573 |        "  __pyx_t_1 = PyFloat_FromDouble(sin(__pyx_t_2)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 16, __pyx_L1_error)\n",
574 |        "  __Pyx_GOTREF(__pyx_t_1);\n",
575 |        "  __pyx_r = __pyx_t_1;\n",
576 |        "  __pyx_t_1 = 0;\n",
577 |        "  goto __pyx_L0;\n",
578 |        "
" 579 | ], 580 | "text/plain": [ 581 | "" 582 | ] 583 | }, 584 | "execution_count": 27, 585 | "metadata": {}, 586 | "output_type": "execute_result" 587 | } 588 | ], 589 | "source": [ 590 | "%%cython -a\n", 591 | "# -a flag tells it to show us the C that Cython generates for our code, we don't usually care\n", 592 | "\n", 593 | "# This example shows that we can access the C standard library easily wth Cython \n", 594 | "\n", 595 | "from libc.math cimport sin\n", 596 | "# Note: to import C/C++ functions, we use 'cimport' rather than 'import'\n", 597 | "\n", 598 | "# Note in the example below that cython allows us to specify types of variables; this helps it know \n", 599 | "# how to speed things up. We'll make one function directly in C with types specified, and another \n", 600 | "# in python without specifying types, but still calling the C function 'sin' -\n", 601 | "\n", 602 | "cpdef double cython_func(double x):\n", 603 | " return sin(x*x)\n", 604 | "\n", 605 | "def python_func(x):\n", 606 | " return sin(x*x)" 607 | ] 608 | }, 609 | { 610 | "cell_type": "code", 611 | "execution_count": 26, 612 | "metadata": {}, 613 | "outputs": [ 614 | { 615 | "name": "stdout", 616 | "output_type": "stream", 617 | "text": [ 618 | "The slowest run took 15.56 times longer than the fastest. This could mean that an intermediate result is being cached.\n", 619 | "1000000 loops, best of 3: 343 ns per loop\n", 620 | "The slowest run took 10.32 times longer than the fastest. This could mean that an intermediate result is being cached.\n", 621 | "1000000 loops, best of 3: 517 ns per loop\n", 622 | "The slowest run took 9.72 times longer than the fastest. This could mean that an intermediate result is being cached.\n", 623 | "100000 loops, best of 3: 5.53 µs per loop\n" 624 | ] 625 | } 626 | ], 627 | "source": [ 628 | "%timeit cython_func(5)\n", 629 | "%timeit python_func(5)\n", 630 | "%timeit np.sin(5*5)" 631 | ] 632 | }, 633 | { 634 | "cell_type": "markdown", 635 | "metadata": {}, 636 | "source": [ 637 | "## So we can see that, while not needed, telling Cython the types lets it get an extra bit of a boost - but still either is more efficient than not using the native C function.\n", 638 | "\n", 639 | "## Also note that while that example only shows a smallish (up to ~20x) speedup, it's worth mentioning that we were comparing it to a Numpy function, which is already pretty optimised." 640 | ] 641 | }, 642 | { 643 | "cell_type": "code", 644 | "execution_count": 31, 645 | "metadata": { 646 | "collapsed": true 647 | }, 648 | "outputs": [], 649 | "source": [ 650 | "%%cython\n", 651 | "\n", 652 | "\"\"\"\n", 653 | "Cython doesn't always have a pre-made way of importing C/C++ functions, so you may need to make one.\n", 654 | "(note this is not the case in the example below, but the method works anyway so it doesn't matter for the example)\n", 655 | "\"\"\"\n", 656 | "\n", 657 | "cdef extern from \"math.h\":\n", 658 | " double cos(double x)\n", 659 | "# Here we've just made a cython-only 'cos' function that uses the C cos function\n", 660 | " \n", 661 | "cpdef double cython_cos(double x):\n", 662 | " return cos(x*x)\n", 663 | "# Here we've made a cython/python type function that uses the 'cos' function we just made\n", 664 | "# Note: in case of doubt, check how we imported the sin one in first example; we didn't import the whole math lib" 665 | ] 666 | }, 667 | { 668 | "cell_type": "code", 669 | "execution_count": 32, 670 | "metadata": {}, 671 | "outputs": [ 672 | { 673 | "data": { 674 | "text/plain": [ 675 | "-0.7915275406282308" 676 | ] 677 | }, 678 | "execution_count": 32, 679 | "metadata": {}, 680 | "output_type": "execute_result" 681 | } 682 | ], 683 | "source": [ 684 | "# And just to show it works;\n", 685 | "cython_cos(49.4)" 686 | ] 687 | }, 688 | { 689 | "cell_type": "markdown", 690 | "metadata": {}, 691 | "source": [ 692 | "### In the above example, we assume Cython is able to find the 'math' header file, which is part of the stdlib for C++ so no big deal to find. Additionally, we only wanted to grab a function rather than a whole class. \n", 693 | "\n", 694 | "### Here we look at using a completely custom C++ class (Rectangle.cpp & Rectangle.h, both in Rectangle/ in this directory). \n", 695 | "\n", 696 | "### Also, while Jupyter usually handles most of the hard parts of Cython silently behind the scenes, it's useful to see what's needed as it needs to be done manually if you ever aren't using jupyter;\n", 697 | "\n", 698 | "---\n", 699 | "\n", 700 | "First we need to make our C/C++ files and such - that part's not Python so I'm leaving all that out. See Rectangle.h/.cpp to see the example I use here if you're interested. The main point is I make a C++ class, Rectangle, with a method, getArea(). \n", 701 | "\n", 702 | "Next we need to make a rectangle.pyx file - a cython file to act as a bridge between the C++ and Python; it reads from the header (.h) file and outlines what's there, then creates a cython version of the class (I called PyRectangle). \n", 703 | "\n", 704 | "Code:\n", 705 | "```\n", 706 | "cdef extern from \"Rectangle.h\" namespace \"shapes\":\n", 707 | " cdef cppclass Rectangle:\n", 708 | " Rectangle(int, int, int, int)\n", 709 | " int x0, y0, x1, y1\n", 710 | " int getArea()\n", 711 | "\n", 712 | "cdef class PyRectangle:\n", 713 | " cdef Rectangle *thisptr \n", 714 | " def __cinit__(self, int x0, int y0, int x1, int y1):\n", 715 | " self.thisptr = new Rectangle(x0, y0, x1, y1)\n", 716 | " def __dealloc__(self):\n", 717 | " del self.thisptr\n", 718 | " def getArea(self):\n", 719 | " return self.thisptr.getArea()\n", 720 | "```\n", 721 | "\n", 722 | "Next we need to make a setup.py script to prepare it for use in Python directly (don't actually need to import cython even to use after this script is run). The setup script essentially says \"make a new python library thing for us to use, use Cython to compile this .pyx file which needs this .cpp file, and call the new library thing 'rectangle'\"\n", 723 | "\n", 724 | "Code:\n", 725 | "\n", 726 | "```\n", 727 | "from distutils.core import setup\n", 728 | "from distutils.extension import Extension\n", 729 | "from Cython.Distutils import build_ext\n", 730 | "\n", 731 | "setup(ext_modules = [Extension(\"rectangle\", \n", 732 | " [\"rectangle.pyx\",\n", 733 | " \"Rectangle.cpp\"],\n", 734 | " language=\"c++\")],\n", 735 | " cmdclass = {'build_ext': build_ext})\n", 736 | "```\n", 737 | "\n", 738 | "Finally, all that's needed is to run the setup script and you have a useable python library - which you can import without involving cython. To run the script in the terminal, enter\n", 739 | "```\n", 740 | "$ python setup.py build_ext\n", 741 | "```\n", 742 | "\n", 743 | "In this example, I call the script in the cell below instead (using some Jupyter magic). Notice that a new 'rectangle.cpp' file is generated automatically when this script runs, with a lot more content - to handle python bindings and such.\n", 744 | "\n", 745 | "The cell below here uses this newly created library thing, note again that there is no mention of C/C++/Cython." 746 | ] 747 | }, 748 | { 749 | "cell_type": "code", 750 | "execution_count": 10, 751 | "metadata": {}, 752 | "outputs": [ 753 | { 754 | "name": "stdout", 755 | "output_type": "stream", 756 | "text": [ 757 | "/home/luke/my_work/QUB_DW_HighPerformancePython/HighPerformance/Rectangle\n", 758 | "running build_ext\n", 759 | "cythoning rectangle.pyx to rectangle.cpp\n", 760 | "building 'rectangle' extension\n", 761 | "C compiler: gcc -pthread -B /home/luke/anaconda3/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC\n", 762 | "\n", 763 | "creating build\n", 764 | "creating build/temp.linux-x86_64-3.6\n", 765 | "compile options: '-I/home/luke/anaconda3/include/python3.6m -c'\n", 766 | "gcc: rectangle.cpp\n", 767 | "cc1plus: warning: command line option ‘-Wstrict-prototypes’ is valid for C/ObjC but not for C++\n", 768 | "gcc: Rectangle.cpp\n", 769 | "cc1plus: warning: command line option ‘-Wstrict-prototypes’ is valid for C/ObjC but not for C++\n", 770 | "g++ -pthread -shared -B /home/luke/anaconda3/compiler_compat -L/home/luke/anaconda3/lib -Wl,-rpath=/home/luke/anaconda3/lib -Wl,--no-as-needed -Wl,--sysroot=/ build/temp.linux-x86_64-3.6/rectangle.o build/temp.linux-x86_64-3.6/Rectangle.o -o /home/luke/my_work/QUB_DW_HighPerformancePython/HighPerformance/Rectangle/rectangle.cpython-36m-x86_64-linux-gnu.so\n", 771 | "/home/luke/my_work/QUB_DW_HighPerformancePython/HighPerformance\n", 772 | "16\n" 773 | ] 774 | } 775 | ], 776 | "source": [ 777 | "%cd Rectangle/\n", 778 | "%run setup.py build_ext -i\n", 779 | "%cd ..\n", 780 | "\n", 781 | "# Note in the commands above that we needed to be in the same directory as the files to build them - \n", 782 | "# this is because of how we referenced their locations in the setup.py file.\n", 783 | "\n", 784 | "# Note also that to be able to import from the Rectangle/ subdirectory we had to place a '__init__.py' file\n", 785 | "# there in order to tell Python to treat that directory as a module\n", 786 | "\n", 787 | "from Rectangle.rectangle import PyRectangle\n", 788 | "r = PyRectangle(1,1,5,5) # params are corners; x0, y0, x1, y1 - so a 4x4 square in this case\n", 789 | "print(r.getArea())" 790 | ] 791 | }, 792 | { 793 | "cell_type": "markdown", 794 | "metadata": {}, 795 | "source": [ 796 | "## So that's actually all we're going to cover for Cython here, other than a bit in Example2\n", 797 | "## To use Cython more efficiently, learn some basic C/C++, especially the standard library and data types/structs.\n", 798 | "\n", 799 | "#### Short list of things Cython allows that may be useful to you (not shown here):\n", 800 | "* use different compilers\n", 801 | "* use different compiler flags\n", 802 | "* use using parallelised C/C++ code\n", 803 | "* use Cython to port Python code to C/C++\n", 804 | "* use Cython to optimise compilation for a particular architecture\n", 805 | "* profle Cython functions/methods with Cython's @cython_profile decorator \n" 806 | ] 807 | }, 808 | { 809 | "cell_type": "code", 810 | "execution_count": null, 811 | "metadata": { 812 | "collapsed": true 813 | }, 814 | "outputs": [], 815 | "source": [] 816 | } 817 | ], 818 | "metadata": { 819 | "kernelspec": { 820 | "display_name": "Python 3", 821 | "language": "python", 822 | "name": "python3" 823 | }, 824 | "language_info": { 825 | "codemirror_mode": { 826 | "name": "ipython", 827 | "version": 3 828 | }, 829 | "file_extension": ".py", 830 | "mimetype": "text/x-python", 831 | "name": "python", 832 | "nbconvert_exporter": "python", 833 | "pygments_lexer": "ipython3", 834 | "version": "3.6.7" 835 | } 836 | }, 837 | "nbformat": 4, 838 | "nbformat_minor": 2 839 | } 840 | --------------------------------------------------------------------------------