{"text": "from IPython.core.display import HTML\ndef css_styling():\n styles = open(\"./styles/custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()\n\n# Library Functions\n# Lesson Goal\n\n - To source and incorporate appropriate functions from external libraries to optimise your code. \n\n# Objectives\n\n- Introduce use of standard library functions\n- Importing and using modules\n- Understanding module documentation\n- Using imported functions to optimise the code you have written so far.\n- Determining optimal solutions by timing your code.\n\n\n\n## Libraries\n\nPython, like other modern programming languages, has an extensive *library* of built-in functions. \n\nThese functions are designed, tested and optimised by the developers of the Python langauge. \n\nWe can use these functions to make our code shorter, faster and more reliable.\n\n\nYou are already familiar with some *built in* Python functions:\n\n - `print()` takes the __input__ in the parentheses and __outputs__ a visible representation.\n - `len()` takes a data structure as __input__ in the parentheses and __outputs__ the number of items in the data structure (in one direction).\n - `sorted()` takes a data structure as __input__ in the parentheses and __outputs__ the data structure sorted by a rule determined by the data type.\n - `abs()` takes a numeric variable as __input__ in the parentheses and __outputs__ the mathematical absolute value of the input.\n\nThese functions belong to Python's standard library.\n\n## The Standard Library\n\nPython has a large standard library. \n\nIt is simply a collection of Python files called 'modules'.\n\nThese files are installed on the computer you are using.\n\nEach module contains code very much like the code that you have been writing, defining various functions. \n\nThere are multiple modules to keep the code sorted and well organised. \n\nThe standard libary contains many useful functions. \n\nThey are listed on the Python website:\nhttps://docs.python.org/3/library/functions.html\n\nIf you want to do something, for example a mathematical operation, it worth trying an internet search for a built-in function already exists.\n\n\n\nFor example, a quick google search for \"python function to sum all the numbers in a list\"...\n\n
\nhttps://www.google.co.jp/search?q=python+function+to+sum+all+the+numbers+in+a+list&rlz=1C5CHFA_enJP751JP751&oq=python+function+to+sum+&aqs=chrome.0.0j69i57j0l4.7962j0j7&sourceid=chrome&ie=UTF-8\n\n...returns the function `sum()`.\n\n`sum()` finds the sum of the values in a data strcuture. \n\n\n```python\nprint(sum([1,2,3,4,5]))\n\nprint(sum((1,2,3,4,5)))\n\na = [1,2,3,4,5]\nprint(sum(a))\n\n\n```\n\n 15\n 15\n 15\n\n\nThe function `max()` finds the maximum value in data structure.\n\n\n```python\nprint(max([4,61,12,9,2]))\n\nprint(max((3,6,9,12,15)))\n\na = [1,2,3,4,5]\nprint(max(a))\n```\n\n 61\n 15\n 5\n\n\n## Packages\n\nThe standard library tools are available in any Python environment.\n\nMore specialised libraries are available. We call these packages. \n\nPackages contain functions and constants for more specific tasks e.g. solving trigonometric functions. \n\nWe simply install the modules on the computer where we want to use them. \n\nWhen developing programs outside of learning exercises, if there is a no standard library module for a problem you are trying to solve, \nsearch online for a module before implementing your own.\n\nTwo widely used packages for mathematics, science and engineeirng are `NumPy` and `SciPy`.\n\nThese are already installed on your computers.\n\n### 1.2.1 Importing a Package\n\nTo use an installed package, we simply `import` it. \n\n\n```python\nimport numpy \n\nx = 1\n\ny = numpy.cos(x)\n\nprint(y)\n\nprint(numpy.pi)\n```\n\n 0.540302305868\n 3.141592653589793\n\n\nThe `import` statement must appear before the use of the package in the code. \n\n import numpy \n\nAfter this, any function in `numpy` can be called as:\n\n `numpy.function()`\n \nand, any constant in `numpy` can be called as:\n\n `numpy.constant`.\n\nThere are a many mathematical functions available.
\nhttps://docs.scipy.org/doc/numpy-1.13.0/reference/routines.math.html\n\n## Reading function documentation\n\nTo check how to use a function e.g.:\n - what arguments to include in the () parentheses\n - allowable data types to use as arguments\n - the order in which arguments should be given \n \nsearch for the documentation online.\n\nhttps://docs.scipy.org/doc/numpy-1.13.0/reference/routines.math.html\n\nFor example, the documentation for the function numpy.cos https://docs.scipy.org/doc/numpy-1.13.0/reference/routines.math.html includes:\n \n>numpy.cos(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) \n \n> Cosine element-wise.\n\n>x : array_like\n>
Input array in radians.\n\nThis tells us:\n - What the function does. \n - how to call the function: \n - we must set one function argument, x\n - there are several default arguments (where, casting etc) that we can optionally set.\n - x should be \"arraylike\" (it can be an `int`, `float`, `list` or `tuple`)\n - x is the input to the cosine function, in radians\n\nWe can change the name of a package e.g. to keep our code short and neat.\n\nUsing the __`as`__ keyword:\n\n\n```python\nimport numpy as np\n\nx = 1\n\ny = np.cos(x)\n\nprint(y)\n```\n\n 0.540302305868\n\n\n## Namespaces\n
By prefixing `cos` with `np`, we are using a *namespace* (which in this case is `np`).\n\nThe namespace shows we want to use the `cos` function from the Numpy package.\n\nIf `cos` appears in more than one package we import, then there will be more than one `cos` function available.\n\nWe must make it clear which `cos` we want to use. \n\nOften, functions with the same name, from different packages, will use a different algorithms for performing the same or similar operation. \n\nThey may vary in speed and accuracy. \n\nIn some applications we might need an accurate method for computing the square root, for example, and the speed of the program may not be important. For other applications we might need speed with an allowable compromise on accuracy.\n\ne.g. Below are two functions, both named `sqrt`. \n\nBoth functions compute the square root of the input.\n\n - `math.sqrt`, from the package, `math`, gives an error if the input is a negative number. It does not support complex numbers.\n - `cmath.sqrt`, from the package, `cmath`, supports complex numbers.\n\n\n\n```python\nimport math\nimport cmath\n\nprint(math.sqrt(4))\n#print(math.sqrt-5)\n#print(cmath.sqrt(-5))\n\n# if we use a function name with more than one definition we get a clash\n#print(sqrt(-5))\n```\n\n 2.0\n\n\nAs anther example, two developers collaborating on the same program might choose the same name for two functions that perform similar but slightly different tasks. If these functions are in different modules, there will be no name clash since the module name provides a 'namespace'. \n\n## Importing a Function\nSingle functions can be imported without importing the entire package e.g. use:\n\n from numpy import cos\n\ninstead of:\n\n import numpy \n\nAfter this you call the function without the numpy prefix: \n\n\n```python\nfrom numpy import cos\n\ncos(x)\n```\n\n\n\n\n 0.54030230586813977\n\n\nBe careful when doing this as there can be only one definition of each function.\nIn the case that a function name is already defined, it will be overwritten by a more recent definietion. \n\n```python\nfrom cmath import sqrt\nfrom math import sqrt\n\n#sqrt(-1)\n```\n\n\n\n\n 1j\n\n\n\nWe can even rename individual functions or constants when we import them:\n\n\n```python\nfrom numpy import cos as cosine\n\ncosine(x)\n```\n\n\n\n\n 0.54030230586813977\n\n\n\n\n```python\nfrom numpy import pi as pi\npi\n```\n\n\n\n\n 3.141592653589793\n\n\n\nThis can be useful when importing functions from different modules:\n\n\n```python\nfrom math import sqrt as square_root\nfrom cmath import sqrt as complex_square_root\n\nprint(square_root(4))\nprint(complex_square_root(-1))\n```\n\n 2.0\n 1j\n\n\nFunction names should be chosen wisely.\n - relevant\n - concise\n\n\n## Using Package Functions. \n\nLet's learn to use `numpy` functions in our programs. \n\nTo check how to use a function e.g.:\n - what arguments to include in the () parentheses\n - allowable data types to use as arguments\n - the order in which arguments should be given \n \nlook at the Numpy documentation.\n\nA google search for 'numpy functions' returns:\n\nhttps://docs.scipy.org/doc/numpy-1.13.0/reference/routines.math.html\n\n(this list is not exhaustive). \n\n\n```python\n# Some Numpy functions with their definitions as given in the documentation\n\nx = 1\ny = 2\nz = 3\n\n# Trigonometric sine, element-wise.\nprint(np.sin(x))\n\n# Compute tangent element-wise.\nprint(np.tan(x))\n\n# Trigonometric inverse tangent\nprint(np.arctan(x))\n\n# Convert angles from radians to degrees\ndegrees = np.degrees(x)\nprint(degrees)\n\n# Convert angles from degrees to radians\nradians = np.radians(degrees)\nprint(radians) \n```\n\n 0.841470984808\n 1.55740772465\n 0.785398163397\n 57.2957795131\n 1.0\n\n\n__Try it yourself:__\n
Find a function in the Python Numpy documentation that matches the function definition and use it to solve the following problem: \n\nGiven the “legs” of a right triangle, return its hypotenuse.
If the lengths of the two shorter sides of a right angle triangle are 6 units and 3 units, what is the length of the hypotenuse?\n\n\n```python\n# The “legs” of a right triangle are are 6 units and 3 units, \n# Return its hypotenuse in units.\n\n```\n\n 6.7082039325\n\n\nNumpy functions often appear within user defined functions e.g.:\n\n$f(x)= \\cos(x) \\qquad x <0$\n\n$f(x) = \\exp(-x) \\qquad x \\ge 0$\n\n\n```python\ndef f(x):\n if x < 0:\n f = np.cos(x)\n else:\n f = np.exp(-x)\n return f\n\nprint(f(np.pi))\nprint(f(np.pi/6))\n```\n\n 0.0432139182638\n 0.592384847188\n\n\nPackage functions can be passed to other functions as arguments.\n\nRecall __Seminar 4, What can be passed as a function argument?__\n\n\nExample: the function `is_positive` checks if the value of a function $f$, evaluated at $x$, is positive.\n
The arguments are:\n - the function $f$\n - the value of $x$,in $f(x)$\n\n\n```python\ndef is_positive(f, x):\n\n if f(x) > 0:\n return True\n else:\n return False\n \ndef f0(x):\n \"\"\"\n Computes x^2 - 1\n \"\"\"\n return x*x - 1\n \n# Value of x to test\nx = 0.5\n\n# Test sign of function f0 (user defined)\nprint(is_positive(f0, x))\n\n# Test sign of function np.cos (numpy function)\nprint(is_positive(np.cos, x))\n```\n\n False\n True\n\n\n__Try it yourself:__\n
Search online for the numpy function for each of the following mathematical functions: \n- $f = arcsin(x)$\n- $f = \\sqrt x$ \n\n
In the cell below use the function `is_positive` to test the sign of output of the functions. \n\n\n```python\n# Test sign of numpy function for arcsin(x)\n\n\n# Test sign of numpy function for square root of x\n\n```\n\n True\n True\n [ 0.87758256]\n\n\n##### Try it yourself\nIn the cell below, copy and paste the `bisection` function you wrote for __Seminar 4: Review Excercise: Using Functions as Function Arguments.__\n\nDemonstrate that your `bisection` function works correctly by finding the zero of the Numpy cos($x$) function that lies in the interval $x_1=0$ to $x_2=3$. \n\n\n```python\n# Bisection\n\n\n```\n\n 0.0707372016677\n -0.628173622723\n -0.29953350619\n -0.116438941125\n -0.0229516576536\n 0.0239190454439\n 0.00048382677602\n -0.0112346868547\n -0.00537552231604\n -0.00244585826649\n -0.000981016797749\n -0.000248595077543\n 0.000117615857125\n -6.54896113066e-05\n 2.60631230187e-05\n -1.97132441646e-05\n 3.17493942786e-06\n root = 1.5707931518554688\n\n\n## Using Package Functions to Optimise your Code\nThe examples in this section will take previous excercises that you have completed either in class or for homework and look at how we can optimise them using Numpy functions.\n
If you have not completed the excercises mentiond in previous seminars you can *optionally* complete the exercise without Numpy functions before optimising. \n\nRefer to your answer to __Seminar 4: Return Arguments__. \n\nThe function `compute_max_min_mean`:\n\n\n\n```python\ndef compute_max_min_mean(x0, x1, x2):\n \"Return maximum, minimum and mean values\"\n \n x_min = x0\n if x1 < x_min:\n x_min = x1\n if x2 < x_min:\n x_min = x2\n\n x_max = x0\n if x1 > x_max:\n x_max = x1\n if x2 > x_max:\n x_max = x2\n\n x_mean = (x0 + x1 + x2)/3 \n \n return x_min, x_max, x_mean\n\n\nxmin, xmax, xmean = compute_max_min_mean(0.5, 0.1, -20)\nprint(xmin, xmax, xmean)\n```\n\n -20 0.5 -6.466666666666666\n\n\nCould be re-written as:\n\n\n```python\ndef np_compute_max_min_mean(x0, x1, x2):\n \"Return maximum, minimum and mean values\"\n \n x_min = np.amin([x0, x1, x2])\n x_max = np.amax([x0, x1, x2])\n x_mean = np.mean([x0, x1, x2])\n \n return x_min, x_max, x_mean\n\n\nxmin, xmax, xmean = np_compute_max_min_mean(0.5, 0.1, -20)\nprint(xmin, xmax, xmean)\n```\n\n -20.0 0.5 -6.46666666667\n\n\n### Data Structures as Function Arguments. \nNotice that the Numpy functions `amin`, `amax` and `amean` take lists as argumets.\n\nWe could simplify further by giving a single list as the argument to the function. \n\nThis way, we can give any number of values and the function will return the aximum, minimum and mean values.\n\n(There are alternative ways of doing this that we will study later in the course).\n\n\n```python\nimport numpy as np\ndef np_compute_max_min_mean(x_list):\n \"Return maximum, minimum and mean values\"\n \n x_min = np.amin(x_list)\n x_max = np.amax(x_list)\n x_mean = np.mean(x_list)\n \n return x_min, x_max, x_mean\n\n\nxmin, xmax, xmean = np_compute_max_min_mean([0.5, 0.1, -20])\nprint(xmin, xmax, xmean)\n\n\nprint(np_compute_max_min_mean([-2, -1, 3, 5, 12]))\n\n\nxmin, xmax, xmean = np_compute_max_min_mean([3, 4])\nprint(xmin, xmax, xmean)\n```\n\n -20.0 0.5 -6.46666666667\n (-2, 12, 3.3999999999999999)\n 3 4 3.5\n\n\n\n### Elementwise Functions\nNumpy functions often operate *elementwise*. \n
This means if the argument is a list, they will perform the same function on each element of the list.\n\nFor example, to find the square root of each number in a list, we can use:\n\n\n```python\na = [9, 25, 36]\nprint(np.sqrt(a))\n```\n\n\n### Magic Functions\nWe can use *magic function* (http://ipython.readthedocs.io/en/stable/interactive/magics.html), `%timeit`, to compare the time the user-defiend function takes to execute compared to the Numpy function. \n\nSometimes we must choose between minimising the length of the code and minimising the time it takes to run. \n\nSimply put `%timeit` before the function call to print the execution time. \n
e.g. `%timeit cos(x)` \n\n\n```python\n%timeit compute_max_min_mean(0.5, 0.1, -20)\nprint(\"\")\n%timeit np_compute_max_min_mean(0.5, 0.1, -20)\n```\n\n The slowest run took 10.69 times longer than the fastest. This could mean that an intermediate result is being cached.\n 1000000 loops, best of 3: 369 ns per loop\n \n The slowest run took 87.57 times longer than the fastest. This could mean that an intermediate result is being cached.\n 10000 loops, best of 3: 21.1 µs per loop\n\n\n##### Try it yourself \nIn the cell below, find a Numpy function that provides the same solution as the function your write as your answer to __Seminar 3, Review Exercise: Indexing, part (A)__: \n
Add two vectors, $\\mathbf{A}$ and $\\mathbf{B}$ such that:\n$ \\mathbf{A} + \\mathbf{B} = [(A_1 + B_1), \n (A_2 + B_2),\n ...\n (A_n + B_n)]$\n\n__(A)__ Use the Numpy function to add vectors:\n\n$\\mathbf{A} = [-2, 1, 3]$\n\n$\\mathbf{B} = [6, 2, 2]$\n\nCheck that your answer is the same as your answer to __Seminar 3, Review Exercise: Indexing__.\n\n__(B)__ Using your answer to __Seminar 3, Review Exercise: Indexing__ write a function `vector_add` that takes vectors A and B as inputs and returns the sum of the two vectors by calling:\n\n```python\nvector_add(A, B)\n```\n\n__(C)__ Use *magic function* `%timeit`, to compare the spped of the Numpy function to the user defined function `vector_add`. \n
Which is fastest?\n\n\n```python\n# Function to sum two vectors\n\n\n```\n\n\n## Importing Algorithms as Functions (e.g. Root finding)\n\nSo far we have mostly looked at library functions that perform single mathematical operations such as trigonomtric or algebraic functions. \n\nLibrary functions also include those that can be used for complete multi-stage tasks.\n\nFor example, in place of the `bisection` function you wrote to find the root of a function, a number of root-finding functions from imported modules can be used. \n\nThe package `scipy.optimize` contains a number of functions for estimating the roots of a function including:\n - `scipy.optimize.bisect`\n - `scipy.optimize.fsolve` (the most popular root-finding function)\n\nThe documentation for `fsolve` https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.optimize.fsolve.html:\n\n>scipy.optimize.fsolve(func, x0, args=(), fprime=None, full_output=0, col_deriv=0, xtol=1.49012e-08, maxfev=0, band=None, epsfcn=None, factor=100, diag=None)[source]\n\n>Return the roots of the (non-linear) equations defined by func(x) = 0 given a starting estimate.\n\n>__func__ : callable f(x, *args)\n
      A function that takes at least one (possibly vector) argument.\n
__x0__ : ndarray\n
      The starting estimate for the roots of func(x) = 0.\n\n__Bisection method:__ the user selects the interval in which to look for the root. \n\n__`solve` method:__ the user selects an __initial estimate__ for the root.\n\n\nTo demonstrate, here is an example:\n \nThe function, $f(x) = x^3 + 4x^2 + x - 6$ has roots -3, -2, and 1. \n\nThe function should return the root that is closest to our estimate. \n\n\n```python\nimport scipy\nfrom scipy.optimize import fsolve\n\ndef func(x):\n return x**3 + 4*x**2 + x - 6\n\na = scipy.optimize.fsolve(func, -30)\n\nprint(a)\n```\n\n [-3.]\n\n\n__Try it yourself:__\n
In the cell below, use `scipy.optimize.fsolve()` to print the root of cos(x) (using `np.cos()`).\n
Try several initial guess values of x. \n\n\n```python\n# Find the root of cos(x)\n```\n\n [-17.27875959]\n\n\nSometimes, we want to find more than one root of a function. \n\n - For the function $cos(x)$, finding all roots is impractical as our solution would be infinite.\n
\n\n - For functions like the polynomial $f(x) = x^3 + 4x^2 + x - 6$ we can use the function `np.roots()` to find all roots.\n
The function argument is the coeffients of the polynomial as a list.\n\n\n```python\nprint(np.roots([1, 4, 1, -6]))\n```\n\n [-3. -2. 1.]\n\n\n__Try it yourself:__\n
In the cell below use `numpy.roots()` to find the roots of the function:\n
$y = x^3 - 2x^2 - 11x + 12$\n\n\n```python\nprint(np.roots([1, -2, -11, 12]))\n```\n\n [-3. 4. 1.]\n\n\n## Review Exercises\nThe following excercises will help you to practise finding useful functions form external packages and applying them when solving engineering problems. \n\n### Review Exercise: Numpy Package Functions. \n
Find a function in the Python Numpy documentation that matches the function definition and use it to solve the problems below:\n\n__(A)__ Calculate the exponential of all elements in the input array.\n
Print a list where each element is the exponential of the corresponding element in list a:\n
`a = [0.1, 0, 10]`\n\n\n```python\n# Print a list where each element is the exponential of the corresponding element in list a\n```\n\n__(B)__ Convert angles from degrees to radians..\n
Convert angle `theta`, expressed in degrees, to radians:\n
`theta` = 47\n\n\n```python\n# convert angle `theta`, expressed in degrees, to radians\n```\n\n### Review Exercise: Searching for Appropriate Package Functions \n
\nRefer to your answer to __Seminar 4, Review Exercise: Default Arguments.__\nCopy and paste your code in the cell below.\n\n__(A)__ *Elementwise functions* perform an operation on each element of a data structure.\n
Within the function create a list to store the values x, y and z:\n```python\ndef magnitude(x, y, z = 0):\n \"\"\"\n Returns the magnitude of a 2D or 3D vector\n \"\"\"\n vector = [x, y, z]\n```\n\n Within your function, replace the operation for square (raise to power of 2) $^2$ with an elementwise numpy function that takes the list `vector` as an argument. \n \n Jump to Elementwise Functions\n\n__(B)__ Find an Numpy functions to the replace operation for:\n\n - summation $\\sum$\n - square root $\\sqrt x$\nand include these in your function. \n\n__(C)__ Use *magic function* `%timeit`, to compare the speed of your user-defined function (from Seminar 4) to the speed when using Numpy functions.\n
Which is fastest?\n\n Jump to Magic Functions\n\n__(D)__ Search online for a single numpy function that takes a vector as input and returns the magnitide of a vector. \n
Use it calculate the magnitude of the vector $x$. \n
Check the answer against the value generated in __A__\n
Check your answers using hand calculations.\n\n__(E)__ Use *magic function* `%timeit`, to compare the time for:\n - the Numpy function to return the magnitude\n - the function you used in parts __(A)-(C)__ \nfor 2D and 3D vectors. \n\n\n```python\n# Searching for Appropriate Package Functions \n```\n\n### Review Exercise: Using Package Functions to Optimise your Code\n\nSearch for a Numpy function that has a __similar__ function to the `is_positive` function from Section: Using Package Functions; the answer it returns should show if an input value is positive or not. \n\nIn the cell below:\n - copy and paste the `is_positive` function\n - use the magic function %timeit to compare the speed of the `is_positive` function with the Numpy function for analysing the sign of a numerical input.\n\nJump to function:`is_positive` \n\n\n\n\n```python\n\n```\n\n### Review Exercise: Alternative Expressions\nRecall __Seminar 3, Indexing__. \n\nWe saw that the __dot product__ of two vectors can be experssed both geometrically and algebraically. \n\n__GEOMETRIC REPRESENTATION__\n\n\\begin{align}\n\\mathbf{A} \\cdot \\mathbf{B} = |\\mathbf{A}| |\\mathbf{B}| cos(\\theta)\n\\end{align}\n\n__ALGEBRAIC REPRESENTATION__\n\n>So the dot product of two 3D vectors:\n>
$ \\mathbf{A} = [A_x, A_y, A_z]$\n>
$ \\mathbf{B} = [B_x, B_y, B_z]$\n>
is:\n\n\\begin{align}\n\\mathbf{A} \\cdot \\mathbf{B} &= \\sum_{i=1}^n A_i B_i \\\\\n&= A_x B_x + A_y B_y + A_z B_z.\n\\end{align}\n\n\n\nIn the cell titled \" `The dot product of C and D `\", you wrote a program to compute the dot product using:\n - a for loop\n - indexing \n\n$\\mathbf{C} = [2, 4, 3.5]$\n\n$\\mathbf{D} = [1, 2, -6]$\n\n\nIn the cell below, use:\n - the Numpy cosine function\n - the magnitude function that you used in the last example (either user defined or Numpy function)\n \nto compute $\\mathbf{C} \\cdot \\mathbf{D}$ using the geomtric expression.\n\nCheck your answer is the same as your answer from Seminar 3. \n\n\n\n### Review Exercise: Importing Algorithms as Functions\n\nIn Importing Algorithms as Functions (e.g. Root finding) we learnt that the package scipy.optimize contains a number of functions for estimating the roots of a function, including `scipy.optimize.bisect`.\n\nThis function performs the same/ a similar function to the `bisection` function that you have been developing. \n\n__(A)__ Find the documentation for the function `scipy.optimize.bisect` to learn how to use it.\n\n__(B)__ Use `scipy.optimize.bisect` to estimate the root of the function $f(x) = 2sin^2 x - 3sin x + 1$:\n
      (i) between 0 and $\\frac{\\pi}{6}$\n
      (ii) between 1.5 and 2\n
      (iii) between $\\frac{3}{4}\\pi$ and $\\pi$\n\n__NOTE:__   $sin^2(x) = (sin(x))^2$\n\n__(C)__ Use the magic function %timeit to compare the speed of your user-sefined function `bisection`, with the speed of `scipy.optimize.bisect`. \n\n\n```python\n\n```\n\n# Summary\n\n- Python has an extensive __standard library__ of built-in functions. \n- More specialised libraries of functions and constants are available. We call these __packages__. \n- Packages are imported using the keyword ....\n- The function documentation tells is what it does and how to use it.\n- When calling a library function it must be prefixed with a __namespace__ is used to show from which package it should be called. \n- The magic function .... can be used to time the execution of a function. \n\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "5252f4a71d5f742e0290397abeb21258dc305028", "size": 45789, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "5_Library_Functions.ipynb", "max_stars_repo_name": "hphilamore/ILAS_python_", "max_stars_repo_head_hexsha": "f17b4f0aeaf0f8daeb943bcdb5544716c0a5b3f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "5_Library_Functions.ipynb", "max_issues_repo_name": "hphilamore/ILAS_python_", "max_issues_repo_head_hexsha": "f17b4f0aeaf0f8daeb943bcdb5544716c0a5b3f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "5_Library_Functions.ipynb", "max_forks_repo_name": "hphilamore/ILAS_python_", "max_forks_repo_head_hexsha": "f17b4f0aeaf0f8daeb943bcdb5544716c0a5b3f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4853528628, "max_line_length": 1642, "alphanum_fraction": 0.5673633405, "converted": true, "num_tokens": 6650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. YES", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.24759329033606817}} {"text": "# Droplet Bounce Parameter Estimation\n## Import experimental data\n\n\n```python\nimport os, fnmatch, csv\nimport numpy as np\n\nclass Experiment(object):\n def __init__(self, data, name, start=0, end=-1, volume=1, surfaceV='[1000]', frame_rate=29.95, \n outlier=False, time=1, debias=1, layers=4, guess=0.72*2.3):\n self.data = data\n self.name = name\n self.start = start\n self.end = end\n self.volume = volume\n self.surfaceV = surfaceV #sum(surfaceV)/len(surfaceV)\n self.frame_rate = frame_rate\n self.outlier = outlier\n #self.charge = charge\n #self.u0 = u0\n self.time = time\n self.debias = debias\n self.layers = layers\n self.guess = guess\n\ndef print_header(drop):\n \"\"\"\n Prints the drop name and measured experimental parameters.\n \"\"\"\n print('name', drop.name)\n print('volume', drop.volume, 'mL')\n print('surfaceV', drop.surfaceV, 'V')\n \ndef import_data(exp_class):\n \"\"\"\n Takes an experiment type and returns an array of Experiment class objects, with attributes specified by\n a metadata csv. The 'data' attribute The column heads include:\n 'R','Area','XM','YM','Major','Minor','Angle','Circ','Slice','AR','Round','Solidity'\n \"\"\"\n meta_file_location = '../data/' + exp_class + '/meta.csv'\n imported_datatype = ('U9', int, int, float, object, float, bool, float, float, int, int, float)\n metadata = np.genfromtxt(meta_file_location, delimiter=';', dtype=imported_datatype, names=True)\n for keys, vals in np.ndenumerate(metadata['surfaceV']):\n metadata['surfaceV'][keys] = np.fromstring(vals, dtype=float, sep=',')\n globals()[exp_class + '_data_list'] = np.array([])\n for drop in metadata:\n name = 'drop' + str(drop['name'])\n path = '../data/' + exp_class + '/' + str(drop['name']) + '.csv'\n data = np.genfromtxt(path, dtype=float, delimiter=',', names=True)\n print(path[-8:])\n start = drop['start']\n end = drop['end']\n volume = drop['volume']\n surfaceV = drop['surfaceV']\n frame_rate = drop['frame_rate']\n outlier = drop['outlier']\n time = drop['time']\n debias = drop['debias']\n layers = drop['layers']\n guess = drop['guess']\n first_frame = drop['first_frame']\n data = data[first_frame:-1]\n data['Slice'] -= first_frame\n data['Minor'] = data['Minor']/2\n data['Major'] = data['Major']/2\n \n # check for gaps\n if (data.shape[0]) < data['Slice'][-1]:\n print('there is {} cells of gap'.format(int((data['Slice'][-1] - data.shape[0]))))\n globals()[str(name)] = Experiment(data, name, start, end, volume, surfaceV,\n frame_rate, outlier, time, debias, layers, guess)\n globals()[exp_class + '_data_list'] = np.append(globals()[exp_class + '_data_list'], \n globals()[str(name)])\n print('done!')\n```\n\n\n```python\nexp_class = 'dielectric_improved'\nimport_data(exp_class)\n\n# use fancy indexing to make a list of outliers\nmask = [datas.outlier==False for datas in globals()[exp_class + '_data_list']]\noutliers = {datas.name:datas for datas in globals()[exp_class + '_data_list'][mask]}\nalldrops = {datas.name:datas for datas in globals()[exp_class + '_data_list']}\nalldrops = outliers\n```\n\n 7294.csv\n there is 2 cells of gap\n 7295.csv\n there is 1 cells of gap\n 7296.csv\n 7297.csv\n 7298.csv\n 7299.csv\n 7300.csv\n 7301.csv\n 7319.csv\n 7325.csv\n 7326.csv\n 7327.csv\n 7328.csv\n 7329.csv\n 7334.csv\n 7335.csv\n 7336.csv\n done!\n\n\n## Filtering\n\n\n```python\nfrom scipy import signal\n\ndef sg_filter(y, dt):\n \"\"\"\n Takes raw data and returns a filtered array of the same length. \n The function avoids IndexErrors by a simple rule for setting the window size.\n \"\"\"\n #try:\n if y.shape[0]>25:\n window = 25\n else:\n window = y.shape[0]\n if window % 2 ==0:\n window-=3\n return derivs(y, window, dt)\n #except ValueError:\n # print('debug: Window size', window)\n \ndef derivs(y, window, dt):\n \"\"\"\n Returns Savitsky-Golay filtered array of a variable and its derivatives by finite differences.\n \"\"\"\n dtdt=dt*dt\n y_savgol = signal.savgol_filter(y, window, 3, deriv=0, axis=0)\n y_savgol1 = signal.savgol_filter(y_savgol, window, 3, deriv=0, axis=0)\n y_savgol2 = signal.savgol_filter(y_savgol1, window, 3, deriv=0, axis=0)\n y_savgol3 = signal.savgol_filter(y_savgol2, window, 3, deriv=0, axis=0)\n dy_savgol = signal.savgol_filter(y_savgol3, window, 3, deriv=1, axis=0)/dt\n ddy_savgol = signal.savgol_filter(y_savgol3, window, 3, deriv=2, axis=0)/dtdt\n return y_savgol3, dy_savgol, ddy_savgol\n```\n\n## Trajectory Plots\n\n\n```python\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib import rc\nimport pylab\nfrom mpl_toolkits.axes_grid1 import host_subplot\nimport mpl_toolkits.axisartist as AA\nfrom matplotlib.collections import LineCollection\nfrom matplotlib.colors import ListedColormap, BoundaryNorm\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\nfrom matplotlib.colors import Normalize\n\n#matplotlib.use('pgf')\n#%matplotlib inline\n#matplotlib.rcParams['figure.figsize'] = (10,10)\n\npgf_with_latex = { # setup matplotlib to use latex for output\n \"pgf.texsystem\": \"pdflatex\", # change this if using xetex or lautex\n \"text.usetex\": True, # use LaTeX to write all text\n \"font.family\": \"serif\",\n \"font.serif\": ['Computer Modern Roman'], # blank entries should cause plots to inherit fonts from the document\n \"font.sans-serif\": ['Computer Modern Sans serif'],\n \"font.monospace\": ['Computer Modern Typewriter'],\n \"axes.labelsize\": 12, # LaTeX default is 10pt font.\n \"font.size\": 12,\n \"legend.fontsize\": 10, # Make the legend/label fonts a little smaller\n \"xtick.labelsize\": 12,\n \"ytick.labelsize\": 12,\n \"pgf.preamble\": [\n r\"\\usepackage[utf8x]{inputenc}\", # use utf8 fonts becasue your computer can handle it :)\n r\"\\usepackage[T1]{fontenc}\", # plots will be generated using this preamble\n ]\n }\n\n#%config InlineBackend.figure_formats = ['svg']\n#matplotlib.rcParams['text.latex.unicode'] = True\n#matplotlib.rcParams.update(pgf_with_latex)\nmatplotlib.rcParams.update(\n{\n 'xtick.color': 'k',\n 'ytick.color': 'k',\n 'axes.labelcolor': 'k'\n})\n\nplt.rc('text', usetex=True)\nplt.rc('font', family='serif')\n#plt.rc('legend', frameon=False)\n\nplt.rcParams['figure.dpi'] = 100\nplt.rc('font', size=16)\n%config InlineBackend.figure_format = 'retina'\npics = False\n```\n\n\n```python\ndef savefig(filename, pics):\n if pics == True:\n plt.savefig('../doc/figures/{}.eps'.format(filename), bbox_inches='tight')\n else:\n pass\n```\n\n\n```python\ndef plot_single(drop, args_for_components=['YM'], kwargs_for_plot={'color':'k'}, **kwargs):\n \"\"\"\n Plots a given variable over the trajectory of a single drop.\n \"\"\"\n #plt.xlabel('t ($s$)')\n (ym, t, dt, contact_mask, y_parted, \n dy_parted, ddy_parted, t_parted, ind_parted) = get_data(drop, param_est=False)\n component = {'y_parted': y_parted, 'dy_parted':dy_parted, 'ddy_parted':ddy_parted}\n if 'parted' in kwargs.keys() and kwargs['parted']==True:\n if 'sub' in kwargs.keys():\n i = kwargs['i']\n fig = kwargs['fig']\n axs = kwargs['axs']\n axs[i].plot(t_parted, component[kwargs['variable']], 'ko', \n markersize=6, markerfacecolor='white', markeredgecolor='black', label='data')\n axs[i].plot(t_parted[ind_parted.flatten()], component[kwargs['variable']][ind_parted.flatten()], 'o')\n #axs[i].ylabel(kwargs['variable'])\n #axs[i].legend(title=drop.name)\n else:\n plt.plot(t_parted, component[kwargs['variable']], 'ko',\n markersize=6, markerfacecolor='white', markeredgecolor='black')\n plt.plot(t_parted[ind_parted.flatten()], component[kwargs['variable']][ind_parted.flatten()], 'o')\n #plt.ylabel(kwargs['variable'])\n else:\n try:\n a = drop.start + kwargs['start']\n except KeyError:\n a = drop.start\n b = -drop.end\n t = drop.data['Slice'][a:b]/drop.frame_rate\n for component in args_for_components:\n y = drop.data[component][a:b]\n if 'n' in kwargs.keys():\n minm = signal.argrelextrema(y, np.less, order=4)[0][::]\n minm = np.append([0],minm)\n minm = np.append(minm, [len(y)-1])\n maxm = signal.argrelextrema(y, np.greater, order=4)[0][::]\n n=kwargs['n']\n if n == 'all':\n plt.plot(t, y, label=drop.name, **kwargs_for_plot)\n plt.plot(t[minm],y[minm],'o')\n plt.plot(t[maxm],y[maxm],'o')\n plt.ylabel(component)\n else:\n plt.plot(t[minm[n]:minm[n+1]+1], y[minm[n]:minm[n+1]+1], label=drop.name, **kwargs_for_plot)\n plt.plot(t[minm][n:n+2],y[minm][n:n+2],'o')\n plt.plot(t[maxm][n],y[maxm][n],'+')\n plt.ylabel(component)\n elif 'c' in kwargs_for_plot.keys():\n plt.plot(t,y, **kwargs_for_plot)\n elif 'points' in kwargs.keys():\n plt.plot(t,y,'k-')\n elif 'qm' in kwargs.keys() and kwargs['qm']==True:\n eu, t0, y0, im = kwargs['qmvals']\n if 'dimless' in kwargs.keys() and kwargs['dimless']==True:\n y, t = y_parted, t_parted\n try:\n y00 = y/y0\n minm = signal.argrelextrema(y, np.less, order=2)[0][::]\n minmm = minm[0]\n #plt.plot(t/t0, y00-np.abs(y00[minmm]),#radius(volume=drop.result.x[1])/y0, \n # label=drop.name, **kwargs_for_plot)\n \n #plt.plot(t/t0, (y-np.abs(y[minmm]) - radius(volume=drop.result.x[1]))/y0,#radius(volume=drop.result.x[1])/y0, \n # label=drop.name, **kwargs_for_plot)\n plt.plot(t/t0, (y-radius(volume=drop.result.x[1]))/y0\n , label=drop.name, **kwargs_for_plot)\n #plt.scatter(t[minm], y[minm]-radius(volume=drop.result.x[1]) - y[minmm], **kwargs_for_plot)\n except IndexError:\n print('uh oh')\n try:\n minm = signal.argrelextrema(y, np.less, order=2)[0][::]\n minmm = minm[0]\n plt.plot(t/t0, (y-radius(volume=drop.result.x[1]))/y0\n , label=drop.name, **kwargs_for_plot)\n #plt.scatter(t[minm], y[minm]-radius(volume=drop.result.x[1]) - y[minmm], **kwargs_for_plot)\n except IndexError:\n pass\n else:\n plt.plot(t, y,label=drop.name, **kwargs_for_plot)\n else:\n plt.plot(t, y,label=drop.name, **kwargs_for_plot)\n #return t[-1]\n if 'single' in kwargs.keys() and kwargs['single']==True:\n plt.show()\n else:\n pass\n\ndef plot_series(dataset, component='YM', **kwargs):\n \"\"\"\n Plots a given variable over the trajectories of a series of drops.\n \"\"\"\n if 'qm' in kwargs.keys() and kwargs['qm']==True:\n if 'reg' in kwargs.keys():\n if kwargs['reg'] == 'l':\n n=1\n m=1\n elif kwargs['reg'] == 'll':\n n=2\n m=1\n elif kwargs['reg'] == 'm':\n n=4\n m=2\n else:\n n=0\n m=0\n else:\n n = 0\n m = 0\n qs = np.array([])\n ts = np.array([])\n ys = np.array([])\n im = np.array([])\n #for drops in dataset.keys():\n for keys, vals in enumerate(dataset.items()):\n drop = vals[1]\n qs = np.append(qs, q_to_m(drop)[m])\n im = np.append(im, img(drop))\n ys = np.append(ys, yc(drop)[m])\n ts = np.append(ts, tc(drop)[n])\n norm = matplotlib.colors.LogNorm(vmin=(qs).min(), vmax=(qs).max())\n color = plt.get_cmap(kwargs['col'])\n my_map = cm.ScalarMappable(norm=norm, cmap=kwargs['col'])\n fig = plt.figure()\n for keys, vals in enumerate(dataset.items()):\n color = my_map.to_rgba(qs[keys])\n drop = vals[1]\n plot_single(drop, [component], kwargs_for_plot={'color':color}, \n qmvals=(qs[keys], ts[keys], ys[keys], im[keys]), **kwargs)\n my_map.set_array([])\n cb1 = plt.colorbar(my_map)\n cb1.set_label(r'${\\mathbf{E} \\mbox{u}}$', size=14, labelpad=8, rotation=0)\n plt.ylabel(kwargs['label'][1])\n plt.xlabel(kwargs['label'][0])\n if 'dimless' in kwargs.keys() and kwargs['dimless']==True:\n if 'reg' in kwargs.keys() and (kwargs['reg']=='s'):# or kwargs['reg']=='m'):\n tn = get_data(drop, param_est=True)[0][-1]\n plt.xlim(xmin=0, xmax = 4)\n #plt.ylim(ymin=0, ymax=2)\n else:\n total_time=[]\n vols = []\n for keys, vals in enumerate(dataset.items()):\n drop = vals[1]\n vols = np.append(vols, drop.volume)\n norm = matplotlib.colors.Normalize(vmin=0, vmax=len(vols))\n color = plt.get_cmap(kwargs['col'])\n my_map = cm.ScalarMappable(norm=norm, cmap=kwargs['col'])\n fig = plt.figure()\n for keys, vals in enumerate(dataset.items()):\n color = my_map.to_rgba(keys)\n drop = vals[1]\n tf = plot_single(drop, [component], kwargs_for_plot={'color':color}) #\n if drop.name in ['drop07298','drop07299','drop07297','drop07300']:\n total_time.append(tf)\n plt.legend(loc = 'upper right')\n plt.ylabel(component)\n plt.xlabel(r'$t$ (s)')\n\n #plt.xlim((0.1,2.2))\n if 'savefig' in kwargs.keys() and kwargs['savefig']==True:\n name = kwargs['name']\n savefig(name, pics)\n plt.show()\n```\n\n\n```python\nn = -4\nm = -1\nsorted_vals = [alldrops[x] for x in sorted_keys[:n]]\nsorted_drops = dict(zip(sorted_keys, sorted_vals))\nplot_series(sorted_drops, component='YM', qm=True, label=[r'$t^*$', r'$y^*$'], \n savefig=True, reg = 's', dimless = True, name='series_s_ds', col=col)\n```\n\n\n```python\n\"\"\"\nUse n=1,2,3 etc (where n may be 0 or any positive integer) to look at an individual bounce.\nOtherwise use n='all' to see all bounces.\n\"\"\"\n\ndrop = drop07336\n#drop.start=10\n#print(len(get_data(drop, param_est=False)[1]), get_data(drop, param_est=False)[1][0], drop.start, drop.end)\nplot_series(alldrops, component='YM', qm=False, savefig=False, col='tab20')\nprint_header(drop)\nplot_single(drop, parted=False, variable='y_parted', points=True, single=True)\n```\n\n\n```python\n# #A bash program to write experiemental metadata.\n\n#header = {'name':1,'start':2,'end':3,'volume':4,'surfaceV':5, \\\n# 'frame_rate':6,'outlier':7,'time':8,'debias':9,'first_frame':10}\n#row = !grep -n \"{drop.name[4:]}\" ../data/dielectric_improved/meta.csv | cut -d , -f 1 | cut -d : -f 1\n#row = int(row[0])\n#col = header['start']\n#value = drop.start\n```\n\n\n```bash\n%%bash -s \"$row\" \"$col\" \"$value\"\n#awk -F \";\" -v r=$1 -v c=$2 -v val=$3 'BEGIN{OFS=\";\"}; NR != r; NR == r {$c = val; print}' \\\n#../data/dielectric_improved/meta.csv > ../data/dielectric_improved/meta2.csv\n#cp ../data/dielectric_improved/meta2.csv ../data/dielectric_improved/meta.csv\n#rm ../data/dielectric_improved/meta2.csv\ncat ../data/dielectric_improved/meta.csv\n```\n\n name;start;end;volume;surfaceV;frame_rate;outlier;time;debias;first_frame;layers;guess\n 07294;3;1;0.4;1600,300;120;False;239;1200;3;4;2.76\n 07295;4;1;0.2;800,700;120;False;99;300;2;4;1.4949999999999999\n 07296;8;1;0.2;500,800;120;False;41;200;2;4;1.4949999999999999\n 07297;7;1;0.1;700,600;120;False;285;0;1;4;2.9899999999999998\n 07298;6;1;0.08;600,600;120;False;108;0;2;4;2.76\n 07299;6;1;0.05;600,500;120;False;83;0;2;4;3.4499999999999997\n 07300;8;1;0.03;500,500;120;False;90;0;2;4;4.83\n 07301;6;1;0.03;200,300;120;True;151;500;1;4;7.13\n 07319;2;1;0.3;1400,1400;120;False;999;0;1;4;1.38\n 07325;8;1;0.2;1300,1000;120;False;999;400;1;3;1.9549999999999998\n 07326;7;1;0.15;1000,1100;120;False;999;0;1;3;2.484\n 07327;10;1;0.3;1000,800;120;False;999;0;1;3;1.4167999999999998\n 07328;9;1;0.1;800,800;120;False;999;0;1;3;2.8979999999999997\n 07329;10;1;0.1;700,700;120;False;999;0;1;3;3.0589999999999997\n 07334;6;1;0.5;1600,900;120;False;999;500;1;3;1.4076000000000002\n 07335;7;1;0.2;800,800;120;False;999;0;1;3;2.05275\n 07336;7;1;0.05;800,700;120;False;999;0;1;3;3.6845999999999997\n\n\n## Munging\n\n\n```python\ndef radius(**kwargs):\n \"\"\"\n Given experimental volume (in mL) the functon returns droplet radius (in m).\n \"\"\"\n if 'mass' in kwargs.keys():\n pass\n if 'volume' in kwargs.keys():\n vol = kwargs['volume']\n return (3 * vol * 1E-6/(np.pi * 4))**(1/3.) # droplet radius [m]\n\ndef mass(volume):\n \"\"\"\n Given experiemental volume (in mL) the function returns mass (in kg).\n \"\"\"\n return 1000 * volume * 1E-6\n\ndef volume(radius_drop):\n \"\"\"\n Given the radius (in m) returns the volume (in m^3).\n \"\"\"\n return 4/3*np.pi*radius_drop**3\n\ndef weber(drop, U):\n \"\"\"\n Returns the Weber number.\n \"\"\"\n surface_tension = 72.86/1000\n density = 1000\n return density*2*radius(volume=drop.volume)*(U/100)**2/surface_tension\n\ndef tj(drop):\n \"\"\"\n Returns the dimensionless contact time.\n \"\"\"\n surface_tension = 72.86/1000\n density = 1000\n return np.sqrt(density*radius(volume=drop.volume)**3/surface_tension)\n\ndef reynolds(U, R_drop):\n \"\"\"\n Returns the Reynolds number.\n \"\"\"\n nu = 15.11E-6\n D = 2 * R_drop\n return D*np.abs(U)/nu\n\ndef ohnesorge(drop):\n R_drop = radius(volume=drop.result.x[1])\n viscosity = 1.0016\n density = 1000\n surface_tension = 72.86/1000\n return viscosity/np.sqrt(density * surface_tension * R_drop)\n\ndef bond(drop):\n #surfaceV, volume, q, dy0\n R_drop = radius(volume=drop.result.x[1])\n surface_tension = 72.86/1000\n #e_force = charge_density(drop.result[0])*eta_0*drop.result[2]\n #e_force = eta_0 * 90 * drop.result[0]**2 #Ree0U^2/y\n e_force = drop.Ef0**2 * 80 * eta_0\n return e_force * R_drop / surface_tension\n```\n\n\n```python\ndef ellipse(data):\n \"\"\"\n Returns the droplet radius in the vertical direction.\n \"\"\"\n YM = data['YM']\n a = data['Major']\n b = data['Minor']\n Angle = (data['Angle']-90)*np.pi/180\n return a*b/((b*np.cos(Angle))**2 + (a*np.sin(Angle))**2)**(1/2)\n\ndef ym_0(drop, n):\n \"\"\"\n Returns drop minima and maxima. \n \"\"\"\n ym = drop.data['YM'][drop.start:-drop.end]\n minm = signal.argrelextrema(ym, np.less, order=4)[0][::]\n maxm = signal.argrelextrema(ym, np.greater, order=4)[0][::]\n minm = np.append([0],minm)\n minm = np.append(minm, [len(ym)-1])\n intstart = minm[n]\n intend = minm[n+1]\n #if minm.shape[0] == 2:\n # YM_0 = 0\n #else:\n # YM_0 = ym[minm[1]] - ellipse(drop.data)[minm[1]]\n YM_0 = 0\n return YM_0, intstart, intend, minm\n\ndef contact(drop, ym, a, b):\n \"\"\"\n Returns a mask with elements true where the droplet is not in contact with the surface.\n \"\"\"\n contact = ym - ellipse(drop.data[a:b])*1 # distance from the bottom of the drop to YM_0\n atol = np.std(ellipse(drop.data[a:b]))*3\n above_mask = np.invert(np.isclose(contact, 0, atol=atol))\n below_zero_mask = np.invert(np.array([(contact <= 0)]))\n return np.logical_and(above_mask, below_zero_mask).flatten()\n\ndef get_data(drop, param_est=False, **kwargs):\n \"\"\"\n Returns filtered droplet position, velocity and acceleration, up to the first trajectory apoapse when\n param_est==True, for all non-contacting time otherwise.\n \"\"\"\n a = drop.start\n b = -drop.end\n t = drop.data['Slice'][a:b]/drop.frame_rate\n ym = drop.data['YM'][a:b]\n dt = t[1]-t[0]\n YM_0, intstart, intend, minm = ym_0(drop, n=0)\n ym = ym - YM_0\n contact_mask = contact(drop, ym, a, b)\n if param_est==True:\n intendmask = np.array([(t <= t[intend])])\n intstartmask = np.array([(t >= t[intstart])])\n parted_mask = np.logical_and.reduce((intstartmask.flatten(), intendmask.flatten(), contact_mask))\n try:\n maxm = signal.argrelextrema(sg_filter(ym[parted_mask],dt)[0], np.greater, order=4)[0][::][0]\n except IndexError:\n maxm = -1\n return (t[parted_mask][0:maxm], sg_filter(ym[parted_mask], dt)[0][0:maxm]/100, \n sg_filter(ym[parted_mask], dt)[1][0:maxm]/100, sg_filter(ym[parted_mask], dt)[2][0:maxm]/100)\n else: #partitioning\n stepsize = 1\n #split_array = np.split(contact_mask, np.where(contact_mask[1:] != contact_mask[:-1])[0] + 1)\n #contact_array = [subarray for subarray in split_array if np.any(subarray)==False]\n #for keys, vals in enumerate(contact_array):\n # vals = len(vals)/120\n # contact_array[keys]=vals\n #\n indices = np.where(contact_mask[1:] != contact_mask[:-1])[0] + 1\n indices[::2]-=1\n if contact_mask[0]==True:\n indices = np.append(0,indices)\n if contact_mask[-1]==True:\n indices = np.append(indices, len(contact_mask)-1)\n y_parted = np.array([])\n dy_parted = np.array([])\n ddy_parted = np.array([])\n t_parted = np.array([])\n ind_parted = np.array([])\n for keys, vals in np.ndenumerate(indices):\n if keys[0] % 2 == 0 and indices[keys[0]+1]+1-vals>=10:\n ind_parted_a = len(y_parted)\n y_parted = np.append(y_parted, sg_filter(ym[vals:indices[keys[0]+1]+1], dt)[0])\n dy_parted = np.append(dy_parted, sg_filter(ym[vals:indices[keys[0]+1]+1], dt)[1])\n ddy_parted = np.append(ddy_parted, sg_filter(ym[vals:indices[keys[0]+1]+1], dt)[2])\n t_parted = np.append(t_parted, t[vals:indices[keys[0]+1]+1])\n ind_parted = np.append(ind_parted, [ind_parted_a, len(y_parted)-1])\n return ym, t, dt, contact_mask, y_parted, dy_parted, ddy_parted, t_parted, ind_parted.astype(int)\n```\n\n# Parameter Estimation\n\n\n```python\n#inputs\nd = 6.47/100\n\nimport numpy as np\n#physical constants\neta_0 = 8.85E-12 # vacuum permitivity\neta_r = 3.4 # relative permitivity\nk = 1/(4*np.pi*eta_0) # Coulomb's constant\n#global k, eta_0, d\n\n\neta_a=eta_r\nsusceptibility = eta_a - 1\nkk = susceptibility/(susceptibility + 2)\nk\n```\n\n\n\n\n 0.5454545454545454\n\n\n\n\n```python\ndef electric_field(end, sigma):\n \"\"\"\n Returns the 1-D electric field, and the gradient of its square\n in the z-direction of a uniform finite square of charge. (units?)\n \"\"\"\n \n #d = 6.5/100\n Ef = np.array([4*k*sigma*np.arctan(d**2/(2*z*np.sqrt(2*d**2 + 4*z**2))) \\\n for z in np.linspace(1E-6, end, 10000)])\n del_Ef2 = np.gradient(Ef**2)\n return Ef, del_Ef2\n\ndef ef2(z, sigma):\n return 4*k*sigma*np.arctan(d**2/(2*z*np.sqrt(2*d**2 + 4*z**2)))\n \ndef charge_density(surfaceV, layers):\n old = surfaceV * eta_0 * eta_r/((layers*2.8+5.9)/1000)\n return old\n```\n\n\n```python\n#\n#print(np.mean(list(drop.surfaceV)))\n#print('Actual fieldmeter reading -{:.2f} kV'.format(V))\n#print('Simulated fieldmeter reading -{:.2f} kV'.format(electric_field(2.54/100, sigma)[2]/1000))\n#print('Simulated fieldmeter reading -{:.2f} kV/m'.format(electric_field(2.54/100, sigma)[0]/1000))\n#\n## Plot the results\n##from matplotlib import rc\n##import pylab\n##%config InlineBackend.figure_formats=['svg']\n##%matplotlib inline\n##rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})\n##rc('text', usetex=True)\n#\n#zz = np.linspace(0.00001, 3./100, 1000) \n##zz = np.linspace(0, 4, 1000)\n#plt.semilogx(zz*1000, electric_field(zz, sigma)[2]/1000)\n#plt.xlabel('z ($cm$)')\n#plt.ylabel('Scalar Potential ($kV$)')\n##plt.autoscale(enable=True, axis='x', tight=True)\n#plt.yticks([2,3,4])\n#plt.show()\n#\n#fig, ax1 = plt.subplots()\n#ax1.plot(zz*100, electric_field(zz, sigma)[0]/1000, zz*100, electric_field(zz, sigma)[3]/1000)\n#ax2 = ax1.twinx()\n#ax2.plot(zz*100, np.multiply(electric_field(zz, sigma)[3],zz)/1000, 'r')\n#ax1.set_xlabel('z ($cm$)')\n#ax1.set_ylabel('Electric field ($kV/m$)')\n#ax2.set_ylabel('Surface Voltage E*d ($kV$)')\n#plt.show()\n#\n#fig, ax1 = plt.subplots()\n#ax1.semilogy(zz*100, np.abs(electric_field(zz, sigma)[1]/1000), 'r', label=r'$\\nabla E$')\n#ax2 = ax1.twinx()\n#ax2.semilogy(zz*100, np.abs(electric_field(zz, sigma)[4]/1000), 'k', label=r'$\\nabla E^2$')\n#ax1.set_xlabel('z ($cm$)')\n#ax1.set_ylabel(r'$\\nabla E$')\n#ax2.set_ylabel(r'$\\nabla E^2$')\n#ax1.legend()\n#plt.show()\n```\n\n\n```python\ndef force_ep(q, Ef):\n \"\"\"\n Returns the electrophoretic force [N], including the contribution to the \n attraction of image charges reflected across the dielectric boundary.\n \"\"\"\n return q * Ef\n\ndef force_image(z, q, R_drop):\n eta_a=eta_r\n susceptibility = eta_a - 1\n k = susceptibility/(susceptibility + 2)\n if z.any() <= 0:\n z[z <= 0] = R_drop\n return 1/(16*np.pi*eta_0)*k*q**2/z**2\n\ndef force_dep(z, R_drop, del_Ef):\n \"\"\"\n Returns the dielectrophoretic force [N].\n \"\"\"\n eta_air = 1.\n eta_water = 90.\n K = (eta_water - eta_air)/(eta_water + 2 * eta_air)\n return -2 * np.pi * R_drop**3. * eta_air * K * eta_0 * del_Ef\n\ndef cd(re):\n \"\"\"\n Drag coefficent, Abraham correlation.\n \"\"\"\n return 24/9.06**2 * (1 + 9.06/np.sqrt(re))**2\n \ndef drag(v, R_drop):\n \"\"\"\n Returns the aerodynamic drag force [N].\n \"\"\"\n rho = 1.225\n #Cd = 24/reynolds(v, R_drop) + 5/np.sqrt(reynolds(v, R_drop)) + 0.3\n return cd(reynolds(v, R_drop))*2*rho*np.pi*R_drop**2*v**2\n\n```\n\n\n```python\nimport scipy.integrate as integrate\nfrom scipy import stats\n\ndef fun(y, t, params):\n \"\"\"\n 1-D Equation of motion for a droplet with initial velocity u0 subject to drag, and electrical forces.\n \"\"\"\n \n z, u = y # unpack current values of y\n m, R_drop, sigma, q, Ef, del_Ef, zf = params # unpack parameters \n ef_interp = np.interp(z, zf, Ef)\n del_ef_interp = np.interp(z,zf,del_Ef)\n #- force_dep(z, R_drop, del_ef_interp)\n derivs = [u, (- force_ep(q, ef_interp) \\\n - force_image(z, q, R_drop) - drag(u, R_drop))/m] # list of dy/dt=f functions\n return derivs\n\ndef get_model(x, model_params):\n \"\"\"\n Solves the ODE for the droplet trajectory given the design vector, x.\n \"\"\"\n t0, z0, volt0, vol0, tStop, layers, q0, Ef, del_Ef, zf = model_params\n surfaceV, volume, q, u0 = x \n m = mass(volume) # droplet mass [kg]\n R_drop = radius(volume=volume) # droplet radius\n sigma = charge_density(surfaceV, layers)\n \n # Initial values\n z0 = z0 # initial displacement\n u0 = u0 # initial velocity\n t0 = t0 # initial time\n\n # Bundle parameters for ODE solver\n params = (m, R_drop, sigma, q, Ef, del_Ef, zf)\n \n # Bundle initial conditions for ODE solver\n y0 = [z0, u0]\n\n # Make time array for solution\n tInc = 0.00001\n t_rk = np.arange(t0, tStop, tInc)\n\n # Call the ODE solver\n psoln = integrate.odeint(fun, y0, t_rk, args=(params,), mxords=5)\n return psoln, t_rk\n```\n\n\n```python\n# error estimates from pyfssa\n# http://pyfssa.readthedocs.io/en/stable/nelder-mead.html\n\ndef _neldermead_errors(sim, fsim, func, X0, *args):\n # fit quadratic coefficients\n fun = func\n args = args\n n = len(sim) - 1\n x = .5 * (sim[np.mgrid[0:n+1, 0:n+1]][1] + sim[np.mgrid[0:n+1, 0:n+1]][0])\n\n for i in range(n + 1):\n assert(np.array_equal(x[i,i], sim[i]))\n for j in range(n + 1):\n assert(np.array_equal(x[i,j], 0.5 * (sim[i] + sim[j])))\n\n y = np.nan * np.ones(shape=(n + 1, n + 1))\n for i in range(n + 1):\n y[i, i] = fsim[i]\n for j in range(i + 1, n + 1):\n y[i, j] = y[j, i] = fun(np.multiply(X0, x[i, j]), *args)\n\n y0i = y[np.mgrid[0:n+1, 0:n+1]][0][1:,1:, 0]\n for i in range(n):\n for j in range(n):\n assert y0i[i, j] == y[0, i + 1], (i, j)\n\n y0j = y[np.mgrid[0:n+1, 0:n+1]][0][0, 1:, 1:]\n for i in range(n):\n for j in range(n):\n assert y0j[i, j] == y[0, j + 1], (i, j)\n\n b = 2 * (y[1:, 1:] + y[0, 0] - y0i - y0j)\n for i in range(n):\n assert abs(b[i, i] - 2 * (fsim[i + 1] + fsim[0] - 2 * y[0, i + 1])) < 1e-12\n for j in range(n):\n if i == j:\n continue\n assert abs(b[i, j] - 2 * (y[i + 1, j + 1] + fsim[0] - y[0, i + 1] -\n y[0, j + 1])) < 1e-12\n\n q = (sim - sim[0])[1:].T\n for i in range(n):\n assert np.array_equal(q[:, i], sim[i + 1] - sim[0])\n \n varco = -np.dot(q, np.dot(np.linalg.inv(b), q.T)) # variance-covariance matrix\n #print(varco)\n w = np.abs(np.linalg.eig(varco)[0])\n cond = np.log10(np.nanmax(w)/np.nanmin(w))\n #print('condition number', cond)\n return np.sqrt(np.diag(varco))\n```\n\n\n```python\nimport scipy.optimize as opt\nimport scipy.interpolate as interp\n\ndef get_params(drop, a=3.5, **kwargs):\n \"\"\"\n Gets experimental parameters from drop object.\n \"\"\"\n layers = drop.layers\n surfaceV = np.mean(drop.surfaceV) # superhydrophobic surface potential\n volume = drop.volume # droplet volume\n if hasattr(drop, 'guess'):\n q = drop.guess*1E-12*volume*surfaceV\n else:\n q = a*1E-12*volume*surfaceV # wild-ass guess droplet net charge [C]\n if 'test' in kwargs.keys() and kwargs['test']==True:\n q = a*1E-12*volume*surfaceV\n sigma = charge_density(surfaceV, layers)\n t, y, dy, ddy = get_data(drop, param_est=True)\n t0 = t[0] # droplet initial time\n y0 = y[0] # droplet initial position\n dy0 = dy[0] # droplet initial y-velocity\n return surfaceV, volume, q, sigma, t0, y0, dy0, layers #remove sigma, m, R_drop\n\ndef get_constraints(drop):\n \"\"\"\n Gets the minimization problem constraints from the experimental measurement error for each parameter.\n \"\"\"\n \n constraints = {'volume': 0.02, # [m^3]\n 'q': None,\n 't0': 1/120., # [s]\n 'y0': 0.02/100, # [m]\n }\n y, t, dy, ddy = get_data(drop, param_est=True)\n y = y\n dy = dy\n constraints.update({'dy0': dy[0]*np.sqrt(1 + (constraints['y0']/(y[1]-y[0]))**2)})\n if np.std(drop.surfaceV) > 0.:\n constraints.update({'surfaceV': np.std(drop.surfaceV) + np.mean(drop.surfaceV)*0.2}) # [V]\n else:\n constraints.update({'surfaceV':100. + np.mean(drop.surfaceV)*0.2})\n return constraints\n\ndef obj_func(x, *args):\n \"\"\"\n Pseudo-objective function with box bound constraints handles by exterior penalty function. The function to be \n minimized is the chi2 goodness of fit between the experimental and model trajectories given the parameter\n estimates (e.g. the design vector), x.\n \"\"\"\n \n exp_data, model_params, constraints = args\n surfaceV, volume, q, dy0 = x \n t, y, dy, ddy = exp_data\n yStop = y[-1]+10*(y[-1]-y[-2])\n layers = model_params[5]\n sigma = charge_density(surfaceV, layers)\n Ef, del_Ef = electric_field(yStop, sigma)\n zf = np.linspace(1E-6, yStop, 10000)\n model_params = model_params + (Ef, del_Ef, zf)\n psoln, t_rk = get_model(x, model_params)\n #psoln = psoln[:,0]*100\n #b = interp.interp1d(np.arange(psoln.size),psoln)\n #y_soln = b(np.linspace(0,psoln.size-1,len(t)))\n y_soln = np.array([])\n for times in t:\n y_soln = np.append(y_soln, np.interp(times, t_rk, psoln[:,0]))\n \n rp = 50 \n penalty_function = rp * ( max(0, volume/(model_params[3] + constraints['volume']) - 1)**2 \n + max(0, -volume/(model_params[3] - constraints['volume']) + 1)**2\n + 0.80* max(0, surfaceV/(model_params[2] + constraints['surfaceV']) - 1)**2 \n + 0.80* max(0, -surfaceV/(model_params[2] - constraints['surfaceV']) + 1)**2\n + max(0, -q/(model_params[6]))**2)\n return np.log(stats.chisquare(y,f_exp=y_soln,axis=0)[0]) + penalty_function\n \ndef reporter(p):\n \"\"\"Reporter function to capture intermediate states of optimization.\"\"\"\n global sim\n sim.append(p)\n \ndef res(drop, a, **kwargs):\n \"\"\"\n Returns the parameter estimates of the drop experiment.\n \"\"\"\n global sim\n exp_data = get_data(drop, param_est=True)\n constraints = get_constraints(drop)\n surfaceV, volume, q, sigma, t0, y0, dy0, layers = get_params(drop, a)\n model_params = (t0, y0, surfaceV, volume, exp_data[0][-1], layers, q)\n X0 = np.asarray((surfaceV, volume, q, dy0))\n sim = [X0]\n args = (exp_data, model_params, constraints)\n result = opt.minimize(obj_func, X0, args=args, \n method='nelder-mead', options={'maxiter':300}, callback=reporter)\n fsim = np.exp(np.array([obj_func(x, *args) for x in sim]))\n result.fun = np.exp(result.fun)\n #final_fsim = np.array([obj_func2(x, *args) for x in result.final_simplex[0]])\n #try:\n # error = _neldermead_errors(np.divide(result.final_simplex[0],X0), \\\n # final_fsim, obj_func2, X0, *args)\n #except AssertionError:\n # error = 'fail'\n error = False\n return result, sim, fsim, error\n```\n\n\n```python\ndef fmt(x):\n \"\"\" For pretty printing chi^2 in scientific notation\"\"\"\n x = float('%s' % float('%.1g' % x))\n a, b = '{:.1e}'.format(x).split('e')\n b = int(b)\n return r'${} \\times 10^{{{}}}$'.format(a[0], b)\n```\n\n\n```python\ndef param_est_plot(drop, sub=False, method='nelder-mead', a=3.5, **kwargs):\n if 'test' in kwargs.keys() and kwargs['test']==True:\n exp_data = get_data(drop, param_est=True)\n surfaceV, volume, q, sigma, t0, y0, dy0, layers = get_params(drop, a, test=True)\n model_params = (t0, y0, surfaceV, volume, exp_data[0][-1], layers, q)\n x = np.asarray((surfaceV, volume, q, dy0))\n elif 'test' in kwargs.keys() and kwargs['test']==False and sub==False:\n result, sim, fsim, error = res(drop, a)\n x = result.x\n #print(result)\n #print(\"errors:\", error)\n check_design_feasibility(drop, result)\n else:\n x = drop.result.x\n \n surfaceV, volume, q, sigma, t0, y0, dy0, layers = get_params(drop, a)\n t, y, dy, ddy = get_data(drop, param_est=True)\n model_params = (t0, y0, surfaceV, volume, t[-1], layers, q)\n yStop = y[-1] + 20 * (y[-1]-y[-2])\n sigma = charge_density(x[0], layers)\n Ef, del_Ef = electric_field(yStop, sigma)\n zf = np.linspace(1E-6, yStop, 10000)\n model_params = model_params + (Ef, del_Ef, zf)\n psoln, t_rk = get_model(x, model_params)\n y_soln = np.array([])\n dy_soln = np.array([])\n for times in t:\n y_soln = np.append(y_soln, np.interp(times, t_rk, psoln[:,0]*100))\n dy_soln = np.append(dy_soln, np.interp(times, t_rk, psoln[:,1]*100))\n \n dx = (t[1]-t[0])\n ddy_soln = np.gradient(dy_soln, dx, edge_order=2)\n drop.y_soln = y_soln\n drop.dy_soln = dy_soln\n drop.ddy_soln = ddy_soln\n y=y*100\n if 'adding' in kwargs.keys() and kwargs['adding']==True:\n return\n \n if 'forces' not in kwargs.keys() and sub==True:\n i = kwargs['i']\n fig = kwargs['fig']\n axs = kwargs['axs'] \n axs[i].plot(t[::], y[::], 'ko', \n markersize=6, markerfacecolor='white', markeredgecolor='black', label='experiment')\n axs[i].plot(t,y_soln, 'r', label='model')\n axs[i].set_title(r'$\\chi^2 =$ ' + fmt(drop.result.fun), fontsize=12)#'{0:.1E}'.format(drop.result.fun))\n #axs[i].legend(title=drop.name)\n #axs.set_xlabel('time')\n #axs.set_ylabel('position')\n #plt.tight_layout()\n #plt.show()\n elif 'forces' in kwargs.keys() and kwargs['forces']==True:\n if 'sub' in kwargs.keys() and kwargs['sub']==True:\n i = kwargs['i']\n fig = kwargs['fig']\n axs = kwargs['axs']\n ep_force, drag_force, image_force, inertia = plot_forces(y_soln, dy_soln, ddy_soln, x, yStop, layers)\n #plt.semilogy(t, dep_force, label='Dielectrophoretic force')\n every = int(len(ep_force)/5)\n n = 3\n axs[i].semilogy(t[:-n], ep_force[:-n], 'rs--', label='Coulomb force', markevery=every)\n axs[i].semilogy(t[:-n], drag_force[:-n], 'bo-', label='Drag force', markevery=every)\n axs[i].semilogy(t[:-n], image_force[:-n], 'cv-.', label='Image force', markevery=every)\n axs[i].semilogy(t[:-n], inertia[:-n], 'k+:', label='Inertia', markevery=every)\n else:\n n=20\n ep_force, drag_force, image_force, inertia = plot_forces(y_soln, dy_soln, ddy_soln, x, yStop, layers)\n #plt.semilogy(t, dep_force, label='Dielectrophoretic force')\n plt.semilogy(y[:-n]/(d*100), ep_force[:-n]/inertia[:-n], 'r', alpha=0.75)\n plt.semilogy(y[:-n]/(d*100), drag_force[:-n]/inertia[:-n], 'b', alpha=0.75)\n plt.semilogy(y[:-n]/(d*100), image_force[:-n]/inertia[:-n], 'c', alpha=0.75)\n else:\n # Plot results\n \n if 'test' in kwargs.keys() and kwargs['test']==False and sub==False:\n #plt.semilogy(range(len(errors)-1), -np.diff(errors))\n fig = plt.figure()\n plt.semilogy(range(len(fsim)), fsim, 'k')\n plt.ylabel(r'$\\chi^2$')\n plt.xlabel('Iteration number')\n savefig('convergence', pics)\n plt.show()\n \n if 'showall' in kwargs.keys() and kwargs['showall']==True and sub==False:\n #fig = plt.figure()\n plt.plot(t[::], y[::], 'ko', \n markersize=6, markerfacecolor='None', \n markeredgecolor='black', alpha=0.5)\n plt.plot(t,y_soln, 'r')\n #plt.xlabel('time (s)')\n #plt.ylabel('position (cm)')\n #plt.legend()\n #plt.show()\n return\n \n fig = plt.figure()\n plt.plot(t[::], y[::], 'ko', \n markersize=6, markerfacecolor='white', markeredgecolor='black', label='experiment')\n plt.plot(t,y_soln, 'r', label='model')\n plt.xlabel('time (s)')\n plt.ylabel('position (cm)')\n plt.legend()\n plt.show()\n \n plt.plot(y_soln[1:], ddy_soln[1:], 'k', label='model')\n #plt.plot(y, ddy*100, 'b', label='data')\n plt.ylabel('acceleration ($\\mbox{cm/}\\mbox{s}^2$)')\n plt.xlabel('position (cm)')\n plt.legend()\n plt.show()\n \n plt.plot(t[1:], reynolds(dy_soln[1:], radius(volume=drop.volume)), 'k', label='model')\n #plt.plot(y, ddy*100, 'b', label='data')\n plt.ylabel('Re')\n plt.xlabel('t (s)')\n #plt.legend()\n plt.show()\n #print(cd(reynolds(dy_soln[1:], radius(volume=drop.volume)))[0])\n \n ep_force, drag_force, image_force, inertia = plot_forces(y_soln, dy_soln, ddy_soln, x, yStop, layers)\n #plt.semilogy(t, dep_force, label='Dielectrophoretic force')\n plt.semilogy(y/(d*100), ep_force/inertia, 'rs--', markevery=10)\n plt.semilogy(y/(d*100), drag_force/inertia, 'bo-', markevery=10)\n plt.semilogy(y/(d*100), image_force/inertia, 'cv-.', markevery=10)\n #plt.semilogy(t, inertia, 'k+:', label='Inertia', markevery=10)\n plt.ylabel('dimensionless force')\n plt.xlabel(r'$y/L$')\n plt.legend()\n plt.show()\n \ndef check_design_feasibility(drop, result):\n #(surfaceV, volume, q, dy0)\n print(result.fun)\n #print(result.errors)\n comp_params = get_params(drop)\n print('nit', result.nit)\n names = ['surfaceV', 'volume', 'q', 'dy0']\n constraints = get_constraints(drop)\n\n for n in range(len(result.x)):\n try:\n print('{}, {:.3} < {:.3} < {:.3}'.format(names[n], \\\n comp_params[n]-constraints[names[n]],result.x[n], \\\n comp_params[n]+constraints[names[n]]))\n except (TypeError, KeyError):\n print('{}, {:.3} {:.3}'.format(names[n], result.x[n], comp_params[n]))\n continue\n```\n\n\n```python\ndef plot_forces(z, u, du, results, yStop, layers):\n z = z/100\n u = u/100\n du = du/100\n surfaceV, volume, q, dy0 = results\n sigma = charge_density(surfaceV, layers)\n Ef, del_Ef = electric_field(yStop, sigma)\n zf = np.linspace(1E-6, yStop, 10000)\n R_drop = radius(volume=volume)\n ef_interp = np.interp(z, zf, Ef)\n del_ef_interp = np.interp(z,zf,del_Ef)\n #force_dep(z, R_drop, del_ef_interp),\n inertia = mass(volume)*du\n return force_ep(q, ef_interp), drag(u, R_drop), force_image(z, q, R_drop), np.abs(inertia)\n```\n\n\n```python\n\"\"\"\nUse n=1,2,3 etc (where n may be 0 or any positive integer) to look at an individual bounce.\nOtherwise use n='all' to see all bounces.\n\"\"\"\n\ndrop = drop07336\nprint_header(drop)\n#print(radius(volume=drop.result[1]))\n#print('Oh', ohnesorge(radius(volume=drop.volume)))\n#print('Bo', bond(drop))\n#plot_single(drop, parted=True, variable='y_parted');\n```\n\n name drop07336\n volume 0.05 mL\n surfaceV [800. 700.] V\n\n\n\n```python\n#%time\na=drop.guess*1 #= a #1.9*2.3\nfig = plot_single(drop, parted=True, variable='y_parted', points=False, single=True)\nname = 'bounce_series'\npics= True\nplt.ylabel(r'$y$ (cm)')\nplt.xlabel(r'$t$ (s)')\nsavefig(name, pics)\nplt.show()\n#param_est_plot(drop, sub=False, method='nelder-mead', a=a, test=True) \n```\n\n\n```python\n#drop.guess = a\n```\n\n\n```python\n## #A bash program to write experiemental metadata.\n#header = {'name':1,'start':2,'end':3,'volume':4,'surfaceV':5, \\\n# 'frame_rate':6,'outlier':7,'time':8,'debias':9,'first_frame':10, 'layers':11, 'guess':12}\n#row = !grep -n \"{drop.name[4:]}\" ../data/dielectric_improved/meta.csv | cut -d , -f 1 | cut -d : -f 1\n#row = int(row[0])\n#col = header['guess']\n#value = drop.guess\n```\n\n\n```python\n#%%bash -s \"$row\" \"$col\" \"$value\"\n#awk -F \";\" -v r=$1 -v c=$2 -v val=$3 'BEGIN{OFS=\";\"}; NR != r; NR == r {$c = val; print}' \\\n#../data/dielectric_improved/meta.csv > ../data/dielectric_improved/meta2.csv\n#cp ../data/dielectric_improved/meta2.csv ../data/dielectric_improved/meta.csv\n#rm ../data/dielectric_improved/meta2.csv\n#cat ../data/dielectric_improved/meta.csv\n```\n\n### Series estimates\n\n\n```python\ni = 0\na = 0.72*2.3 #2.2\nfor drop in alldrops:\n print(drop)\n (alldrops[drop].result, alldrops[drop].sim,\n alldrops[drop].fsim, alldrops[drop].error) = res(alldrops[drop], a=a)\n param_est_plot(alldrops[drop], sub=True, adding=True)\n i += 1\n\n```\n\n drop07294\n drop07295\n drop07296\n drop07297\n drop07298\n drop07299\n drop07300\n drop07319\n drop07325\n drop07326\n drop07327\n drop07328\n drop07329\n drop07334\n drop07335\n drop07336\n\n\n\n```python\n#import pickle\n#with open('../data/pickles/sorted_data.pkl', 'wb') as f:\n# pickle.dump(alldrops, f)\n#alldrops_ba = alldrops\n```\n\n\n```python\n#with open('../data/pickles/sorted_data.pkl', 'rb') as f:\n# alldrops = pickle.load(f)\n#sorted_keys = [elements[1] for elements in \\\n# sorted([[vals.y_soln.max(), keys] for keys, vals in alldrops.items()])]\n#sorted_vals = [alldrops[x] for x in sorted_keys]\n#sorted_drops = dict(zip(sorted_keys, sorted_vals))\n```\n\n\n```python\nfrom math import ceil\n\nfig, axs = plt.subplots(4,ceil(len(alldrops)/4), figsize=(12, 10), facecolor='w', edgecolor='k')\nfig.subplots_adjust(hspace = .5, wspace=.3)\naxs = axs.ravel()\ni = 0\nfor drop in sorted_drops:\n plot_single(sorted_drops[drop], parted=True, variable='y_parted', sub=True, i=i, fig=fig, axs=axs)\n i += 1\n\nfig.text(0.5, -0.02, r'$t$ (s)', ha='center', fontsize=16, color='k')\nfig.text(-0.02, 0.5, r'$y$ (cm)', va='center', rotation='vertical', fontsize=16, color='k')\nfig.tight_layout()\n#plt.legend(loc=(1.2, 2.55), borderaxespad=0., fontsize=14)\nname = 'jump_matrix'\nsavefig(name, pics)\nplt.show()\n```\n\n\n```python\nfig, axs = plt.subplots(4,ceil(len(alldrops)/4), figsize=(12, 10), facecolor='w', edgecolor='k')\nfig.subplots_adjust(hspace = .5, wspace=.3)\naxs = axs.ravel()\ni = 0\nfor drop in sorted_drops:\n param_est_plot(sorted_drops[drop], sub=True, method='Nelder-Mead', a=a, i=i, fig=fig, axs=axs)\n i += 1\n\nfig.text(0.5, -0.02, r'$t$ (s)', ha='center', fontsize=16)\nfig.text(-0.02, 0.5, r'$y$ (cm)', va='center', rotation='vertical', fontsize=16)\n#plt.legend(loc=(1.2, 2.55), borderaxespad=0., fontsize=14)\nfig.tight_layout()\nname = 'inverse_problem'\nsavefig(name, pics)\nplt.show()\n```\n\n\n```python\n#fig, axs = plt.subplots(4,ceil(len(alldrops)/4), figsize=(12, 10), facecolor='w', edgecolor='k')\n#fig.subplots_adjust(hspace = .5, wspace=.3)\n#axs = axs.ravel()\n#i = 0\n#for drop in sorted_drops:\n# param_est_plot(sorted_drops[drop], sub=True, method='Nelder-Mead', forces=True, a=a, i=i, fig=fig, axs=axs)\n# i += 1\n#\n#fig.text(0.5, 0.06, r'$t$ (s)', ha='center', fontsize=14)\n#fig.text(0.06, 0.5, 'Force (N)', va='center', rotation='vertical', fontsize=14)\n#plt.legend(loc=(1.2, 2.45), borderaxespad=0., fontsize=14);\n#name = 'forces'\n#savefig(name, pics)\n#plt.show()\n```\n\n\n```python\nplt.figure()\nfor drop in sorted_drops:\n param_est_plot(sorted_drops[drop], sub=False, method='Nelder-Mead', forces=True)\nplt.ylim(ymin=5E-3)\nplt.xlabel(r'$y/L$')\nplt.ylabel('Dimensionless force')\nplt.semilogy([],[],'r', label='Coulomb force', markevery=10)\nplt.semilogy([],[],'b', label='Drag force', markevery=10)\nplt.semilogy([],[],'c', label='Image force', markevery=10)\n#leg = plt.legend(loc=4)\n#leg.get_frame().set_linewidth(0.0)\nname = 'forces_all'\nsavefig(name, pics)\nplt.show();\n```\n\n\n```python\n#likely outliers\n#outliers = {#'drop07294':alldrops.pop('drop07294'),\n# 'drop07334':alldrops.pop('drop07334')}\n#alldrops['drop07334'] = outliers.pop('drop07334')\n #surfaceV, volume, q, dy0\n```\n\n\n```python\ndef param_est(alldrops):\n #surfaceV, volume, q, dy0\n Ef0 = []\n vols = []\n qs = []\n u0s = []\n surfaceVs = []\n for drop in alldrops.keys():\n qs.append(alldrops[drop].result.x[2])\n vols.append(alldrops[drop].result.x[1])\n y = get_data(alldrops[drop], param_est=True)[1]\n yStop = y[-1] + 20 * (y[-1]-y[-2])\n sigma = charge_density(alldrops[drop].result.x[0], alldrops[drop].layers)\n zf = np.linspace(1E-6, yStop, 10000)\n R_0 = radius(volume = alldrops[drop].result.x[1])\n Ef0.append(np.interp(radius(volume=alldrops[drop].result.x[1]), zf, electric_field(yStop, sigma)[0]))\n alldrops[drop].Ef0 = Ef0[-1]\n surfaceVs.append(alldrops[drop].result.x[0])\n u0s.append(alldrops[drop].result.x[3])\n return np.array(vols), np.array(qs), np.array(u0s), np.array(surfaceVs), np.array(Ef0)\n\nvols, qs, u0s, surfaceVs, Ef0 = param_est(alldrops)\n```\n\n\n```python\ndef drop_planning_plots(surfaceVs, vol, qs, **kwargs):\n x = np.array(surfaceVs)/1000\n y = vol\n z = qs\n plt.plot(x,y,'.')\n plt.xlabel(r'$\\varphi$ (kV)')\n plt.ylabel('$V_d$ (mL)')\n plt.show()\n \n xi = np.linspace(min(x), max(x), 50)\n yi = np.linspace(min(y),max(y), 50)\n Z = matplotlib.mlab.griddata(x, y, z, xi, yi, interp='linear')\n X, Y = np.meshgrid(xi, yi)\n\n fig = plt.figure()\n #ax = Axes3D(fig)\n #ax.scatter(x, vols, qs, c='k', marker='o', s=40)\n\n #norm = Normalize(vmin=np.min(Z), vmax=np.max(Z))\n #surf = ax.plot_surface(X,Y,Z, linewidth=1,\n # antialiased=True, cstride=2, \n # rstride=2, edgecolor='k',\n # cmap=cm.jet, alpha=0.3, norm=norm)\n #fig.colorbar(surf, label=r'$q$ (C)')\n #ax.view_init(90, 35-90)\n CS = plt.contourf(X,Y,Z,cmap=plt.cm.bone)\n plt.scatter(x, y, color='k', facecolors='white', edgecolors='k')\n #CS2 = plt.contour(CS, levels=CS.levels[::2], colors='white')\n #fmt = matplotlib.ticker.LogFormatterMathtext()\n #fmt.create_dummy_axis()\n #manual_locations = [(-1, -1.4), (-0.62, -0.7), (-2, 0.5)]\n #plt.clabel(CS2, inline=1, colors='w', fontsize=10, fmt=fmt, manual=manual_locations)\n cbar = plt.colorbar(CS)\n cbar.ax.set_ylabel('$q$ (C)')\n #cbar.add_lines(CS2)\n plt.xlabel(r'$\\varphi_s$ (kV)')\n plt.ylabel(r'$V_d$ (mL)')\n #ax.set_xlabel(r'$E_0$ (kV/cm)')\n #ax.set_ylabel(r'Volume (mL)')\n #ax.set_zticks([])\n #ax.set_zlabel(r'$q$ (C)')\n if 'savefig' in kwargs.keys() and kwargs['savefig']==True:\n name = 'charge'\n savefig(name, pics)\n plt.show()\n \ndrop_planning_plots(surfaceVs, vols, qs, savefig=True)\n#print(qs)\n```\n\n\n```python\n#from sympy import *\n#init_printing()\n#\n#y, z, nu, a = symbols('y z nu a')\n#nu*integrate(z/((z**2 + y**2)*sqrt(z**2 + y**2 + a**2/4)), (y,0,a/2))\n```\n\n\n```python\ndef hysteresis_plot():\n # relating apparent contact angle hysteresis to \n # roll-off angle using the model of Furmidge, J. Colloid Sci. 1962, 17, 309.\n # 2 mL data for DDT surfaces\n\n #%config InlineBackend.figure_formats = ['svg']\n #matplotlib.rcParams['text.usetex'] = True\n #matplotlib.rcParams['text.latex.preamble'] = [r'\\usepackage{amsmath}']\n #matplotlib.rcParams['text.latex.unicode'] = True\n #matplotlib.rcParams.update(pgf_with_latex)\n n = np.linspace(5,25,5)\n a = np.linspace(130,180,100)\n const = -10\n colors = plt.cm.cool_r(np.linspace(0,1,len(n)))\n\n for k,i in np.ndenumerate(n):\n b = a - i\n hyster = np.arcsin(np.cos(a*np.pi/180)-np.cos(b*np.pi/180))\n plt.plot(a, const*hyster, label=int(i), color=colors[k], zorder=1)\n\n exp_roll_off = 2.8\n exp_CA_appar = 148\n plt.scatter([exp_CA_appar,138],[exp_roll_off,2],100, marker=\"v\", facecolors='r', edgecolors='m', zorder=2)\n plt.annotate('laser-etched PMMA ($R_q \\sim 775 \\mu m$)', xy=(exp_CA_appar,exp_roll_off), xycoords='data', \n xytext=(15, 30), textcoords='offset points', fontsize=10, \n arrowprops=dict(arrowstyle=\"->\", connectionstyle=\"arc3, rad=.47\"))\n plt.annotate('', xy=(138,2), xycoords='data', \n xytext=(85,74), textcoords='offset points', fontsize=10, \n arrowprops=dict(arrowstyle=\"->\", connectionstyle=\"arc3, rad=.2\"))\n\n plt.scatter([158,],[2,],100, marker=\"o\", facecolors='b', edgecolors='c', zorder=2)\n plt.annotate('sandpaper ($R_q \\sim 30 \\mu m$)', xy=(158,2), xycoords='data', \n xytext=(-10, 40), textcoords='offset points', fontsize=10, \n arrowprops=dict(arrowstyle=\"->\", connectionstyle=\"arc3, rad=.5\"))\n\n plt.legend(title=r'$\\theta_r - \\theta_a$', loc='upper right')\n axes = plt.gca()\n axes.set_xlim(135,180)\n plt.xticks([140,150, 160,170, 180])\n plt.ylabel(r'$\\alpha$')\n plt.xlabel(r'$\\theta$')\n name = 'hysteresis'\n savefig(name, pics)\n plt.show()\n\nhysteresis_plot()\n```\n\n\n```python\ndef impact_data(drop):\n \"\"\"\n Returns Weber numbers, contact times, and coefficients of restituion for each bounce event in a drop.\n \"\"\"\n ym, t, dt, contact_mask, y_parted, dy_parted, ddy_parted, t_parted, ind_parted = get_data(drop, param_est=False)\n ind_parted = ind_parted[1:-1]\n impact_weber = weber(drop, dy_parted[ind_parted])[::2]\n ind_parted = ind_parted.tolist()\n contact_time = np.array([])\n diameter_ratio = np.array([])\n restitution = np.array([])\n for keys, vals in enumerate(ind_parted[::2]):\n ind_parted.index(ind_parted[::2][keys])\n pair = [ind_parted[::2][keys], ind_parted[ind_parted.index(ind_parted[::2][keys])+1]]\n contact_time = np.append(contact_time, t_parted[pair[1]]-t_parted[pair[0]])\n restitution = np.append(restitution, abs(dy_parted[pair[1]]/dy_parted[pair[0]]))\n \n # Note: I scale the contact time by a parameter such that it \n # gives the same results as a manual count of frames.\n try:\n tb = t_parted[ind_parted[0]]\n except IndexError:\n tb = False\n return impact_weber, contact_time*.78, diameter_ratio, restitution*.78, tb #0.78\n\ndef q_to_m(drop):\n #surfaceV, volume, q, dy0\n density = 1000\n U = drop.dy_soln[0]/100 #drop.result.x[3]\n old_inertia = density * 2 * radius(volume=drop.result.x[1])**2 * U**2\n old_e_force = charge_density(drop.result.x[0], drop.layers)*eta_0*drop.result.x[2]\n #e_force = drop.result.x[0]/2.54*100*drop.result.x[2]\n e_force = drop.Ef0*drop.result.x[2]\n inertia = mass(drop.result.x[1]) * U**2\n eu_s = inertia/(e_force*radius(volume=drop.result.x[1]))\n phi = 4 * np.pi *radius(volume=drop.result.x[1])**2/d**2\n eu_m = inertia/(e_force*d)\n qm = drop.result.x[2]/mass(drop.result.x[1])\n return eu_s, 2*phi**2*eu_s, eu_m, qm, phi\n\ndef img(drop):\n q = drop.result.x[2]\n rad = radius(volume=drop.result.x[1])\n eta_a=eta_r\n susceptibility = eta_a - 1\n k = susceptibility/(susceptibility+2)\n return k * q /(16*np.pi*eta_0*rad**2*drop.Ef0)\n \ndef tc(drop):\n epss, epsl, epsm, qm, phi = q_to_m(drop)\n epsl = epss*phi\n tc_s = epss*radius(volume=drop.result.x[1])/(drop.result.x[3])\n #tc_l = epsl*radius(volume=drop.result.x[1])/(drop.result.x[3])\n tc_l = epss*phi*radius(volume=drop.result.x[1])/(drop.result.x[3])\n tfl = 0.456229037652571*epsl**3 + 0.799200144*epsl**2 + 1.33293333333333*epsl + 2\n tfs = (-4*epss**2*(0.0121*epss + 0.2121)*(2*(0.0121*epss + 0.2121)**4 + \n 6*(0.0121*epss + 0.2121)**3 - 4*(0.0121*epss + 0.2121)**2 + 1)/\n (0.363*epss + 40*(0.0121*epss + 0.2121)**3 + 60*(0.0121*epss + 0.2121)**2 + 11.363) \n + 4*epss*(-0.0121*epss + 0.7879)*(0.0121*epss + 0.2121)/(3*(0.0242*epss + 1.4242)) + 2)\n tc_m = epsm*radius(volume=drop.result.x[1])/(drop.result.x[3])\n return tc_s, tc_l, tfl, tfs, tc_m\n\ndef yc(drop):\n epss, epsl, epsm, qm, phi = q_to_m(drop)\n epsl = epss*phi\n yc_s = epss*radius(volume=drop.result.x[1])*100\n yc_l = epsl*radius(volume=drop.result.x[1])*100\n yc_m = epsm*radius(volume=drop.result.x[1])*100\n return yc_s, yc_l, yc_m\n\ndef yf(drop):\n epsilon, phi = q_to_m(drop)[0], q_to_m(drop)[4]\n alpha = img(drop)\n epsilonl = epsilon*phi\n yfl = (0.00997118232863575*epsilonl**4 + 0.0180903441714801*epsilonl**3\n - 0.0972943974999999*epsilonl**2 + 0.2498375*epsilonl + 1/2)\n yfs = (epsilon**3*(alpha*(-17*alpha - 12)/60 + alpha*(73*alpha**2 + 117*alpha + 45)/630 \n + alpha*(-73*alpha**3 - 190*alpha**2 - 162*alpha - 45)/5040 + alpha/5) + \n epsilon**2*(alpha*(11*alpha + 9)/60 + alpha*(-11*alpha**2 - 20*alpha - 9)/360 - alpha/4) + \n epsilon*(alpha*(-alpha - 1)/12 + alpha/3) + 1/2)\n return yfl, yfs\n\ndef molacek(bo, web):\n st = 72.86/1000\n density = 1000\n #rad = radius(volume=drop.result.x[1])\n #density* rad**3/st\n return (2*(np.log(1/bo)/3 + 0.192/np.log(1/bo))**(1/2) * \n (np.pi - np.arccos((1 + 3.*web/(bo**2 * np.log(1./bo)))**(-1/2))))\n\ndef impact_plots(alldrops):\n #fig1, ax1 = plt.subplots()\n qm = np.array([])\n i_weber = np.array([])\n contact_r = np.array([])\n restn = np.array([])\n oh = np.array([])\n bo = np.array([])\n \n for keys in alldrops:\n impact_weber, contact_time, diameter_ratio, restitution, tb = impact_data(alldrops[keys])\n if impact_weber.size != 0:\n qm = np.append(qm, impact_weber.size*[q_to_m(alldrops[keys])[0]])\n R_drop = radius(volume=alldrops[keys].result.x[1])\n oh = np.append(oh, impact_weber.size*[ohnesorge(alldrops[keys])])\n bo = np.append(bo, impact_weber.size*[bond(alldrops[keys])])\n i_weber = np.append(i_weber, impact_weber)\n restn = np.append(restn, restitution)\n contact_r = np.append(contact_r, contact_time/tj(alldrops[keys]))\n alldrops[keys].tb = tb\n print(keys, restitution)\n print(np.average(i_weber), np.std(i_weber))\n \n fig = plt.figure()\n norm = matplotlib.colors.Normalize(vmin=bo.min(), vmax=bo.max())\n cmap = plt.cm.rainbow\n plt.scatter(i_weber, contact_r, c=bo, cmap=cmap, norm=norm)\n cb1 = plt.colorbar()\n cb1.set_label(r'$\\mathrm{\\mathit{Bo_e}} \\equiv \\frac{\\epsilon E_0^2 R_d}{\\gamma}$')\n \n plt.xscale('log')\n plt.xticks([10**(-2),10**(-1),10**0])\n #plt.grid(which='both', linestyle='--')\n webers = np.linspace(10**(-2),.99, 100)\n bos = [0.4,.6,.8]\n plt.plot(webers, 2.2*np.ones(len(webers)), 'k--', label='Richards, 2001')\n plt.plot(webers, np.log(1/webers) + 2.31, linestyle='-.', color='grey', \n label='Gopinath et al., 2002')\n plt.plot(webers, molacek(0.1, webers), c=cmap(norm(0.4)),\n label='Molacek et al., 2012, $\\mathbf{B}\\mbox{o} = $' + '{}'.format(0.2))\n for boo in bos:\n plt.plot(webers, molacek(boo, webers), c=cmap(norm(boo)), \n label='..., $\\mathbf{B}\\mbox{o} = $' + '{}'.format(boo))\n \n plt.legend(loc=2)\n plt.xlabel('$\\mathbf{W}\\mbox{e}$')\n plt.ylabel(r'$t_j/ \\tau$')\n plt.ylim(ymin=2)\n plt.xlim(xmin=5E-2)\n name = 'contact2'\n savefig(name, pics)\n plt.show()\n \n fig = plt.figure()\n plt.scatter(i_weber, restn, c=bo, cmap=plt.cm.rainbow, norm=norm)\n plt.xscale('log')\n plt.xticks([10**(-2),10**(-1),10**0])\n #plt.grid(which='both', linestyle='--')\n cb2 = plt.colorbar()\n cb2.set_label(r'$\\mathrm{\\mathit{Bo_e}} \\equiv \\frac{\\epsilon E_0^2 R_d}{\\gamma}$')\n plt.xlabel('$\\mathbf{W}\\mbox{e}$')\n plt.ylabel('$C_r$')\n name = 'restitution'\n bbox_props = dict(boxstyle=\"round\", fc=\"w\", ec=\"0.5\", alpha=0.7)\n plt.text(1.5E-2,.75,r'$\\mathbf{O}\\mbox{h}_{\\mu} = 2.2$', bbox=bbox_props)\n savefig(name, pics)\n plt.show()\n```\n\n\n```python\neus0s = np.array([])\nbs = np.array([])\nqss = np.array([])\nfor drop in alldrops: \n eus0, b, c, qm, phi = q_to_m(alldrops[drop])\n eus0s = np.append(eus0s, eus0)\n bs = np.append(bs, b)\n qss = np.append(qs, qm)\n#escp, vols = (list(t) for t in zip(*sorted(zip(escp, vols))))\n#plt.figure()\n#plt.plot(vols, eus0,\n# 'ko', markersize=6, markerfacecolor='white', markeredgecolor='black')\n#plt.ylabel(r'$\\mathbf{E}\\mbox{u}$')\n#plt.xlabel(r'$V_d$')\n#name = 'eu_vs_vol'\n#savefig(name, pics)\n#plt.show()\ndef tof(dim):\n return 2+1.333*dim + 0.700*dim**2\nprint(eus0s) \nprint(bs*eus0s/(8*np.pi))\ntof(bs*eus0s)\nprint(qs)\n```\n\n\n```python\nimpact_plots(alldrops)\n```\n\n\n```python\n#figure_series = {'drop07296':drop07296, 'drop07327':drop07327, 'drop07295':drop07295,\n# 'drop07335':drop07335, 'drop07319':drop07319, 'drop07300':drop07300,\n# 'drop07325':drop07325, 'drop07326':drop07326}\n#\nfigure_series = ['drop07296','drop07327','drop07295',\n 'drop07335','drop07319', 'drop07300', 'drop07325', 'drop07326']\n\nkeys = [elements[1] for elements in \n sorted([[alldrops[vals].y_soln.max(), vals] for vals in figure_series], reverse=True)]\nsorted_drops2 = dict(zip(keys, [alldrops[key] for key in keys]))\n```\n\n\n```python\n#sorted_keys2 = [elements[1] for elements in \n# sorted([[vals.y_soln.max(), keys] for keys, vals in figure_series.items()], reverse=True)]#[::-1]\n#sorted_vals2 = [figure_series[x] for x in sorted_keys2]#[::-1]\n#sorted_drops2 = dict(zip(sorted_keys2, sorted_vals2))\n\n\n['y_soln' in dir(sorted_drops2[drop]) for drop in sorted_drops2]\n\ni = 0\nfor drop in sorted_drops2:\n param_est_plot(sorted_drops2[drop], sub=False, method='Nelder-Mead', a=a, i=i, fig=fig, axs=axs, showall=True)\n i += 1\n\nplt.xlabel('$t$ (s)')\nplt.ylabel('$y$ (cm)')\nplt.legend(loc='best')\nplt.plot([],[],'ko', markersize=6, markerfacecolor='None', \n markeredgecolor='black', label='experiment')\nplt.plot([],[],'r-', label='model')\n\nleg = plt.legend(loc='best')\nleg.get_frame().set_linewidth(0.0)\nfor text in leg.get_texts():\n text.set_color('k')\nname = 'forces_all'\nname = 'inverse_problem2'\nsavefig(name, pics)\nplt.show()\n```\n\n\n```python\nsorted_keys = [elements[1] for elements in \\\n sorted([[q_to_m(vals), keys] for keys, vals in alldrops.items()])]\n```\n\n\n```python\ncol = 'viridis_r' #'rainbow_r'\n\n#m=-5\n#sorted_vals = [alldrops[x] for x in sorted_keys[:m]]\n#sorted_drops = dict(zip(sorted_keys, sorted_vals))\n#plot_series(alldrops, component='YM', qm=True, label=[r'$t$ (s)', r'$y$ (cm)'], col=col)\n#plot_series(figure_series, component='YM', qm=True, label=[r'$t$ (s)', r'$y$ (cm)'], \n# savefig=True, reg = 's', name='series_s_eu', col=col)\n\nn = -4\nm = -1\nsorted_vals = [alldrops[x] for x in sorted_keys[:n]]\nsorted_drops = dict(zip(sorted_keys, sorted_vals))\nplot_series(sorted_drops, component='YM', qm=True, label=[r'$t^*$', r'$y^*$'], \n savefig=False, reg = 's', dimless = True, name='series_s_ds', col=col)\n\n#\n#n = -5\n#sorted_vals = [alldrops[x] for x in sorted_keys[n:]]\n#sorted_drops = dict(zip(sorted_keys, sorted_vals))\n#plot_series(sorted_drops, component='YM', qm=True, label=[r'$\\bar{t}$',r'$\\bar{y}$'], \n# savefig=True, reg = 'l', dimless = True, name='series_l_ds', col=col)\n#\n```\n\n\n```python\nn = -1\nm = 0\nsorted_vals = [alldrops[x] for x in sorted_keys[:n]]\nsorted_drops = dict(zip(sorted_keys, sorted_vals))\nplot_series(sorted_drops2, component='YM', qm=True, label=[r'$t$ (s)', r'$y$ (cm)'], \n savefig=True, reg = 's', dimless = False, name='series', col=col)\n```\n\n\n```python\n#escape = []\n#for drop in alldrops:\n# escape.append(8*np.pi()*radius(alldrops[drop])**2/d**2)\n#print(np.average(os), np.std(os))\n```\n\n\n```python\ndef find_nearest(array,value):\n idx = (np.abs(array-value)).argmin()\n return idx\n\n#print(650*eta_0/(2.54/100), 'field meter')\n#print(650*eta_0/(2.54/100), 'non-contacting voltmeter')\n#print(650*eta_0*3/(0.4*5/1000), 'nc-voltmeter w/ dielectric back by conductive groundplane')\n\ndrop = alldrops['drop07298']\n\nef = electric_field(40/100, charge_density(drop.result.x[0], drop.layers))[0]\nz = np.linspace(1/1000, 40/100, 10000)\n\nE0 = charge_density(drop.result.x[0], drop.layers)/(2*eta_0)\nplt.loglog(z/(6.5/100), ef/E0, 'k')\nplt.ylabel(r'$E/E_0$')\nplt.xlabel(r'$y/L$')\nprint(E0/1000/100)\n\nname = 'E0'\nsavefig(name, pics)\nplt.show()\n\n#print(np.interp(2.54/100,z,ef)/1000, 'electric field at 2.54 cm')\n```\n\n\n```python\n#for drop in sorted_drops:\n# print(drop)\n# check_design_feasibility(sorted_drops[drop], sorted_drops[drop].result)\n# print('\\n')\n```\n\n\n```python\nEf0\n```\n\n\n```python\nimport pandas\nfrom statsmodels.formula.api import ols, rlm, WLS\nfrom pandas import plotting\nimport seaborn\n\ndef scatter_matrix(x):\n area, qs, u0s, surfaceVs, Ef0 = x\n data = pandas.DataFrame({'area':area, 'charge':qs, 'u0': u0s, 'Ef0':Ef0/100/1000})\n plotting.scatter_matrix(data, diagonal='density', c='k');\n prod = area*Ef0\n data = pandas.DataFrame({'area':area, 'charge':qs, 'u0': u0s, 'Ef0':Ef0, 'prod': prod})\n model = ols('charge ~ prod - 1', data)\n #model = rlm('charge ~ area * Ef0', data)\n #r2_wls = WLS(model.endog, model.exog, weights=model.fit().weights).fit().rsquared\n print(model.fit().summary())\n #print(r'R^2 = {}'.format(r2_wls))\n\narea = (vols/1E6)**(2/3)\nvariables = (area, qs, u0s, surfaceVs, Ef0)\nscatter_matrix(variables)\nname = 'scatter'\nsavefig(name, pics)\nplt.show()\n\nplt.scatter(qs, area*Ef0)\nplt.xlim(0.25E-10, 0.6E-9)\nplt.show()\n```\n\n\n```python\n#plt.scatter(area*Ef0, qs, color='k')\n#data = pandas.DataFrame({'charge':qs,'prod': area*Ef0})\n#model = ols('charge ~ prod', data).fit()\n#inter, coef = model._results.params\n#f = lambda x: x*coef + inter\n#x = np.linspace(0, (area*Ef0).max(), 100)\n#plt.plot(x, f(x), 'r') \n#plt.ylim(1E-11, 1E-9)\n#plt.show()\n#model.summary()\n```\n\n\n```python\nparallel = np.abs(np.array([ -2.70158796e-12, -4.20176010e-12, 7.78928795e-12, -4.86568450e-12,\n -1.79171842e-12, -1.74111697e-11, -1.07898239e-11, -5.68331113e-12,\n -2.89082418e-12, -2.57343722e-12, -1.30402067e-11, -7.51379045e-13,\n 1.11525974e-12, -9.83808965e-13, -6.00145897e-13, -2.84923705e-12,\n -9.78463511e-12]))\nstats.ttest_ind(qs, parallel, equal_var=False)\n```\n\n\n```python\nfrom statsmodels.stats.anova import anova_lm\nims = np.array([])\neus = np.array([])\nphis = np.array([])\nplt.figure()\nfor drop in alldrops:\n eus = np.append(eus, q_to_m(alldrops[drop])[0])\n ims = np.append(ims, img(alldrops[drop]))\n phis = np.append(phis, q_to_m(alldrops[drop])[4])\n\n# Convert the data into a Pandas DataFrame to use the formulas framework\n# in statsmodels\ndata = pandas.DataFrame({'Eu': eus, 'Im': ims, 'Phi':phis})\n\n# Fit the model\nmodel = ols(formula=\"Im ~ Eu\", data=data).fit()\noffset, coef = model._results.params\nplt.plot(eus, eus*coef + offset, 'k-', alpha=0.3,\n label=r'$\\mathbf{I}\\mbox{g} \\approx 0.013 \\mathbf{E}\\mbox{u} + 0.230$, $R^2=0.57$')\nplt.scatter(eus, ims, color='w', edgecolors='k')\n\nplt.xlabel(r'$\\mathbf{E}\\mbox{u}$')\nplt.ylabel(r'$\\mathbf{I}\\mbox{g}$')\nplt.legend()\nname = 'dnumbs'\nsavefig(name, pics)\nplt.show()\n\n# Fit the model\n#model = ols(formula=\"Im ~ Phi\", data=data).fit()\n#offset, coef = model._results.params\nplt.scatter(ims, 10*phis)\nplt.show()\n```\n\n\n```python\n# Print the summary\nprint(model.summary())\n\n# Peform analysis of variance on fitted linear model\nanova_results = anova_lm(model)\n\nprint('\\nANOVA results')\nprint(anova_results)\n\n```\n\n\n```python\nsorted_keys = [elements[1] for elements in \\\n sorted([[vals.y_soln.max(), keys] for keys, vals in alldrops.items()])]\nm=-5\nsorted_vals = [alldrops[x] for x in sorted_keys[:m]]\nsorted_drops = dict(zip(sorted_keys, sorted_vals))\n\nbo = np.array([alldrops[x].Ef0*alldrops[x].volume for x in sorted_keys[:m]])\nnorm = matplotlib.colors.Normalize(vmin=bo.min(), vmax=bo.max())\ncmap = plt.cm.rainbow\ntbl = np.array([])\ntcl = np.array([])\neus = np.array([])\nybl = np.array([])\nycl = np.array([])\ntk = np.array([])\nyk = np.array([])\nline = np.arange(0.2,1,100)\nfor drop in sorted_drops:\n #print(2*sorted_drops[drop].tb/tc(sorted_drops[drop])[3])\n tbl = np.append(tbl, sorted_drops[drop].tb)\n tcl = np.append(tcl, tc(sorted_drops[drop])[0]*tc(sorted_drops[drop])[2])\n ybl = np.append(ybl, sorted_drops[drop].data['YM'].max())\n ycl = np.append(ycl, yc(sorted_drops[drop])[0]*yf(sorted_drops[drop])[0])\n tk = np.append(tk,tc(sorted_drops[drop])[0])\n yk = np.append(yk, yc(sorted_drops[drop])[0])\n eus = np.append(eus, q_to_m(sorted_drops[drop])[0])\ndata = pandas.DataFrame({'tb': tbl, 'tof': tcl})\n\n# Fit the model\nmodel = ols(formula=\"tof ~ tb\", data=data).fit()\noffset, coef = model._results.params\nprint(1/coef)\n#plt.plot(tbl, tbl*coef + offset, 'k-')\nplt.scatter(tbl, tcl, color='None', edgecolors='k', label='$\\mathcal{O}(\\phi^3 \\mathbf{E}\\mbox{u}^3)$')\nplt.scatter(tbl, tk*2, color='None', marker='s', edgecolors='r', label='$\\mathcal{O}(1)$')\n#cb1 = plt.colorbar()\n#cb1.set_label(r'$\\mathbf{E}\\mbox{u}$')\nplt.xlabel(r'${t_b}$ (s)')\nplt.ylabel(r'$t_c t_f$ (s)')\nleg = plt.legend()\nleg.get_frame().set_linewidth(0.0)\nfor text in leg.get_texts():\n text.set_color('k')\nname = 'times'\nsavefig(name, pics)\nplt.show()\n#model.summary()\n\n#plt.scatter(tbl/tcl, eus, color='w', edgecolors='k')\n#plt.scatter(tbl/(tk*2), eus, color='w', edgecolors='r')\n#plt.show()\n\n#print(tbl)\n\n#sorted_keys = [elements[1] for elements in \\\n# sorted([[vals.y_soln.max(), keys] for keys, vals in alldrops.items()])]\n#sorted_vals = [alldrops[x] for x in sorted_keys]\n#sorted_drops = dict(zip(sorted_keys, sorted_vals))\n#tbl = np.array([])\n#tcl = np.array([])\n#for drop in sorted_drops:\n# #print(2*sorted_drops[drop].tb/tc(sorted_drops[drop])[3])\n# tbl = np.append(tbl, sorted_drops[drop].tb)\n# tcl = np.append(tcl, tc(sorted_drops[drop])[0]*tc(sorted_drops[drop])[2])\n#print(tcl)\n```\n\n\n```python\nsorted_keys = [elements[1] for elements in \\\n sorted([[q_to_m(vals), keys] for keys, vals in alldrops.items()])]\nn = -1\nm = -1\nsorted_vals = [alldrops[x] for x in sorted_keys[:n]]\n#del sorted_vals[-2]\nsorted_drops = dict(zip(sorted_keys, sorted_vals))\n\nybl = np.array([])\nycl = np.array([])\neus = np.array([])\nyk = np.array([])\nline = np.arange(0.2,1,100)\nfor drop in sorted_drops:\n #print(2*sorted_drops[drop].tb/tc(sorted_drops[drop])[3])\n ybl = np.append(ybl, sorted_drops[drop].data['YM'].max())\n ycl = np.append(ycl, yf(sorted_drops[drop])[0])\n yk = np.append(yk, yc(sorted_drops[drop])[0])\n eus = np.append(eus, q_to_m(sorted_drops[drop])[0])\ndata = pandas.DataFrame({'ymax': ybl, 'ycl': ycl*yk})\n\n# Fit the model\nmodel = ols(formula=\"ycl ~ ymax\", data=data).fit()\noffset, coef = model._results.params\nprint(1/coef)\n\nplt.figure()\nplt.scatter(eus, ybl/(yk), color='w', edgecolors='k')\nplt.ylabel(r'${y_{max}}/y_c$')\nplt.xlabel(r'$\\mathbf{E}\\mbox{u}$')\n#plt.xlim(0.4,1.5)\n#plt.ylim(0,2)\nname = 'yscale_trend'\nsavefig(name, pics)\nplt.show()\n\nplt.scatter(ybl, yk*ycl, color='None', edgecolors='k', label='$\\mathcal{O}(\\phi^3 \\mathbf{E}\\mbox{u}^3)$')\nplt.scatter(ybl, yk*0.5, color='None', marker='s', edgecolors='r', label='$\\mathcal{O}(1)$')\nplt.ylabel(r'$y_c y_f$ (cm)')\nplt.xlabel(r'$y_{max}$ (cm)')\n#plt.ylim(0,2.3)\nleg = plt.legend()\nleg.get_frame().set_linewidth(0.0)\nfor text in leg.get_texts():\n text.set_color('k')\nname = 'ymaxes'\nsavefig(name, pics)\nplt.show()\n```\n\n\n```python\neus\n```\n\n\n```python\n#m = -1\n#sorted_vals = [alldrops[x] for x in sorted_keys[:m]]\n#sorted_drops = dict(zip(sorted_keys, sorted_vals))\n#\n#bo = np.array([q_to_m(alldrops[x])[0] for x in sorted_keys[:m]])\n#norm = matplotlib.colors.Normalize(vmin=bo.min(), vmax=bo.max())\n#cmap = plt.cm.rainbow\n#\n#tbs = np.array([])\n#tcs = np.array([])\n#for drop in sorted_drops:\n# tbs = np.append(tbs, sorted_drops[drop].tb/tc(sorted_drops[drop])[0])\n# tcs = np.append(tcs, tc(sorted_drops[drop])[3])\n#\n#plt.scatter(tbs, tcs, c=bo, cmap=cmap, norm=norm)\n#cb1 = plt.colorbar()\n#cb1.set_label(r'$\\mathbf{E}\\mbox{u}$')\n#plt.xlabel(r'$\\frac{t_b}{t_c}$')\n#plt.ylabel(r'$t_f$')\n#plt.ylim(ymin=1.9, ymax=2.2)\n#plt.xlim(xmin = 2.5, xmax=3)\n#name = 'times_short'\n#savefig(name, pics)\n#plt.show()\n```\n\n\n```python\ntk = tc(alldrops['drop07296'])\nprint(tk[1]*113.75340697961346)\nprint(yc(alldrops['drop07296'])[1]/d)\n```\n\n\n```python\ndrop = 'drop07296'\ny_soln = alldrops[drop].y_soln\nt = get_data(alldrops[drop], param_est=True)[0]\n\nplt.plot(t, y_soln)\nplt.show()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "d60087268dd66733337a06b20330a9c2f4ecb2b1", "size": 821532, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "src/parameter_estimation (copy).ipynb", "max_stars_repo_name": "7deeptide/Thesis_scratch", "max_stars_repo_head_hexsha": "d776d57f642de4df718c1f655f080c8fe402e092", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/parameter_estimation (copy).ipynb", "max_issues_repo_name": "7deeptide/Thesis_scratch", "max_issues_repo_head_hexsha": "d776d57f642de4df718c1f655f080c8fe402e092", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/parameter_estimation (copy).ipynb", "max_forks_repo_name": "7deeptide/Thesis_scratch", "max_forks_repo_head_hexsha": "d776d57f642de4df718c1f655f080c8fe402e092", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 323.4377952756, "max_line_length": 347312, "alphanum_fraction": 0.9095190449, "converted": true, "num_tokens": 22526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.24461313884192074}} {"text": "\n\n\n#Chapter 6\n\n____\n\nThis chapter of [Bayesian Methods for Hackers](https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers) focuses on the most debated and discussed part of Bayesian methodologies: how to choose an appropriate prior distribution. We also present how the prior's influence changes as our dataset increases, and an interesting relationship between priors and penalties on linear regression.\n\n## Getting our priorities straight\n\n\nUp until now, we have mostly ignored our choice of priors. This is unfortunate as we can be very expressive with our priors, but we also must be careful about choosing them. This is especially true if we want to be objective, that is, not to express any personal beliefs in the priors. \n\n###Subjective vs Objective priors\n\nBayesian priors can be classified into two classes: *objective* priors, which aim to allow the data to influence the posterior the most, and *subjective* priors, which allow the practitioner to express his or her views into the prior. \n\nWhat is an example of an objective prior? We have seen some already, including the *flat* prior, which is a uniform distribution over the entire possible range of the unknown. Using a flat prior implies that we give each possible value an equal weighting. Choosing this type of prior is invoking what is called \"The Principle of Indifference\", literally we have no prior reason to favor one value over another. Calling a flat prior over a restricted space an objective prior is not correct, though it seems similar. If we know $p$ in a Binomial model is greater than 0.5, then $\\text{Uniform}(0.5,1)$ is not an objective prior (since we have used prior knowledge) even though it is \"flat\" over [0.5, 1]. The flat prior must be flat along the *entire* range of possibilities. \n\nAside from the flat prior, other examples of objective priors are less obvious, but they contain important characteristics that reflect objectivity. For now, it should be said that *rarely* is a objective prior *truly* objective. We will see this later. \n\n#### Subjective Priors\n\nOn the other hand, if we added more probability mass to certain areas of the prior, and less elsewhere, we are biasing our inference towards the unknowns existing in the former area. This is known as a subjective, or *informative* prior. In the figure below, the subjective prior reflects a belief that the unknown likely lives around 0.5, and not around the extremes. The objective prior is insensitive to this.\n\n\n```\n%matplotlib inline\nimport numpy as np\nfrom IPython.core.pylabtools import figsize\nimport matplotlib.pyplot as plt\nimport scipy.stats as stats\n\nfigsize(12.5, 3)\ncolors = [\"#348ABD\", \"#A60628\", \"#7A68A6\", \"#467821\"]\n\nx = np.linspace(0, 1)\ny1, y2 = stats.beta.pdf(x, 1, 1), stats.beta.pdf(x, 10, 10)\n\np = plt.plot(x, y1,\n label='An objective prior \\n(uninformative, \\n\"Principle of Indifference\" )')\nplt.fill_between(x, 0, y1, color=p[0].get_color(), alpha=0.3)\n\np = plt.plot(x, y2,\n label=\"A subjective prior \\n(informative)\")\nplt.fill_between(x, 0, y2, color=p[0].get_color(), alpha=0.3)\n\np = plt.plot(x[25:], 2 * np.ones(25), label=\"another subjective prior\")\nplt.fill_between(x[25:], 0, 2, color=p[0].get_color(), alpha=0.3)\n\nplt.ylim(0, 4)\n\nplt.ylim(0, 4)\nleg = plt.legend(loc=\"upper left\")\nleg.get_frame().set_alpha(0.4)\nplt.title(\"Comparing objective vs. subjective priors for an unknown probability\");\n```\n\nThe choice of a subjective prior does not always imply that we are using the practitioner's subjective opinion: more often the subjective prior was once a posterior to a previous problem, and now the practitioner is updating this posterior with new data. A subjective prior can also be used to inject *domain knowledge* of the problem into the model. We will see examples of these two situations later.\n\n### Decision, decisions...\n\nThe choice, either *objective* or *subjective* mostly depends on the problem being solved, but there are a few cases where one is preferred over the other. In instances of scientific research, the choice of an objective prior is obvious. This eliminates any biases in the results, and two researchers who might have differing prior opinions would feel an objective prior is fair. Consider a more extreme situation:\n\n> A tobacco company publishes a report with a Bayesian methodology that retreated 60 years of medical research on tobacco use. Would you believe the results? Unlikely. The researchers probably chose a subjective prior that too strongly biased results in their favor.\n\nUnfortunately, choosing an objective prior is not as simple as selecting a flat prior, and even today the problem is still not completely solved. The problem with naively choosing the uniform prior is that pathological issues can arise. Some of these issues are pedantic, but we delay more serious issues to the Appendix of this Chapter (TODO).\n\nWe must remember that choosing a prior, whether subjective or objective, is still part of the modeling process. To quote Gelman [5]:\n\n>...after the model has been fit, one should look at the posterior distribution\nand see if it makes sense. If the posterior distribution does not make sense, this implies\nthat additional prior knowledge is available that has not been included in the model,\nand that contradicts the assumptions of the prior distribution that has been used. It is\nthen appropriate to go back and alter the prior distribution to be more consistent with\nthis external knowledge.\n\nIf the posterior does not make sense, then clearly one had an idea what the posterior *should* look like (not what one *hopes* it looks like), implying that the current prior does not contain all the prior information and should be updated. At this point, we can discard the current prior and choose a more reflective one.\n\nGelman [4] suggests that using a uniform distribution with large bounds is often a good choice for objective priors. Although, one should be wary about using Uniform objective priors with large bounds, as they can assign too large of a prior probability to non-intuitive points. Ask yourself: do you really think the unknown could be incredibly large? Often quantities are naturally biased towards 0. A Normal random variable with large variance (small precision) might be a better choice, or an Exponential with a fat tail in the strictly positive (or negative) case. \n\nIf using a particularly subjective prior, it is your responsibility to be able to explain the choice of that prior, else you are no better than the tobacco company's guilty parties. \n\n### Empirical Bayes\n\nWhile not a true Bayesian method, *empirical Bayes* is a trick that combines frequentist and Bayesian inference. As mentioned previously, for (almost) every inference problem there is a Bayesian method and a frequentist method. The significant difference between the two is that Bayesian methods have a prior distribution, with hyperparameters $\\alpha$, while empirical methods do not have any notion of a prior. Empirical Bayes combines the two methods by using frequentist methods to select $\\alpha$, and then proceeds with Bayesian methods on the original problem. \n\nA very simple example follows: suppose we wish to estimate the parameter $\\mu$ of a Normal distribution, with $\\sigma = 5$. Since $\\mu$ could range over the whole real line, we can use a Normal distribution as a prior for $\\mu$. How to select the prior's hyperparameters, denoted ($\\mu_p, \\sigma_p^2$)? The $\\sigma_p^2$ parameter can be chosen to reflect the uncertainty we have. For $\\mu_p$, we have two options:\n\n1. Empirical Bayes suggests using the empirical sample mean, which will center the prior around the observed empirical mean:\n\n$$ \\mu_p = \\frac{1}{N} \\sum_{i=0}^N X_i $$\n\n2. Traditional Bayesian inference suggests using prior knowledge, or a more objective prior (zero mean and fat standard deviation).\n\nEmpirical Bayes can be argued as being semi-objective, since while the choice of prior model is ours (hence subjective), the parameters are solely determined by the data.\n\nPersonally, I feel that Empirical Bayes is *double-counting* the data. That is, we are using the data twice: once in the prior, which will influence our results towards the observed data, and again in the inferential engine of MCMC. This double-counting will understate our true uncertainty. To minimize this double-counting, I would only suggest using Empirical Bayes when you have *lots* of observations, else the prior will have too strong of an influence. I would also recommend, if possible, to maintain high uncertainty (either by setting a large $\\sigma_p^2$ or equivalent.)\n\nEmpirical Bayes also violates a theoretical axiom in Bayesian inference. The textbook Bayesian algorithm of:\n\n>*prior* $\\Rightarrow$ *observed data* $\\Rightarrow$ *posterior* \n\nis violated by Empirical Bayes, which instead uses \n\n>*observed data* $\\Rightarrow$ *prior* $\\Rightarrow$ *observed data* $\\Rightarrow$ *posterior*\n\nIdeally, all priors should be specified *before* we observe the data, so that the data does not influence our prior opinions (see the volumes of research by Daniel Kahneman *et. al* about [anchoring](http://en.wikipedia.org/wiki/Anchoring_and_adjustment) ).\n\n## Useful priors to know about\n\n### The Gamma distribution\n\nA Gamma random variable, denoted $X \\sim \\text{Gamma}(\\alpha, \\beta)$, is a random variable over the positive real numbers. It is in fact a generalization of the Exponential random variable, that is:\n\n$$ \\text{Exp}(\\beta) \\sim \\text{Gamma}(1, \\beta) $$\n\nThis additional parameter allows the probability density function to have more flexibility, hence allowing the practitioner to express his or her subjective priors more accurately. The density function for a $\\text{Gamma}(\\alpha, \\beta)$ random variable is:\n\n$$ f(x \\mid \\alpha, \\beta) = \\frac{\\beta^{\\alpha}x^{\\alpha-1}e^{-\\beta x}}{\\Gamma(\\alpha)} $$\n\nwhere $\\Gamma(\\alpha)$ is the [Gamma function](http://en.wikipedia.org/wiki/Gamma_function), and for differing values of $(\\alpha, \\beta)$ looks like:\n\n\n```\nfigsize(12.5, 5)\ngamma = stats.gamma\n\nparameters = [(1, 0.5), (9, 2), (3, 0.5), (7, 0.5)]\nx = np.linspace(0.001, 20, 150)\nfor alpha, beta in parameters:\n y = gamma.pdf(x, alpha, scale=1. / beta)\n lines = plt.plot(x, y, label=\"(%.1f,%.1f)\" % (alpha, beta), lw=3)\n plt.fill_between(x, 0, y, alpha=0.2, color=lines[0].get_color())\n plt.autoscale(tight=True)\n\nplt.legend(title=r\"$\\alpha, \\beta$ - parameters\");\n```\n\n### The Wishart distribution\n\nUntil now, we have only seen random variables that are scalars. Of course, we can also have *random matrices*! Specifically, the Wishart distribution is a distribution over all [positive semi-definite matrices](http://en.wikipedia.org/wiki/Positive-definite_matrix). Why is this useful to have in our arsenal? (Proper) covariance matrices are positive-definite, hence the Wishart is an appropriate prior for covariance matrices. We can't really visualize a distribution of matrices, so I'll plot some realizations from the $5 \\times 5$ (above) and $20 \\times 20$ (below) Wishart distribution:\n\n\n```\nimport pymc as pm\n\nn = 4\nfor i in range(10):\n ax = plt.subplot(2, 5, i + 1)\n if i >= 5:\n n = 15\n plt.imshow(pm.rwishart(n + 1, np.eye(n)), interpolation=\"none\",\n cmap=plt.cm.hot)\n ax.axis(\"off\")\n\nplt.suptitle(\"Random matrices from a Wishart Distribution\");\n```\n\nOne thing to notice is the symmetry of these matrices. The Wishart distribution can be a little troubling to deal with, but we will use it in an example later.\n\n### The Beta distribution\n\nYou may have seen the term `beta` in previous code in this book. Often, I was implementing a Beta distribution. The Beta distribution is very useful in Bayesian statistics. A random variable $X$ has a $\\text{Beta}$ distribution, with parameters $(\\alpha, \\beta)$, if its density function is:\n\n$$f_X(x | \\; \\alpha, \\beta ) = \\frac{ x^{(\\alpha - 1)}(1-x)^{ (\\beta - 1) } }{B(\\alpha, \\beta) }$$\n\nwhere $B$ is the [Beta function](http://en.wikipedia.org/wiki/Beta_function) (hence the name). The random variable $X$ is only allowed in [0,1], making the Beta distribution a popular distribution for decimal values, probabilities and proportions. The values of $\\alpha$ and $\\beta$, both positive values, provide great flexibility in the shape of the distribution. Below we plot some distributions:\n\n\n```\nfigsize(12.5, 5)\n\nparams = [(2, 5), (1, 1), (0.5, 0.5), (5, 5), (20, 4), (5, 1)]\n\nx = np.linspace(0.01, .99, 100)\nbeta = stats.beta\nfor a, b in params:\n y = beta.pdf(x, a, b)\n lines = plt.plot(x, y, label=\"(%.1f,%.1f)\" % (a, b), lw=3)\n plt.fill_between(x, 0, y, alpha=0.2, color=lines[0].get_color())\n plt.autoscale(tight=True)\nplt.ylim(0)\nplt.legend(loc='upper left', title=\"(a,b)-parameters\");\n```\n\nOne thing I'd like the reader to notice is the presence of the flat distribution above, specified by parameters $(1,1)$. This is the Uniform distribution. Hence the Beta distribution is a generalization of the Uniform distribution, something we will revisit many times.\n\nThere is an interesting connection between the Beta distribution and the Binomial distribution. Suppose we are interested in some unknown proportion or probability $p$. We assign a $\\text{Beta}(\\alpha, \\beta)$ prior to $p$. We observe some data generated by a Binomial process, say $X \\sim \\text{Binomial}(N, p)$, with $p$ still unknown. Then our posterior *is again a Beta distribution*, i.e. $p | X \\sim \\text{Beta}( \\alpha + X, \\beta + N -X )$. Succinctly, one can relate the two by \"a Beta prior with Binomial observations creates a Beta posterior\". This is a very useful property, both computationally and heuristically.\n\nIn light of the above two paragraphs, if we start with a $\\text{Beta}(1,1)$ prior on $p$ (which is a Uniform), observe data $X \\sim \\text{Binomial}(N, p)$, then our posterior is $\\text{Beta}(1 + X, 1 + N - X)$. \n\n\n#####Example: Bayesian Multi-Armed Bandits\n*Adapted from an example by Ted Dunning of MapR Technologies*\n\n> Suppose you are faced with $N$ slot machines (colourfully called multi-armed bandits). Each bandit has an unknown probability of distributing a prize (assume for now the prizes are the same for each bandit, only the probabilities differ). Some bandits are very generous, others not so much. Of course, you don't know what these probabilities are. By only choosing one bandit per round, our task is devise a strategy to maximize our winnings.\n\nOf course, if we knew the bandit with the largest probability, then always picking this bandit would yield the maximum winnings. So our task can be phrased as \"Find the best bandit, and as quickly as possible\". \n\nThe task is complicated by the stochastic nature of the bandits. A suboptimal bandit can return many winnings, purely by chance, which would make us believe that it is a very profitable bandit. Similarly, the best bandit can return many duds. Should we keep trying losers then, or give up? \n\nA more troublesome problem is, if we have a found a bandit that returns *pretty good* results, do we keep drawing from it to maintain our *pretty good score*, or do we try other bandits in hopes of finding an *even-better* bandit? This is the exploration vs. exploitation dilemma.\n\n### Applications\n\n\nThe Multi-Armed Bandit problem at first seems very artificial, something only a mathematician would love, but that is only before we address some applications:\n\n- Internet display advertising: companies have a suite of potential ads they can display to visitors, but the company is not sure which ad strategy to follow to maximize sales. This is similar to A/B testing, but has the added advantage of naturally minimizing strategies that do not work (and generalizes to A/B/C/D... strategies)\n- Ecology: animals have a finite amount of energy to expend, and following certain behaviours has uncertain rewards. How does the animal maximize its fitness?\n- Finance: which stock option gives the highest return, under time-varying return profiles.\n- Clinical trials: a researcher would like to find the best treatment, out of many possible treatment, while minimizing losses. \n- Psychology: how does punishment and reward affect our behaviour? How do humans learn?\n\nMany of these questions above are fundamental to the application's field.\n\nIt turns out the *optimal solution* is incredibly difficult, and it took decades for an overall solution to develop. There are also many approximately-optimal solutions which are quite good. The one I wish to discuss is one of the few solutions that can scale incredibly well. The solution is known as *Bayesian Bandits*.\n\n\n### A Proposed Solution\n\n\nAny proposed strategy is called an *online algorithm* (not in the internet sense, but in the continuously-being-updated sense), and more specifically a reinforcement learning algorithm. The algorithm starts in an ignorant state, where it knows nothing, and begins to acquire data by testing the system. As it acquires data and results, it learns what the best and worst behaviours are (in this case, it learns which bandit is the best). With this in mind, perhaps we can add an additional application of the Multi-Armed Bandit problem:\n\n- Psychology: how does punishment and reward affect our behaviour? How do humans learn?\n\n\nThe Bayesian solution begins by assuming priors on the probability of winning for each bandit. In our vignette we assumed complete ignorance of these probabilities. So a very natural prior is the flat prior over 0 to 1. The algorithm proceeds as follows:\n\nFor each round:\n\n1. Sample a random variable $X_b$ from the prior of bandit $b$, for all $b$.\n2. Select the bandit with largest sample, i.e. select $B = \\text{argmax}\\;\\; X_b$.\n3. Observe the result of pulling bandit $B$, and update your prior on bandit $B$.\n4. Return to 1.\n\nThat's it. Computationally, the algorithm involves sampling from $N$ distributions. Since the initial priors are $\\text{Beta}(\\alpha=1,\\beta=1)$ (a uniform distribution), and the observed result $X$ (a win or loss, encoded 1 and 0 respectfully) is Binomial, the posterior is a $\\text{Beta}(\\alpha=1+X,\\beta=1+1−X)$.\n\nTo answer our question from before, this algorithm suggests that we should not discard losers, but we should pick them at a decreasing rate as we gather confidence that there exist *better* bandits. This follows because there is always a non-zero chance that a loser will achieve the status of $B$, but the probability of this event decreases as we play more rounds (see figure below).\n\nBelow we implement Bayesian Bandits using two classes, `Bandits` that defines the slot machines, and `BayesianStrategy` which implements the above learning strategy.\n\n\n```\nfrom pymc import rbeta\n\nrand = np.random.rand\n\n\nclass Bandits(object):\n\n \"\"\"\n This class represents N bandits machines.\n\n parameters:\n p_array: a (n,) Numpy array of probabilities >0, <1.\n\n methods:\n pull( i ): return the results, 0 or 1, of pulling \n the ith bandit.\n \"\"\"\n\n def __init__(self, p_array):\n self.p = p_array\n self.optimal = np.argmax(p_array)\n\n def pull(self, i):\n # i is which arm to pull\n return np.random.rand() < self.p[i]\n\n def __len__(self):\n return len(self.p)\n\n\nclass BayesianStrategy(object):\n\n \"\"\"\n Implements a online, learning strategy to solve\n the Multi-Armed Bandit problem.\n \n parameters:\n bandits: a Bandit class with .pull method\n \n methods:\n sample_bandits(n): sample and train on n pulls.\n\n attributes:\n N: the cumulative number of samples\n choices: the historical choices as a (N,) array\n bb_score: the historical score as a (N,) array\n \"\"\"\n\n def __init__(self, bandits):\n\n self.bandits = bandits\n n_bandits = len(self.bandits)\n self.wins = np.zeros(n_bandits)\n self.trials = np.zeros(n_bandits)\n self.N = 0\n self.choices = []\n self.bb_score = []\n\n def sample_bandits(self, n=1):\n\n bb_score = np.zeros(n)\n choices = np.zeros(n)\n\n for k in range(n):\n # sample from the bandits's priors, and select the largest sample\n choice = np.argmax(rbeta(1 + self.wins, 1 + self.trials - self.wins))\n\n # sample the chosen bandit\n result = self.bandits.pull(choice)\n\n # update priors and score\n self.wins[choice] += result\n self.trials[choice] += 1\n bb_score[k] = result\n self.N += 1\n choices[k] = choice\n\n self.bb_score = np.r_[self.bb_score, bb_score]\n self.choices = np.r_[self.choices, choices]\n return\n```\n\nBelow we visualize the learning of the Bayesian Bandit solution.\n\n\n```\nfigsize(11.0, 10)\n\nbeta = stats.beta\nx = np.linspace(0.001, .999, 200)\n\n\ndef plot_priors(bayesian_strategy, prob, lw=3, alpha=0.2, plt_vlines=True):\n # plotting function\n wins = bayesian_strategy.wins\n trials = bayesian_strategy.trials\n for i in range(prob.shape[0]):\n y = beta(1 + wins[i], 1 + trials[i] - wins[i])\n p = plt.plot(x, y.pdf(x), lw=lw)\n c = p[0].get_markeredgecolor()\n plt.fill_between(x, y.pdf(x), 0, color=c, alpha=alpha,\n label=\"underlying probability: %.2f\" % prob[i])\n if plt_vlines:\n plt.vlines(prob[i], 0, y.pdf(prob[i]),\n colors=c, linestyles=\"--\", lw=2)\n plt.autoscale(tight=\"True\")\n plt.title(\"Posteriors After %d pull\" % bayesian_strategy.N +\n \"s\" * (bayesian_strategy.N > 1))\n plt.autoscale(tight=True)\n return\n```\n\n\n```\nhidden_prob = np.array([0.85, 0.60, 0.75])\nbandits = Bandits(hidden_prob)\nbayesian_strat = BayesianStrategy(bandits)\n\ndraw_samples = [1, 1, 3, 10, 10, 25, 50, 100, 200, 600]\n\nfor j, i in enumerate(draw_samples):\n plt.subplot(5, 2, j + 1)\n bayesian_strat.sample_bandits(i)\n plot_priors(bayesian_strat, hidden_prob)\n # plt.legend()\n plt.autoscale(tight=True)\nplt.tight_layout()\n```\n\nNote that we don't really care how accurate we become about the inference of the hidden probabilities — for this problem we are more interested in choosing the best bandit (or more accurately, becoming *more confident* in choosing the best bandit). For this reason, the distribution of the red bandit is very wide (representing ignorance about what that hidden probability might be) but we are reasonably confident that it is not the best, so the algorithm chooses to ignore it.\n\nFrom the above, we can see that after 1000 pulls, the majority of the \"blue\" function leads the pack, hence we will almost always choose this arm. This is good, as this arm is indeed the best.\n\nBelow is a D3 app that demonstrates our algorithm updating/learning three bandits. The first figure shows the raw counts of pulls and wins, and the second figure is a dynamically updating plot. I encourage you to try to guess which bandit is optimal, prior to revealing the true probabilities, by selecting the `arm buttons`.\n\n\n```\nfrom IPython.core.display import HTML\n\n# try executing the below command twice if the first time doesn't work\nHTML(filename=\"BanditsD3.html\")\n```\n\n\n\n\n\n \n \n\n\n\n\n\n\n
\n
\n\n\n\n\n
\n \n \n \n
\n\n \n \n
\n\n
\n\n
\n\n
\n

Rewards

\n

0

\n
\n\n
\n

Pulls

\n

0

\n
\n\n
\n

Reward/Pull Ratio

\n

0

\n
\n\n
\n\n\n\n\n\n\nDeviations of the observed ratio from the highest probability is a measure of performance. For example,in the long run, optimally we can attain the reward/pull ratio of the maximum bandit probability. Long-term realized ratios less than the maximum represent inefficiencies. (Realized ratios larger than the maximum probability is due to randomness, and will eventually fall below). \n\n### A Measure of *Good*\n\nWe need a metric to calculate how well we are doing. Recall the absolute *best* we can do is to always pick the bandit with the largest probability of winning. Denote this best bandit's probability of $w_{opt}$. Our score should be relative to how well we would have done had we chosen the best bandit from the beginning. This motivates the *total regret* of a strategy, defined as:\n\n\\begin{align}\nR_T & = \\sum_{i=1}^{T} \\left( w_{opt} - w_{B(i)} \\right)\\\\\\\\\n& = Tw^* - \\sum_{i=1}^{T} \\; w_{B(i)} \n\\end{align}\n\n\nwhere $w_{B(i)}$ is the probability of a prize of the chosen bandit in the $i$th round. A total regret of 0 means the strategy is attaining the best possible score. This is likely not possible, as initially our algorithm will often make the wrong choice. Ideally, a strategy's total regret should flatten as it learns the best bandit. (Mathematically, we achieve $w_{B(i)}=w_{opt}$ often)\n\n\nBelow we plot the total regret of this simulation, including the scores of some other strategies:\n\n1. Random: randomly choose a bandit to pull. If you can't beat this, just stop. \n2. Largest Bayesian credible bound: pick the bandit with the largest upper bound in its 95% credible region of the underlying probability. \n3. Bayes-UCB algorithm: pick the bandit with the largest *score*, where score is a dynamic quantile of the posterior (see [4] )\n3. Mean of posterior: choose the bandit with the largest posterior mean. This is what a human player (sans computer) would likely do. \n3. Largest proportion: pick the bandit with the current largest observed proportion of winning. \n\nThe code for these are in the `other_strats.py`, where you can implement your own strategy very easily.\n\n\n```\nfigsize(12.5, 5)\nfrom other_strats import *\n\n# define a harder problem\nhidden_prob = np.array([0.15, 0.2, 0.1, 0.05])\nbandits = Bandits(hidden_prob)\n\n# define regret\n\n\ndef regret(probabilities, choices):\n w_opt = probabilities.max()\n return (w_opt - probabilities[choices.astype(int)]).cumsum()\n\n# create new strategies\nstrategies = [upper_credible_choice,\n bayesian_bandit_choice,\n ucb_bayes,\n max_mean,\n random_choice]\nalgos = []\nfor strat in strategies:\n algos.append(GeneralBanditStrat(bandits, strat))\n```\n\n\n```\n# train 10000 times\nfor strat in algos:\n strat.sample_bandits(10000)\n\n#test and plot\nfor i, strat in enumerate(algos):\n _regret = regret(hidden_prob, strat.choices)\n plt.plot(_regret, label=strategies[i].__name__, lw=3)\n\nplt.title(\"Total Regret of Bayesian Bandits Strategy vs. Random guessing\")\nplt.xlabel(\"Number of pulls\")\nplt.ylabel(\"Regret after $n$ pulls\");\nplt.legend(loc=\"upper left\");\n```\n\nLike we wanted, Bayesian bandits and other strategies have decreasing rates of regret, representing that we are achieving optimal choices. To be more scientific so as to remove any possible luck in the above simulation, we should instead look at the *expected total regret*:\n\n$$\\bar{R_T} = E[ R_T ] $$\n\nIt can be shown that any *sub-optimal* strategy's expected total regret is bounded below logarithmically. Formally:\n\n$$ E[R_T] = \\Omega \\left( \\;\\log(T)\\; \\right)$$\n\nThus, any strategy that matches logarithmic-growing regret is said to \"solve\" the Multi-Armed Bandit problem [3].\n\nUsing the Law of Large Numbers, we can approximate Bayesian Bandit's expected total regret by performing the same experiment many times (500 times, to be fair):\n\n\n```\n# this can be slow, so I recommend NOT running it.\n\ntrials = 500\nexpected_total_regret = np.zeros((10000, 3))\n\nfor i_strat, strat in enumerate(strategies[:-2]):\n for i in range(trials):\n general_strat = GeneralBanditStrat(bandits, strat)\n general_strat.sample_bandits(10000)\n _regret = regret(hidden_prob, general_strat.choices)\n expected_total_regret[:, i_strat] += _regret\n\n plt.plot(expected_total_regret[:, i_strat] / trials, lw=3, label=strat.__name__)\n# plot(expected_total_regret[:, i_strat] / trials, lw=3, label=strat.__name__)\n\nplt.title(\"Expected Total Regret of Multi-armed Bandit strategies\")\nplt.xlabel(\"Number of pulls\")\nplt.ylabel(\"Exepected Total Regret \\n after $n$ pulls\");\nplt.legend(loc=\"upper left\");\n```\n\n\n```\nplt.figure()\n[pl1, pl2, pl3] = plt.plot(expected_total_regret[:, [0, 1, 2]], lw=3)\nplt.xscale(\"log\")\nplt.legend([pl1, pl2, pl3],\n [\"Upper Credible Bound\", \"Bayesian Bandit\", \"UCB-Bayes\"],\n loc=\"upper left\")\nplt.ylabel(\"Exepected Total Regret \\n after $\\log{n}$ pulls\");\nplt.title(\"log-scale of above\");\nplt.ylabel(\"Exepected Total Regret \\n after $\\log{n}$ pulls\");\n```\n\n### Extending the algorithm \n\n\nBecause of the Bayesian Bandits algorithm's simplicity, it is easy to extend. Some possibilities are:\n\n- If interested in the *minimum* probability (eg: where prizes are a bad thing), simply choose $B = \\text{argmin} \\; X_b$ and proceed.\n\n- Adding learning rates: Suppose the underlying environment may change over time. Technically the standard Bayesian Bandit algorithm would self-update itself (awesome) by noting that what it thought was the best is starting to fail more often. We can motivate the algorithm to learn changing environments quicker by simply adding a *rate* term upon updating:\n\n self.wins[ choice ] = rate*self.wins[ choice ] + result\n self.trials[ choice ] = rate*self.trials[ choice ] + 1\n\n If `rate < 1`, the algorithm will *forget* its previous wins quicker and there will be a downward pressure towards ignorance. Conversely, setting `rate > 1` implies your algorithm will act more risky, and bet on earlier winners more often and be more resistant to changing environments. \n\n- Hierarchical algorithms: We can setup a Bayesian Bandit algorithm on top of smaller bandit algorithms. Suppose we have $N$ Bayesian Bandit models, each varying in some behavior (for example different `rate` parameters, representing varying sensitivity to changing environments). On top of these $N$ models is another Bayesian Bandit learner that will select a sub-Bayesian Bandit. This chosen Bayesian Bandit will then make an internal choice as to which machine to pull. The super-Bayesian Bandit updates itself depending on whether the sub-Bayesian Bandit was correct or not. \n\n- Extending the rewards, denoted $y_a$ for bandit $a$, to random variables from a distribution $f_{y_a}(y)$ is straightforward. More generally, this problem can be rephrased as \"Find the bandit with the largest expected value\", as playing the bandit with the largest expected value is optimal. In the case above, $f_{y_a}$ was Bernoulli with probability $p_a$, hence the expected value for a bandit is equal to $p_a$, which is why it looks like we are aiming to maximize the probability of winning. If $f$ is not Bernoulli, and it is non-negative, which can be accomplished apriori by shifting the distribution (we assume we know $f$), then the algorithm behaves as before:\n\n For each round, \n \n 1. Sample a random variable $X_b$ from the prior of bandit $b$, for all $b$.\n 2. Select the bandit with largest sample, i.e. select bandit $B = \\text{argmax}\\;\\; X_b$.\n 3. Observe the result,$R \\sim f_{y_b}$, of pulling bandit $B$, and update your prior on bandit $B$.\n 4. Return to 1\n\n The issue is in the sampling of the $X_b$ drawing phase. With Beta priors and Bernoulli observations, we have a Beta posterior — this is easy to sample from. But now, with arbitrary distributions $f$, we have a non-trivial posterior. Sampling from these can be difficult.\n\n- There has been some interest in extending the Bayesian Bandit algorithm to commenting systems. Recall in Chapter 4, we developed a ranking algorithm based on the Bayesian lower-bound of the proportion of upvotes to the total number of votes. One problem with this approach is that it will bias the top rankings towards older comments, since older comments naturally have more votes (and hence the lower-bound is tighter to the true proportion). This creates a positive feedback cycle where older comments gain more votes, hence are displayed more often, hence gain more votes, etc. This pushes any new, potentially better comments, towards the bottom. J. Neufeld proposes a system to remedy this that uses a Bayesian Bandit solution.\n\nHis proposal is to consider each comment as a Bandit, with the number of pulls equal to the number of votes cast, and number of rewards as the number of upvotes, hence creating a $\\text{Beta}(1+U,1+D)$ posterior. As visitors visit the page, samples are drawn from each bandit/comment, but instead of displaying the comment with the $\\max$ sample, the comments are ranked according to the ranking of their respective samples. From J. Neufeld's blog [7]:\n\n > [The] resulting ranking algorithm is quite straightforward, each new time the comments page is loaded, the score for each comment is sampled from a $\\text{Beta}(1+U,1+D)$, comments are then ranked by this score in descending order... This randomization has a unique benefit in that even untouched comments $(U=0,D=0)$ have some chance of being seen even in threads with 5000+ comments (something that is not happening now), but, at the same time, the user is not likely to be inundated with rating these new comments. \n\nJust for fun, though the colors explode, we watch the Bayesian Bandit algorithm learn 35 different options. \n\n\n```\nfigsize(12.0, 8)\nbeta = stats.beta\nhidden_prob = beta.rvs(1, 13, size=35)\nprint hidden_prob\nbandits = Bandits(hidden_prob)\nbayesian_strat = BayesianStrategy(bandits)\n\nfor j, i in enumerate([100, 200, 500, 1300]):\n plt.subplot(2, 2, j + 1)\n bayesian_strat.sample_bandits(i)\n plot_priors(bayesian_strat, hidden_prob, lw=2, alpha=0.0, plt_vlines=False)\n # plt.legend()\n plt.xlim(0, 0.5)\n```\n\n## Eliciting expert prior\n\nSpecifying a subjective prior is how practitioners incorporate domain knowledge about the problem into our mathematical framework. Allowing domain knowledge is useful for many reasons, for example:\n\n- Aids the speed of MCMC convergence. For example, if we know the unknown parameter is strictly positive, then we can restrict our attention there, hence saving time that would otherwise be spent exploring negative values.\n- More accurate inference. By weighing prior values near the true unknown value higher, we are narrowing our eventual inference (by making the posterior tighter around the unknown) \n- Express our uncertainty better. See the *Price is Right* problem in Chapter 5.\n\nOf course, practitioners of Bayesian methods are not experts in every field, so we must turn to domain experts to craft our priors. We must be careful with how we elicit these priors though. Some things to consider:\n\n1. From experience, I would avoid introducing Betas, Gammas, etc. to non-Bayesian practitioners. Furthermore, non-statisticians can get tripped up by how a continuous probability function can have a value exceeding one.\n\n2. Individuals often neglect the rare *tail-events* and put too much weight around the mean of distribution. \n\n3. Related to above is that almost always individuals will under-emphasize the uncertainty in their guesses.\n\nEliciting priors from non-technical experts is especially difficult. Rather than introduce the notion of probability distributions, priors, etc. that may scare an expert, there is a much simpler solution. \n\n###Trial roulette method \n\n\nThe *trial roulette method* [8] focuses on building a prior distribution by placing counters (think casino chips) on what the expert thinks are possible outcomes. The expert is given $N$ counters (say $N=20$) and is asked to place them on a pre-printed grid, with bins representing intervals. Each column would represent their belief of the probability of getting the corresponding bin result. Each chip would represent an $\\frac{1}{N} = 0.05$ increase in the probability of the outcome being in that interval. For example [9]:\n\n> A student is asked to predict the mark in a future exam. The figure below shows a completed grid for the elicitation of a subjective probability distribution. The horizontal axis of the grid shows the possible bins (or mark intervals) that the student was asked to consider. The numbers in top row record the number of chips per bin. The completed grid (using a total of 20 chips) shows that the student believes there is a 30% chance that the mark will be between 60 and 64.9.\n\n\n\n\nFrom this, we can fit a distribution that captures the expert's choice. Some reasons in favor of using this technique are:\n\n1. Many questions about the shape of the expert's subjective probability distribution can be answered without the need to pose a long series of questions to the expert - the statistician can simply read off the density above or below any given point, or that between any two points.\n\n2. During the elicitation process, the experts can move around the chips if unsatisfied with the way they placed them initially - thus they can be sure of the final result to be submitted.\n\n3. It forces the expert to be coherent in the set of probabilities that are provided. If all the chips are used, the probabilities must sum to one.\n\n4. Graphical methods seem to provide more accurate results, especially for participants with modest levels of statistical sophistication.\n\n##### Example: Stock Returns\n\n\nTake note stock brokers: you're doing it wrong. When choosing which stocks to pick, an analyst will often look at the *daily return* of the stock. Suppose $S_t$ is the price of the stock on day $t$, then the daily return on day $t$ is :\n\n$$r_t = \\frac{ S_t - S_{t-1} }{ S_{t-1} } $$\n\nThe *expected daily return* of a stock is denoted $\\mu = E[ r_t ] $. Obviously, stocks with high expected returns are desirable. Unfortunately, stock returns are so filled with noise that it is very hard to estimate this parameter. Furthermore, the parameter might change over time (consider the rises and falls of AAPL stock), hence it is unwise to use a large historical dataset. \n\nHistorically, the expected return has been estimated by using the sample mean. This is a bad idea. As mentioned, the sample mean of a small sized dataset has enormous potential to be very wrong (again, see Chapter 4 for full details). Thus Bayesian inference is the correct procedure here, since we are able to see our uncertainty along with probable values.\n\nFor this exercise, we will be examining the daily returns of the AAPL, GOOG, MSFT and AMZN. Before we pull in the data, suppose we ask our a stock fund manager (an expert in finance, but see [10] ), \n\n> What do you think the return profile looks like for each of these companies?\n\nOur stock broker, without needing to know the language of Normal distributions, or priors, or variances, etc. creates four distributions using the trial roulette method above. Suppose they look enough like Normals, so we fit Normals to them. They may look like: \n\n\n```\nfigsize(11., 5)\ncolors = [\"#348ABD\", \"#A60628\", \"#7A68A6\", \"#467821\"]\n\nnormal = stats.norm\nx = np.linspace(-0.15, 0.15, 100)\n\nexpert_prior_params = {\"AAPL\": (0.05, 0.03),\n \"GOOG\": (-0.03, 0.04),\n \"TSLA\": (-0.02, 0.01),\n \"AMZN\": (0.03, 0.02),\n }\n\nfor i, (name, params) in enumerate(expert_prior_params.iteritems()):\n plt.subplot(2, 2, i)\n y = normal.pdf(x, params[0], scale=params[1])\n #plt.plot( x, y, c = colors[i] )\n plt.fill_between(x, 0, y, color=colors[i], linewidth=2,\n edgecolor=colors[i], alpha=0.6)\n plt.title(name + \" prior\")\n plt.vlines(0, 0, y.max(), \"k\", \"--\", linewidth=0.5)\n plt.xlim(-0.15, 0.15)\nplt.tight_layout()\n```\n\nNote that these are subjective priors: the expert has a personal opinion on the stock returns of each of these companies, and is expressing them in a distribution. He's not wishful thinking -- he's introducing domain knowledge.\n\nIn order to better model these returns, we should investigate the *covariance matrix* of the returns. For example, it would be unwise to invest in two stocks that are highly correlated, since they are likely to tank together (hence why fund managers suggest a diversification strategy). We will use the *Wishart distribution* for this, introduced earlier.\n\n\n```\nimport pymc as pm\n\nn_observations = 100 # we will truncate the the most recent 100 days.\n\nprior_mu = np.array([x[0] for x in expert_prior_params.values()])\nprior_std = np.array([x[1] for x in expert_prior_params.values()])\n\ninv_cov_matrix = pm.Wishart(\"inv_cov_matrix\", n_observations, np.diag(prior_std ** 2))\nmu = pm.Normal(\"returns\", prior_mu, 1, size=4)\n```\n\nNext we pull historical data for these stocks:\n\n\n```\n# I wish I could have used Pandas as a prereq for this book, but oh well.\nimport datetime\nimport ystockquote as ysq\n\nstocks = [\"AAPL\", \"GOOG\", \"TSLA\", \"AMZN\"]\n\nenddate = datetime.datetime.now().strftime(\"%Y-%m-%d\") # today's date.\nstartdate = \"2012-09-01\"\n\nstock_closes = {}\nstock_returns = {}\nCLOSE = 6\n\nfor stock in stocks:\n x = np.array(ysq.get_historical_prices(stock, startdate, enddate))\n stock_closes[stock] = x[1:, CLOSE].astype(float)\n\n# create returns:\n\nfor stock in stocks:\n _previous_day = np.roll(stock_closes[stock], -1)\n stock_returns[stock] = ((stock_closes[stock] - _previous_day) / _previous_day)[:n_observations]\n\ndates = map(lambda x: datetime.datetime.strptime(x, \"%Y-%m-%d\"), x[1:n_observations + 1, 0])\n```\n\n\n```\nfigsize(12.5, 4)\n\nfor _stock, _returns in stock_returns.iteritems():\n p = plt.plot((1 + _returns)[::-1].cumprod() - 1, '-o', label=\"%s\" % _stock,\n markersize=4, markeredgecolor=\"none\")\n\nplt.xticks(np.arange(100)[::-8],\n map(lambda x: datetime.datetime.strftime(x, \"%Y-%m-%d\"), dates[::8]),\n rotation=60);\n\nplt.legend(loc=\"upper left\")\nplt.title(\"Return space\")\nplt.ylabel(\"Return of $1 on first date, x100%\");\n```\n\n\n```\nfigsize(11., 5)\nreturns = np.zeros((n_observations, 4))\n\nfor i, (_stock, _returns) in enumerate(stock_returns.iteritems()):\n returns[:, i] = _returns\n plt.subplot(2, 2, i)\n plt.hist(_returns, bins=20,\n normed=True, histtype=\"stepfilled\",\n color=colors[i], alpha=0.7)\n plt.title(_stock + \" returns\")\n plt.xlim(-0.15, 0.15)\n\nplt.tight_layout()\nplt.suptitle(\"Histogram of daily returns\", size=14);\n```\n\nBelow we perform the inference on the posterior mean return and posterior covariance matrix. \n\n\n```\nobs = pm.MvNormal(\"observed returns\", mu, inv_cov_matrix, observed=True, value=returns)\n\nmodel = pm.Model([obs, mu, inv_cov_matrix])\nmcmc = pm.MCMC()\n\nmcmc.sample(150000, 100000, 3)\n```\n\n [****************100%******************] 150000 of 150000 complete\n\n\n\n```\nfigsize(12.5, 4)\n\n# examine the mean return first.\nmu_samples = mcmc.trace(\"returns\")[:]\n\nfor i in range(4):\n plt.hist(mu_samples[:, i], alpha=0.8 - 0.05 * i, bins=30,\n histtype=\"stepfilled\", normed=True,\n label=\"%s\" % stock_returns.keys()[i])\n\nplt.vlines(mu_samples.mean(axis=0), 0, 500, linestyle=\"--\", linewidth=.5)\n\nplt.title(\"Posterior distribution of $\\mu$, daily stock returns\")\nplt.legend();\n```\n\n(Plots like these are what inspired the book's cover.)\n\nWhat can we say about the results above? Clearly TSLA has been a strong performer, and our analysis suggests that it has an almost 1% daily return! Similarly, most of the distribution of AAPL is negative, suggesting that it's *true daily return* is negative.\n\n\nYou may not have immediately noticed, but these variables are a whole order of magnitude *less* than our priors on them. For example, to put these one the same scale as the above prior distributions:\n\n\n```\nfigsize(11.0, 3)\nfor i in range(4):\n plt.subplot(2, 2, i + 1)\n plt.hist(mu_samples[:, i], alpha=0.8 - 0.05 * i, bins=30,\n histtype=\"stepfilled\", normed=True, color=colors[i],\n label=\"%s\" % stock_returns.keys()[i])\n plt.title(\"%s\" % stock_returns.keys()[i])\n plt.xlim(-0.15, 0.15)\n\nplt.suptitle(\"Posterior distribution of daily stock returns\")\nplt.tight_layout()\n```\n\nWhy did this occur? Recall how I mentioned that finance has a very very low signal to noise ratio. This implies an environment where inference is much more difficult. One should be careful about over-interpreting these results: notice (in the first figure) that each distribution is positive at 0, implying that the stock may return nothing. Furthermore, the subjective priors influenced the results. From the fund managers point of view, this is good as it reflects his updated beliefs about the stocks, whereas from a neutral viewpoint this can be too subjective of a result. \n\nBelow we show the posterior correlation matrix, and posterior standard deviations. An important caveat to know is that the Wishart distribution models the *inverse covariance matrix*, so we must invert it to get the covariance matrix. We also normalize the matrix to acquire the *correlation matrix*. Since we cannot plot hundreds of matrices effectively, we settle by summarizing the posterior distribution of correlation matrices by showing the *mean posterior correlation matrix* (defined on line 2).\n\n\n```\ninv_cov_samples = mcmc.trace(\"inv_cov_matrix\")[:]\nmean_covariance_matrix = np.linalg.inv(inv_cov_samples.mean(axis=0))\n\n\ndef cov2corr(A):\n \"\"\"\n covariance matrix to correlation matrix.\n \"\"\"\n d = np.sqrt(A.diagonal())\n A = ((A.T / d).T) / d\n #A[ np.diag_indices(A.shape[0]) ] = np.ones( A.shape[0] )\n return A\n\n\nplt.subplot(1, 2, 1)\nplt.imshow(cov2corr(mean_covariance_matrix), interpolation=\"none\",\n cmap=plt.cm.hot)\nplt.xticks(np.arange(4), stock_returns.keys())\nplt.yticks(np.arange(4), stock_returns.keys())\nplt.colorbar(orientation=\"vertical\")\nplt.title(\"(mean posterior) Correlation Matrix\")\n\nplt.subplot(1, 2, 2)\nplt.bar(np.arange(4), np.sqrt(np.diag(mean_covariance_matrix)),\n color=\"#348ABD\", alpha=0.7)\nplt.xticks(np.arange(4) + 0.5, stock_returns.keys());\nplt.title(\"(mean posterior) variances of daily stock returns\")\n\nplt.tight_layout();\n```\n\nLooking at the above figures, we can say that it is likely that TSLA has an above-average volatility (looking at the return graph this is quite clear). The correlation matrix shows that there are no strong correlations present, but perhaps GOOG and AMZN express a higher correlation (about 0.30). \n\nWith this Bayesian analysis of the stock market, we can throw it into a Mean-Variance optimizer (which I cannot stress enough to not use with frequentist point estimates) and find the minimum. This optimizer balances the tradeoff between a high return and high variance.\n\n$$ w_{opt} = \\min_{w} \\frac{1}{N}\\left( \\sum_{i=0}^N \\mu_i^T w - \\frac{\\lambda}{2}w^T\\Sigma_i w \\right)$$\n\nwhere $\\mu_i$ and $\\Sigma_i$ are the $i$th posterior estimate of the mean returns and the covariance matrix. This is another example of loss function optimization.\n\n### Protips for the Wishart distribution\n\nIf you plan to be using the Wishart distribution, read on. Else, feel free to skip this. \n\nIn the problem above, the Wishart distribution behaves pretty nicely. Unfortunately, this is rarely the case. The problem is that estimating an $NxN$ covariance matrix involves estimating $\\frac{1}{2}N(N-1)$ unknowns. This is a large number even for a modest $N$. Personally, I've tried performing a similar simulation as above with $N = 23$ stocks, and ended up giving considering that I was requesting my MCMC simulation to estimate at least $\\frac{1}{2}23*22 = 253$ additional unknowns (plus the other interesting unknowns in the problem). This is not easy for MCMC. Essentially, you are asking you MCMC to traverse a 250+ dimensional space. And the problem seemed so innocent initially! Below are some tips, in order of supremacy:\n\n1. Use conjugancy if it applies. See section below.\n\n2. Use a good starting value. What might be a good starting value? Why, the data's sample covariance matrix is! Note that this is not empirical Bayes: we are not touching the prior's parameters, we are modifying the starting value of the MCMC. Due to numerical instability, it is best to truncate the floats in the sample covariance matrix down a few degrees of precision (e.g. instability can cause unsymmetrical matrices, which can cause PyMC to cry.). \n\n3. Provide as much domain knowledge in the form of priors, if possible. I stress *if possible*. It is likely impossible to have an estimate about each $\\frac{1}{2}N(N-1)$ unknown. In this case, see number 4.\n\n4. Use empirical Bayes, i.e. use the sample covariance matrix as the prior's parameter.\n\n5. For problems where $N$ is very large, nothing is going to help. Instead, ask, do I really care about *every* correlation? Probably not. Furthermore ask yourself, do I really really care about correlations? Possibly not. In finance, we can set an informal hierarchy of what we might be interested in the most: first a good estimate of $\\mu$, the variances along the diagonal of the covariance matrix are secondly important, and finally the correlations are least important. So, it might be better to ignore the $\\frac{1}{2}(N-1)(N-2)$ correlations and instead focus on the more important unknowns.\n\n\n## Conjugate Priors\n\nRecall that a $\\text{Beta}$ prior with $\\text{Binomial}$ data implies a $\\text{Beta}$ posterior. Graphically:\n\n$$ \\underbrace{\\text{Beta}}_{\\text{prior}} \\cdot \\overbrace{\\text{Binomial}}^{\\text{data}} = \\overbrace{\\text{Beta}}^{\\text{posterior} } $$ \n\nNotice the $\\text{Beta}$ on both sides of this equation (no, you cannot cancel them, this is not a *real* equation). This is a really useful property. It allows us to avoid using MCMC, since the posterior is known in closed form. Hence inference and analytics are easy to derive. This shortcut was the heart of the Bayesian Bandit algorithm above. Fortunately, there is an entire family of distributions that have similar behaviour. \n\nSuppose $X$ comes from, or is believed to come from, a well-known distribution, call it $f_{\\alpha}$, where $\\alpha$ are possibly unknown parameters of $f$. $f$ could be a Normal distribution, or Binomial distribution, etc. For particular distributions $f_{\\alpha}$, there may exist a prior distribution $p_{\\beta}$, such that:\n\n$$ \\overbrace{p_{\\beta}}^{\\text{prior}} \\cdot \\overbrace{f_{\\alpha}(X)}^{\\text{data}} = \\overbrace{p_{\\beta'}}^{\\text{posterior} } $$ \n\nwhere $\\beta'$ is a different set of parameters *but $p$ is the same distribution as the prior*. A prior $p$ that satisfies this relationship is called a *conjugate prior*. As I mentioned, they are useful computationally, as we can avoided approximate inference using MCMC and go directly to the posterior. This sounds great, right?\n\nUnfortunately, not quite. There are a few issues with conjugate priors.\n\n1. The conjugate prior is not objective. Hence it is only useful when a subjective prior is required. It is not guaranteed that the conjugate prior can accommodate the practitioner's subjective opinion.\n\n2. There typically exist conjugate priors for simple, one dimensional problems. For larger problems, involving more complicated structures, hope is lost to find a conjugate prior. For smaller models, Wikipedia has a nice [table of conjugate priors](http://en.wikipedia.org/wiki/Conjugate_prior#Table_of_conjugate_distributions).\n\nReally, conjugate priors are only useful for their mathematical convenience: it is simple to go from prior to posterior. I personally see conjugate priors as only a neat mathematical trick, and offer little insight into the problem at hand. \n\n## Jefferys Priors\n\nEarlier, we talked about objective priors rarely being *objective*. Partly what we mean by this is that we want a prior that doesn't bias our posterior estimates. The flat prior seems like a reasonable choice as it assigns equal probability to all values. \n\nBut the flat prior is not transformation invariant. What does this mean? Suppose we have a random variable $ \\bf X $ from Bernoulli($\\theta$). We define the prior on $p(\\theta) = 1$. \n\n\n```\nfigsize(12.5, 5)\n\nx = np.linspace(0.000, 1, 150)\ny = np.linspace(1.0, 1.0, 150)\nlines = plt.plot(x, y, color=\"#A60628\", lw=3)\nplt.fill_between(x, 0, y, alpha=0.2, color=lines[0].get_color())\nplt.autoscale(tight=True)\nplt.ylim(0, 2);\n```\n\nNow, let's transform $\\theta$ with the function $\\psi = log \\frac{\\theta}{1-\\theta}$. This is just a function to stretch $\\theta$ across the real line. Now how likely are different values of $\\psi$ under our transformation.\n\n\n```\nfigsize(12.5, 5)\n\npsi = np.linspace(-10, 10, 150)\ny = np.exp(psi) / (1 + np.exp(psi)) ** 2\nlines = plt.plot(psi, y, color=\"#A60628\", lw=3)\nplt.fill_between(psi, 0, y, alpha=0.2, color=lines[0].get_color())\nplt.autoscale(tight=True)\nplt.ylim(0, 1);\n```\n\nOh no! Our function is no longer flat. It turns out flat priors do carry information in them after all. The point of Jeffreys Priors is to create priors that don't accidentally become informative when you transform the variables you placed them originally on.\n\nJeffreys Priors are defined as:\n\n$$p_J(\\theta) \\propto \\mathbf{I}(\\theta)^\\frac{1}{2}$$\n$$\\mathbf{I}(\\theta) = - \\mathbb{E}\\bigg[\\frac{d^2 \\text{ log } p(X|\\theta)}{d\\theta^2}\\bigg]$$\n\n$\\mathbf{I}$ being the *Fisher information*\n\n##Effect of the prior as $N$ increases\n\nIn the first chapter, I proposed that as the amount of observations, or data, that we posses, the less the prior matters. This is intuitive. After all, our prior is based on previous information, and eventually enough new information will shadow our previous information's value. The smothering of the prior by enough data is also helpful: if our prior is significantly wrong, then the self-correcting nature of the data will present to us a *less wrong*, and eventually *correct*, posterior. \n\nWe can see this mathematically. First, recall Bayes Theorem from Chapter 1 that relates the prior to the posterior. The following is a sample from [What is the relationship between sample size and the influence of prior on posterior?](http://stats.stackexchange.com/questions/30387/what-is-the-relationship-between-sample-size-and-the-influence-of-prior-on-poste)[1] on CrossValidated.\n\n>The posterior distribution for a parameter $\\theta$, given a data set ${\\bf X}$ can be written as \n\n$$p(\\theta | {\\bf X}) \\propto \\underbrace{p({\\bf X} | \\theta)}_{{\\rm likelihood}} \\cdot \\overbrace{ p(\\theta) }^{ {\\rm prior} } $$\n\n\n\n>or, as is more commonly displayed on the log scale, \n\n$$ \\log( p(\\theta | {\\bf X}) ) = c + L(\\theta;{\\bf X}) + \\log(p(\\theta)) $$\n\n>The log-likelihood, $L(\\theta;{\\bf X}) = \\log \\left( p({\\bf X}|\\theta) \\right)$, **scales with the sample size**, since it is a function of the data, while the prior density does not. Therefore, as the sample size increases, the absolute value of $L(\\theta;{\\bf X})$ is getting larger while $\\log(p(\\theta))$ stays fixed (for a fixed value of $\\theta$), thus the sum $L(\\theta;{\\bf X}) + \\log(p(\\theta))$ becomes more heavily influenced by $L(\\theta;{\\bf X})$ as the sample size increases. \n\nThere is an interesting consequence not immediately apparent. As the sample size increases, the chosen prior has less influence. Hence inference converges regardless of chosen prior, so long as the areas of non-zero probabilities are the same. \n\nBelow we visualize this. We examine the convergence of two posteriors of a Binomial's parameter $\\theta$, one with a flat prior and the other with a biased prior towards 0. As the sample size increases, the posteriors, and hence the inference, converge.\n\n\n```\nfigsize(12.5, 15)\n\np = 0.6\nbeta1_params = np.array([1., 1.])\nbeta2_params = np.array([2, 10])\nbeta = stats.beta\n\nx = np.linspace(0.00, 1, 125)\ndata = pm.rbernoulli(p, size=500)\n\nplt.figure()\nfor i, N in enumerate([0, 4, 8, 32, 64, 128, 500]):\n s = data[:N].sum()\n plt.subplot(8, 1, i + 1)\n params1 = beta1_params + np.array([s, N - s])\n params2 = beta2_params + np.array([s, N - s])\n y1, y2 = beta.pdf(x, *params1), beta.pdf(x, *params2)\n plt.plot(x, y1, label=r\"flat prior\", lw=3)\n plt.plot(x, y2, label=\"biased prior\", lw=3)\n plt.fill_between(x, 0, y1, color=\"#348ABD\", alpha=0.15)\n plt.fill_between(x, 0, y2, color=\"#A60628\", alpha=0.15)\n plt.legend(title=\"N=%d\" % N)\n plt.vlines(p, 0.0, 7.5, linestyles=\"--\", linewidth=1)\n #plt.ylim( 0, 10)#\n```\n\nKeep in mind, not all posteriors will \"forget\" the prior this quickly. This example was just to show that *eventually* the prior is forgotten. The \"forgetfulness\" of the prior as we become awash in more and more data is the reason why Bayesian and Frequentist inference eventually converge as well.\n\n### Bayesian perspective of Penalized Linear Regressions\n\nThere is a very interesting relationship between a penalized least-squares regression and Bayesian priors. A penalized linear regression is a optimization problem of the form:\n\n$$ \\text{argmin}_{\\beta} \\;\\; (Y - X\\beta)^T(Y - X\\beta) + f(\\beta)$$\n\nfor some function $f$ (typically a norm like $|| \\cdot ||_p^p$). \n\nWe will first describe the probabilistic interpretation of least-squares linear regression. Denote our response variable $Y$, and features are contained in the data matrix $X$. The standard linear model is:\n\n\\begin{equation}\nY = X\\beta + \\epsilon\n\\end{equation}\n\nwhere $\\epsilon \\sim \\text{Normal}( {\\bf 0}, \\sigma{\\bf I })$. Simply, the observed $Y$ is a linear function of $X$ (with coefficients $\\beta$) plus some noise term. Our unknown to be determined is $\\beta$. We use the following property of Normal random variables:\n\n$$ \\mu' + \\text{Normal}( \\mu, \\sigma ) \\sim \\text{Normal}( \\mu' + \\mu , \\sigma ) $$\n\nto rewrite the above linear model as:\n\n\\begin{align}\n& Y = X\\beta + \\text{Normal}( {\\bf 0}, \\sigma{\\bf I }) \\\\\\\\\n& Y = \\text{Normal}( X\\beta , \\sigma{\\bf I }) \\\\\\\\\n\\end{align}\n\nIn probabilistic notation, denote $f_Y(y \\; | \\; \\beta )$ the probability distribution of $Y$, and recalling the density function for a Normal random variable (see [here](http://en.wikipedia.org/wiki/Normal_distribution) ):\n\n$$ f_Y( Y \\; |\\; \\beta, X) = L(\\beta|\\; X,Y)= \\frac{1}{\\sqrt{ 2\\pi\\sigma} } \\exp \\left( \\frac{1}{2\\sigma^2} (Y - X\\beta)^T(Y - X\\beta) \\right) $$\n\nThis is the likelihood function for $\\beta$. Taking the $\\log$:\n\n$$ \\ell(\\beta) = K - c(Y - X\\beta)^T(Y - X\\beta) $$\n\nwhere $K$ and $c>0$ are constants. Maximum likelihood techniques wish to maximize this for $\\beta$, \n\n$$\\hat{ \\beta } = \\text{argmax}_{\\beta} \\;\\; - (Y - X\\beta)^T(Y - X\\beta) $$\n\nEquivalently we can *minimize the negative* of the above:\n\n$$\\hat{ \\beta } = \\text{argmin}_{\\beta} \\;\\; (Y - X\\beta)^T(Y - X\\beta) $$\n\nThis is the familiar least-squares linear regression equation. Therefore we showed that the solution to a linear least-squares is the same as the maximum likelihood assuming Normal noise. Next we extend this to show how we can arrive at penalized linear regression by a suitable choice of prior on $\\beta$. \n\n#### Penalized least-squares\n\nIn the above, once we have the likelihood, we can include a prior distribution on $\\beta$ to derive to the equation for the posterior distribution:\n\n$$P( \\beta | Y, X ) = L(\\beta|\\;X,Y)p( \\beta )$$\n\nwhere $p(\\beta)$ is a prior on the elements of $\\beta$. What are some interesting priors? \n\n1\\. If we include *no explicit* prior term, we are actually including an uninformative prior, $P( \\beta ) \\propto 1$, think of it as uniform over all numbers. \n\n2\\. If we have reason to believe the elements of $\\beta$ are not too large, we can suppose that *a priori*:\n\n$$ \\beta \\sim \\text{Normal}({\\bf 0 }, \\lambda {\\bf I } ) $$\n\nThe resulting posterior density function for $\\beta$ is *proportional to*:\n\n$$ \\exp \\left( \\frac{1}{2\\sigma^2} (Y - X\\beta)^T(Y - X\\beta) \\right) \\exp \\left( \\frac{1}{2\\lambda^2} \\beta^T\\beta \\right) $$\n\nand taking the $\\log$ of this, and combining and redefining constants, we arrive at:\n\n$$ \\ell(\\beta) \\propto K - (Y - X\\beta)^T(Y - X\\beta) - \\alpha \\beta^T\\beta $$\n\nwe arrive at the function we wish to maximize (recall the point that maximizes the posterior distribution is the MAP, or *maximum a posterior*):\n\n$$\\hat{ \\beta } = \\text{argmax}_{\\beta} \\;\\; -(Y - X\\beta)^T(Y - X\\beta) - \\alpha \\;\\beta^T\\beta $$\n\nEquivalently, we can minimize the negative of the above, and rewriting $\\beta^T \\beta = ||\\beta||_2^2$:\n\n$$\\hat{ \\beta } = \\text{argmin}_{\\beta} \\;\\; (Y - X\\beta)^T(Y - X\\beta) + \\alpha \\;||\\beta||_2^2$$\n\nThis above term is exactly Ridge Regression. Thus we can see that ridge regression corresponds to the MAP of a linear model with Normal errors and a Normal prior on $\\beta$.\n\n3\\. Similarly, if we assume a *Laplace* prior on $\\beta$, ie. \n\n$$ f_\\beta( \\beta) \\propto \\exp \\left(- \\lambda ||\\beta||_1 \\right)$$\n\nand following the same steps as above, we recover:\n\n$$\\hat{ \\beta } = \\text{argmin}_{\\beta} \\;\\; (Y - X\\beta)^T(Y - X\\beta) + \\alpha \\;||\\beta||_1$$\n\nwhich is LASSO regression. Some important notes about this equivalence. The sparsity that is a result of using a LASSO regularization is not a result of the prior assigning high probability to sparsity. Quite the opposite actually. It is the combination of the $|| \\cdot ||_1$ function and using the MAP that creates sparsity on $\\beta$: [purely a geometric argument](http://camdp.com/blogs/least-squares-regression-l1-penalty). The prior does contribute to an overall shrinking of the coefficients towards 0 though. An interesting discussion of this can be found in [2].\n\nFor an example of Bayesian linear regression, see Chapter 4's example on financial losses.\n\n##### References\n\n1. Macro, . \"What is the relationship between sample size and the influence of prior on posterior?.\" 13 Jun 2013. StackOverflow, Online Posting to Cross-Validated. Web. 25 Apr. 2013.\n\n2. Starck, J.-L., , et al. \"Sparsity and the Bayesian Perspective.\" Astronomy & Astrophysics. (2013): n. page. Print.\n\n3. Kuleshov, Volodymyr, and Doina Precup. \"Algorithms for the multi-armed bandit problem.\" Journal of Machine Learning Research. (2000): 1-49. Print.\n\n4. Gelman, Andrew. \"Prior distributions for variance parameters in hierarchical models.\" Bayesian Analysis. 1.3 (2006): 515-533. Print.\n\n5. Gelman, Andrew, and Cosma R. Shalizi. \"Philosophy and the practice of Bayesian statistics.\" British Journal of Mathematical and Statistical Psychology. (2012): n. page. Web. 17 Apr. 2013.\n\n6. http://jmlr.csail.mit.edu/proceedings/papers/v22/kaufmann12/kaufmann12.pdf\n\n7. James, Neufeld. \"Reddit's \"best\" comment scoring algorithm as a multi-armed bandit task.\" Simple ML Hacks. Blogger, 09 Apr 2013. Web. 25 Apr. 2013.\n\n8. Oakley, J. E., Daneshkhah, A. and O’Hagan, A. Nonparametric elicitation using the roulette method. Submitted to Bayesian Analysis.\n\n9. \"Eliciting priors from experts.\" 19 Jul 2010. StackOverflow, Online Posting to Cross-Validated. Web. 1 May. 2013. .\n\n10. Taleb, Nassim Nicholas (2007), The Black Swan: The Impact of the Highly Improbable, Random House, ISBN 978-1400063512\n\n\n```\nfrom IPython.core.display import HTML\n\n\ndef css_styling():\n styles = open(\"../styles/custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()\n```\n\n\n\n\n\n\n\n\n\n\n\n```\n\n```\n", "meta": {"hexsha": "e4dcf898f0f85738e4c4853edd4c86e260c9b89c", "size": 909588, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter6_Priorities/Priors.ipynb", "max_stars_repo_name": "brianzhang01/Bayesian-Methods-for-Hackers", "max_stars_repo_head_hexsha": "f0ce2a6d35ac5a839c89b306ab5bda603e2f31bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-02-28T06:01:33.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-04T02:32:34.000Z", "max_issues_repo_path": "Chapter6_Priorities/Priors.ipynb", "max_issues_repo_name": "brianzhang01/Bayesian-Methods-for-Hackers", "max_issues_repo_head_hexsha": "f0ce2a6d35ac5a839c89b306ab5bda603e2f31bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter6_Priorities/Priors.ipynb", "max_forks_repo_name": "brianzhang01/Bayesian-Methods-for-Hackers", "max_forks_repo_head_hexsha": "f0ce2a6d35ac5a839c89b306ab5bda603e2f31bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-06-04T21:46:21.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-04T21:46:21.000Z", "avg_line_length": 506.4521158129, "max_line_length": 166499, "alphanum_fraction": 0.9151143155, "converted": true, "num_tokens": 16978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091957, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.24417149706988217}} {"text": "# Parameter Selection for the Functionally Assembled Terrestrial Ecosystem Simulator (FATES)\n\n__Summary__
\nNumerical models that simulate tropical forest ecosystem dynamics, such as the Functionally Assembled Terrestrial Ecosystem Simulator (FATES), have been proposed as a way to improve projections of future climate change. However, parameterizing these complex, process-based models is challenging due to their numerous and interconnected non-linear relationships and relatively long spin-up requirements. This analysis identifies three high-performing parameter sets for use in future FATES experiments by quantitatively evaluating the performance of nearly 600 simulations, which test 300 unique parameter sets in two different background environments, against diverse observations at a tropical forest test site.\n\n__Motivation__
\nGreenhouse gas emissions from human activities are warming the Earth with potentially catastrophic implications for human health. Predicting twenty-first century warming is critical to climate change mitigation and adaptation efforts. Unfortunately, the numerical models used to project future climate differ in their predictions of warming even for the same greenhouse gas emissions scenario. This variability in projections across models stems largely from uncertainty about how Earth's vegetation will respond to environmental change. In particular, predictions of tropical forest responses to climate change must be improved, as these forests exert strong control over global climate. Numerical, process-based models of vegetated ecosystem dynamics, such as the Functionally Assembled Terrestrial Ecosystem Simulator (FATES; Fisher et al., 2015, 2018), have been proposed as a way of improving projections of tropical forests and thus future climate. However, parameterizing these complex, process-based models remains challenging due to their numerous interconnected, non-linear relationships and long spin-up requirements.\n\n__Goal__
\nThe goal of this analysis is to identify parameter sets that allow the FATES model to best match observations of tropical forest structure and functioning at a test site.\n\n__Methods__
\nThis analysis identifies three high-performing parameter sets for use in future FATES experiments by quantitatively evaluating the performance of nearly 600 simulations, which test nearly 300 unique parameter sets in two different background environments, against diverse observations at a tropical forest test site.\n\n_Parameter ensemble simulations_
\nPrior to this analysis, we ran an ensemble of FATES simulations for Barro Colorado Island, Panama. These simulations were initialized with 287 unique parameter sets, which differed in 12 key plant trait parameters that were sampled from observed distributions when possible (following Koven et al., _in review_). Plant structure and functioning are sensitive to atmospheric carbon dioxide concentration, which increased over the observational time period. We therefore tested each parameter set under two carbon dioxide concentrations (i.e., background environments) that approximately bookend the observational time period (367 ppm and 400 ppm carbon dioxide). All simulations were forced with repeating meteorological data for Barro Colorado Island, Panama, from the years 2003 to 2016 (Faybishenko et al., 2018). See Kovenock (2019) for further details of the parameter ensemble simulations.\n\n_Parameter set evaluation and selection_
\nThis code uses the above ensemble of simulations to quantitatively evaluate the performance of each parameter set against observations of six variables at our tropical forest test site. These variables characterize ecosystem structure (leaf area index, above-ground biomass, basal area) and functioning (gross primary productivity, latent heat flux, sensible heat flux). Observations come from the following sources: leaf area index from Detto et al. (2018); above-ground biomass from Meakem et al. (2018), Feeley et al. (2007), and Baraloto et al. (2013); basal area from Condit et al. (2017, 2012), Condit (1998), and Hubbell et al. (1999); and gross primary productivity, latent heat flux, and sensible heat flux from Koven et al. (_in review_). (As some of these data sets require permission to use or are not yet publicly available, observational data sets are not included for download here.)\n\nWe use two performance metrics $-$ error rate and normalized root mean square error (NRMSE) $-$ to quantify each parameter set's performance. The error rate measures how frequently the model output falls within the observed range for each variable. The NRMSE measures the distance between the model output and the observed mean, relative to the observed range for each variable. The expectation is that high-performing parameter sets will result in model output that falls within the range of observations (low error rate) and near the observed mean (low NRMSE). After evaluating a parameter set's performance for each individual variable, we calculate the weighted average performance across all variables for that parameter set. To ensure that our selection of a high-performing parameter set is robust to weighting method, we consider three different weighting approaches: even weighting, weighting favoring structural variables (leaf area index, basal area, and above-ground biomass), and weighting accounting for correlation between individual variable performance values.\n\nLastly, we identify parameter sets for use in future experiments by assigning an overall rank to each parameter set based on its performance across both performance metrics, three weighted averaging approaches, and two background carbon dioxide concentrations.\n\n__Results__
\nThis analysis identifies three high-performing parameter sets for use in future FATES simulations. We recommend the highest-performing parameter set for use in primary experiments and the next two highest-performing parameter sets for use in parameter sensitivity tests. These high-performing parameter sets are publicly available through the University of Washington ResearchWorks digital repository at http://hdl.handle.net/1773/43779. The performance of these parameter sets is reported in further detail in the [Results](#Results) section below and in Kovenock (2019).\n\n## Analysis\n## Step 1: Load libraries\n\n\n```python\nimport netCDF4 as nc4\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom scipy import stats\n\nfrom psfxns import annmeans\nfrom psfxns import metrics\nfrom psfxns import plotmetrics\n```\n\n## Step 2: Load and preprocess data\n\nThis code section returns two multidimensional arrays, one for model output and one for observations, that contain annual mean time series for six variables organized by parameter set and background carbon dioxide concentration. The six ecosystem characteristics we analyze are: leaf area index, above-ground biomass, basal area, gross primary productivity, latent heat flux, and sensible heat flux.\n\n### 2.1 Model output\n\nThis part of the code loads and preprocesses the model output for all FATES simulations in our parameter ensemble. It returns a 4-D array called 'model_data' that contains annual mean timeseries for each variable, parameter set, and background carbon dioxide concentration.\n\n\n```python\n# Return model_data: a 4-D array of annual mean values \n# with shape (CO2levels, varlist, nens, nyrs).\n\n# Model output file path and names\nmodel_filepath = 'data/'\nname1 = 'fates_clm5_fullmodel_bci_parameter_ensemble_1pft_slaprofile_{}_v001.'\nname2 = 'I2000Clm50FatesGs.Cdf9b02d-Fb178808.2018-07-27.h{}.ensemble.sofar.nc'\nmodel_filenames = [name1 + name2,\n name1 + name2]\n\n# Variable list\nvarlist = ['TLAI', 'AGB', 'BA', 'GPP', 'FLH', 'FSH']\n\n# File type, indexed by varlist:\n# 0 = monthly mean for entire ecosystem; and\n# 1 = annual mean by tree size.\nvarfiletype = [0, 1, 1, 0, 0, 0]\n\n# Conversion factor, indexed by varlist:\nvarconv = [1, 1, 1, 86400*365, 1, 1]\n\n# Background carbon dioxide (CO2) concentrations\nCO2levels = ['367ppm', '400ppm']\n\n# Number of years of model output to analyze\nnyrs = 50\n\n# Number of parameter sets in ensemble\nnens = nc4.Dataset(\n model_filepath + model_filenames[0]\n .format(CO2levels[0], varfiletype[0])).variables[varlist[0]].shape[0]\n\nmodel_data = np.zeros([len(CO2levels), len(varlist), nens, nyrs])\nfor c in range(len(CO2levels)):\n for v in range(len(varlist)):\n filepath = (model_filepath + model_filenames[c]\n .format(CO2levels[c], varfiletype[v]))\n model_data[c, v, :, :] = annmeans.annual_mean_model(\n filepath, varlist[v], varfiletype[v], nyrs, varconv[v])\n filepath = None\n```\n\n### 2.2 Observations\n\nThis code section loads and preprocesses the data for the observations we will use to evaluate the performance of each parameter set in our FATES parameter ensemble.\n\n#### Leaf area index\n\nLeaf area index observations come from Detto et al. (2018) and were made using hemispherical photographs taken approximately monthly from January 2015 to August 2017 at 188 locations at our test site, Barro Colorado Island, Panama. Data was captured from Detto et al. (2018) Figure 7a using GraphClick software. We calculate annual mean values from the monthly means reported by Detto et al. (2018). (Note that monthly data consists of spatial means across photograph locations, rather than temporal means.) In order to use all the data available, we calculate two time series of annual means $-$ one starting in from January and the second starting from September. We then choose the time series that allows for the best performance in our performance metric calculations in the next section.\n\n\n```python\n# Return obs_data_lai: 2-D array of annual mean leaf area index\n# with shape (sample_number, nyrs). Sample_number coded as follows: \n# 0 = sample months starting from January; and\n# 1 = sample months starting from September.\n\nfilepath = 'data/LAI_Detto2018Obs.csv'\n\n# Monthly spatial means\nlai_mthts = np.asarray([col[2] for col in (pd.read_csv(filepath)).values])\n\n# Specify start months for observations\nstartmonth_list = np.array([1, 9])\n\n# Number of annual means per sample\nnyears_lai = round(len(lai_mthts)/12 - 0.5)\n\nobs_data_lai = np.zeros([len(startmonth_list), nyears_lai])\nfor x in range(len(startmonth_list)):\n obs_data_lai[x, :] = np.nanmean(np.reshape(\n lai_mthts[startmonth_list[x]-1 : 24+startmonth_list[x]-1],\n (nyears_lai, 12)), 1)\n```\n\n#### Above-ground carbon biomass\n\nAbove-ground carbon biomass estimates were calculated by Meakem et al. (2018) from 1995 census survey data for our test site, Barro Colorado Island. They estimate above-ground biomass using two different methods (the standard and Chave allometric formulations). We use values from these two methods to represent uncertainty in the observational estimate. \n\nAlternatively, we can approximate above-ground carbon biomass from estimates of total biomass (rather than just carbon biomass) from census survey data reproted in Baraloto et al. (2013) and Feeley et al. (2007) for the following years: 1985, 1990, 1995, 2000, and 2005. This alternative method yields similar results and can be implemented by setting use_alt_agb_obs to 1 in the code below.\n\n\n```python\n# Return obs_data_agb: a vector of above-ground carbon biomass\n# (KgC/m2) indexed by allometric formulation as follows:\n# 0 = standard formulation; and\n# 1 = Chave formulation.\n\n# Specify whether to use (0) Meakem et al. (2018) estimate; or\n# (1) Baraloto et al. (2013) and Feeley et al. (2007) estimates.\nuse_alt_agb_obs = 0;\n\nfilepath = 'data/BCI_biomass.csv'\n\nif use_alt_agb_obs == 0:\n # Above-ground carbon biomass from Meakem et al. 2018 (MgC/ha)\n cbiomass_obs_Mgha = np.asarray(\n [col[2] for col in (pd.read_csv(filepath)).values])[-2:,]\n # Convert from MgC/ha to KgC/m2\n ha_to_m2 = 1/10000\n Mg_to_kg = 1000\n obs_data_agb = cbiomass_obs_Mgha * ha_to_m2 * Mg_to_kg\n \nelif use_alt_agb_obs == 1:\n # Total aboveground biomass (Mg biomass/ha) from \n # Baraloto et al. (2013) and Feeley et al. (2007)\n agb_biomass_obs = np.asarray(\n [col[1] for col in (pd.read_csv(filepath)).values])[:-2,]\n # Estimate of carbon biomass from total biomass\n # using a conversion factor of 0.47 gC/g biomass\n # following Meakem et al. 2018\n obs_data_agb_v2 = agb_biomass_obs * 0.47\n obs_data_agb = obs_data_agb_v2\n```\n\n#### Basal area\n\nWe use estimates of the median basal area for our test site Barro Colorado Island, Panama, from census surveys conducted in 1999, 2001, 2006, and 2011 by Condit (1998), Condit et al. (2012, 2017), and Hubbell et al. (1999).\n\n\n```python\n# Return obs_data_ba: vector containing basal area (m^2/ha)\n# indexed by census year in chronological order.\n\nfilepath = 'data/census_bmks_bci_171208.nc'\n\n# Load basal area median values for the last 5 census dates\n# Data structured as follows:\n# [census number, tree diameter size class,\n# distribution percentiles (0.05,0.5,0.95)]\nbasalarea_bysize = nc4.Dataset(\n filepath).variables['basal_area_by_size_census'][-5:, :, 1]\n\n# Sum across tree size classes\nobs_data_ba = np.nansum(basalarea_bysize, 1)\n```\n\n#### Gross primary productivity, latent heat flux, and sensible heat flux\n\nEstimates of gross primary productivity, latent heat flux, and sensible heat flux were calculated from fluxtower eddy covariance measurements made from July 2012 to August 2017 at Barro Colorado Island by Koven et al. (_in review_). To use all available data in our analysis, we calculate two versions of the annual means time series, one beginning in July and the second beginning in September. We then choose the time series that allows for the best performance in our performance metric calculations in the next section.\n\n\n```python\n# Return obs_data_flux: 3-D array of annual mean \n# fluxtower estimates with shape (sample_number, variable, years).\n# Sample_number is indexed as follows: 0 = sample months \n# starting from July; and 1 = sample months starting from September.\n# Variable is indexed as follows: 0 = gross primary productivity;\n# 1 = latent heat flux; and 2 = sensible heat flux.\n\n# Load observations\nGPP_data = np.load('data/fluxdata_GPP.npy')\nLH_data = np.load('data/fluxdata_LH.npy')\nSH_data = np.load('data/fluxdata_SH.npy')\nfluxdata_mask= np.load('data/fluxdata_mask.npy')\n\n# Apply mask to arrays\nGPP_monthyear = np.ma.masked_array(GPP_data, mask=fluxdata_mask)\nLH_monthyear = np.ma.masked_array(LH_data, mask=fluxdata_mask)\nSH_monthyear = np.ma.masked_array(SH_data, mask=fluxdata_mask)\n\n# Specify start months for observations\nstartmonth_list = np.array([7, 9])\n\n# Number of years\nnyrs_obsflux = len(annmeans.annual_mean_fluxobs(\n GPP_monthyear, startmonth_list[0]))\n\nobs_data_flux = np.zeros([len(startmonth_list), 3, nyrs_obsflux])\nfor x in range(len(startmonth_list)):\n obs_data_flux[x, 0, :] = annmeans.annual_mean_fluxobs(\n GPP_monthyear, startmonth_list[x])\n obs_data_flux[x, 1, :] = annmeans.annual_mean_fluxobs(\n LH_monthyear, startmonth_list[x])\n obs_data_flux[x, 2, :] = annmeans.annual_mean_fluxobs(\n SH_monthyear, startmonth_list[x])\n```\n\nLastly, we return one list that contains the observed annual mean time series for all variables (i.e., a list of the observed data arrays returned in the code above).\n\n\n```python\n# Return obs_data_list: a list containing all six observed\n# variable arrays.\nobs_data_list = [obs_data_lai, obs_data_agb, obs_data_ba,\n obs_data_flux[:, 0, :], \n obs_data_flux[:, 1, :],\n obs_data_flux[:, 2, :]]\n```\n\n## Step 3: Quanitfy performance of each parameter set\n\nIn this section we evaluate the model performance for each parameter set and background carbon dioxide concentration against observations. As we would like to identify parameter sets that robsutly perform well regardless of performance metric we use two metrics to evaluate performance: error rate and normalized root mean square error (NRMSE). We calculate both metrics for each variable. Then, we take a weighted average across all variables for each metric, parameter set, and background carbon dioxide concentration combination.\n\n### Performance Metric #1: Error Rate\n\nThe error rate measures the percent of model annual means that fall within the observed range for each variable and ensemble member. To account for relatively small sample sizes and potential measurment error within the observations we extend the observed range by 10% in both directions.\n\n\n```python\n# Return error_rate_array: a 3-D array containing error rates\n# indexed by (CO2levels, varlist, nens)\n\n# Degradation level for the observational range \n# (as fraction, not percent)\ndg = 0.10\n\nerror_rate_array = np.zeros([len(CO2levels), len(varlist), nens])\nfor i in range(len(CO2levels)):\n for j in range(len(varlist)):\n error_rate_array[i, j, :] = metrics.error_rate(\n model_data[i, j, :, :], obs_data_list[j], dg) \n```\n\n### Performance Metric #2: Normalized root mean square error (NRMSE)\n\nThe normalized root mean square error (NRMSE) measures the distance between the model output and the observed mean value, relative to the spread in the observations. The NRMSE is calculated as follows:\n\n\\begin{equation}\\Large\nNRMSE = \\frac{ \\sqrt{ \\sum_{k=1}^n \\frac{(x_{model,k} - \\bar{X}_{obs})^2}{n}}} {x_{obs,max} - x_{obs,min}}\n\\end{equation}\n\nwhere $NRMSE$ is the normalized root mean square error for a single variable (e.g. leaf area index) and parameter set, $n$ is the number of years of model output, $x_{model,k}$ is the model annual mean for year $k$, $\\bar{X}_{obs}$ is the overall annual mean of the observed values, and $x_{obs,max}$ and $x_{obs,min}$ are the maximum and minimum observed annual mean values, respectively. When mulitple annual mean time series were sampled for an observed variable (e.g. observations for leaf area index spanned a partial year), we calculate the difference between the observed mean and model output using the time series that minimizes this difference.\n\n\n```python\n# Return nrsmse_array: a 3-D array containing the NRMSE \n# indexed by [CO2level, varlist, nens] \n\nnrmse_array = np.zeros([len(CO2levels), len(varlist), nens])\nfor i in range(len(CO2levels)):\n for j in range(len(varlist)):\n nrmse_array[i, j, :] = metrics.nrmse(\n model_data[i, j, :, :], obs_data_list[j])\n```\n\n### Weighted average permformance metrics across variables\n\nWe calculate weighted average performance metrics across variables for both error rate and NRMSE. We consider three different weighting approaches to ensure that our selection of high-performing parameter sets is robust to weighting method. The weighting approaches we use are:\n\n1. Even: All variables are evenly weighted.\n\n2. Structure: This weighting favors structural ecosystem properties (leaf area index, above-ground biomass, and basal area). It reflects the likelihood that structural variables at our test site include less measurment uncertainty than flux variables.\n\n3. Correlation: This weighting scheme is informed by correlations between individual variable performance metrics. The ability of a parameter set to mach observations of flux variables (gross primary productivity, sensible heat, and latent heat) was correlated with ability to match observations of leaf area index, as well as other flux variables. As leaf area index observations likely include smaller measurement uncertainty, we choose to give a greater weighting to leaf area index at the expense of flux estimates. We also reduced the weightings of basal area and above-ground biomass performance to account for their correlation with one another.\n\n#### Weighted average error rate\n\n\n```python\n# Even weighting across all variables\ner_wavg_even = np.average(error_rate_array, axis=1)\n\n# Weighted average favoring structural properties\nws = 0.3\nwf = (1-3*ws)/3\nw_strct = [ws, ws, ws, wf, wf, wf]\ner_wavg_strct = np.average(error_rate_array, axis=1, weights=w_strct)\n\n# Weighting considering correlations between performance metrics\nw1 = 0.4\nw2 = 0.25\nw3 = 0.1/3\nw_corr = [w1, w2, w2, w3, w3, w3]\ner_wavg_corr = np.average(error_rate_array, axis=1, weights=w_corr)\n```\n\n#### Weighted average NRMSE\n\nWe quantify the distance of model output from the mean observations in multivariate space by calculating the weighted Euclidean distance as follows:\n\n\\begin{equation}\nNRMSE_{avg} = \\sqrt{ \\sum_{i=1}^m \\omega_{i} \\cdot NRMSE_{i}^2}\n\\end{equation}\n\nwhere $NRMSE_{avg}$ is the weighted average NRMSE across variables, $m$ is the number of variables, and $NRMSE_{i}$ and $\\omega_{i}$ are the individual variable NRMSE and weighting, respectively.\n\n\n```python\n# Even weighting across all variables\nnvars = nrmse_array.shape[1]\nw = 1/nvars\nw_even = np.matlib.repmat(w,nvars,1)\nnrmse_wavg_even = metrics.avg_nrmse(nrmse_array, w_even)\n\n# Weighted average favoring structural properties\nnrmse_wavg_strct = metrics.avg_nrmse(nrmse_array, w_strct)\n\n# Weighting considering correlations between performance metrics\nnrmse_wavg_corr = metrics.avg_nrmse(nrmse_array, w_corr)\n```\n\nLastly, we return one array that contains the weighted average values for all combinations of weighting approach and performance metric.\n\n\n```python\nall_avg_array = np.transpose(np.stack([\n er_wavg_even, er_wavg_strct, er_wavg_corr,\n nrmse_wavg_even, nrmse_wavg_strct, nrmse_wavg_corr]),\n (1,0,2))\n```\n\n## Step 4: Rank parameter sets by performance\nHere we assign an overall rank to each parameter set based on its performance across two performance metrics (error rate and NRMSE), three weighted averaging approaches (even, structure, and correlated), and two background carbon dioxide concentrations (367 ppm and 400 ppm). High-performing parameter sets (i.e., parameter sets that robustly performed well at our test site) are indicated by a low numbered rank.\n\n\n```python\n# Assign each simulation a rank for \n# each weighted average performance metric\nrank_array = stats.mstats.rankdata(all_avg_array, axis=2)\n\n# Sum ranks across performance metrics and\n# background carbon dioxide concentrations\nsum_rank_array = np.nansum(np.nansum(rank_array, axis=0), axis=0)\n\n# Sort parameter set indexes by their summed rank\n# (best to worst performance)\nsum_rank_index = np.argsort(sum_rank_array)\n\n#Print for highest-performing parameter set numbers\nhighperform_num = np.transpose(sum_rank_index)[:10,] + 1\nprint(\"Highest-performing parameter set numbers: \", highperform_num[0:3])\n```\n\n Highest-performing parameter set numbers: [ 86 260 151]\n\n\n__Result:__ Parameter sets 86, 260, and 151 resulted in the highest model performance (in descending order) at our test site.\n\n\n## Step 5: Plot performance metrics for each parameter set\n\nIn this section we visualize the model performance for each parameter set to gain insight into how the highest-performing parameter sets performed in individual variables and in comparison to all other parameter sets.\n\n\n```python\n# Return error_heatdata and nrmse_heatdata: two 3-D arrays\n# containing error rates and NRMSE values, respectively,\n# indexed by (CO2level, variables, nens). Variables indexed \n# as follows: \n# 0-5, variables in order of varlist; and \n# 6-8 = weighted averages across variables using even,\n# structure, and correlation weights, respectively\n\nerror_heatdata = np.concatenate(\n [error_rate_array, all_avg_array[:, :3, :]], axis=1)\nnrmse_heatdata = np.concatenate(\n [nrmse_array, all_avg_array[:, 3:, :]], axis=1)\n```\n\n### Plot for simulations run at 367 ppm carbon dioxide\n\n\n```python\n# Set carbon dioxide case to 367 ppm\ncasenum = 0\n\n# Plot Error Rate and NRMSE\nfig1 = plt.figure(figsize=(12, 12))\n\nplotnum = 1\nplotmetrics.heatmap_subplot(error_heatdata, casenum, 0, 100, \n plotnum, 'A. Error Rate (%)', highperform_num)\n\nplotnum = plotnum + 1\nplotmetrics.heatmap_subplot(nrmse_heatdata, casenum, 0, 10,\n plotnum, 'B. NRMSE', highperform_num)\n\nplt.tight_layout()\n```\n\n__Figure 1.__ FATES model performance as measured by (A) error rate and (B) normalized root mean square error (NRMSE) for simulations run with 367 ppm atmospheric carbon dioxide. Performance metrics are shown for leaf area index (LAI), above-ground biomass (AGB), basal area (BA), gross primary productivity (GPP), latent heat flux (LH), sensible heat flux (SH), and weighted averages across variables using three weighting approaches: even (Av$_E$), favoring structural variables (Av$_S$), and considering correlations between individual performance metrics (Av$_C$). Top panels highlight the performance of the 10 highest-perfoming parameter sets. Bottom panels show the performance of all 287 parameter sets we tested.\n\n### Plot for simulations run at 400 ppm carbon dioxide\n\n\n```python\n# Set carbon dioxide case to 400 ppm\ncasenum = 1\n\n# Plot Error Rate and NRMSE\nfig2 = plt.figure(figsize=(12, 12))\n\nplotnum = 1\nplotmetrics.heatmap_subplot(error_heatdata, casenum, 0, 100,\n plotnum, 'A. Error Rate (%)', highperform_num)\n\nplotnum = plotnum + 1\nplotmetrics.heatmap_subplot(nrmse_heatdata, casenum, 0, 10,\n plotnum, 'B. NRMSE', highperform_num)\n\nplt.tight_layout()\n```\n\n__Figure 2.__ FATES model performance as measured by (A) error rate and (B) normalized root mean square error (NRMSE) for simulations run with 400 ppm atmospheric carbon dioxide. Performance metrics are shown for leaf area index (LAI), above-ground biomass (AGB), basal area (BA), gross primary productivity (GPP), latent heat flux (LH), sensible heat flux (SH), and weighted averages across variables using three weighting approaches: even (Av$_E$), favoring structural variables (Av$_S$), and considering correlations between individual performance metrics (Av$_C$). Top panels highlight the performance of the 10 highest-perfoming parameter sets. Bottom panels show the performance of all 287 parameter sets we tested.\n\n## Results\nThis analysis identifies three high-performing parameter sets for use in future FATES simulations. We recommend the highest-performing parameter set (parameter set number 86; Figures 1 and 2) as the primary parameter set for future experiments. The next two highest-performing parameter sets (parameter sets numbers 151 and 260; Figures 1 and 2) are recommended for testing the sensitivity of experiments to model parameterization. Parameter set number 260 is the second highest-performing parameter set and is similar in parameter values and resulting ecosystem properties to parameter set number 86. Parameter set number 151, on the other hand, differs more substantially in its parameter values and results in a different combination of ecosystem properties. In particular, parameter set number 151 performs well in above-ground biomass and basal area measures across carbon dioxide levels, but results in low leaf area index and high gross primary productivity compared to observations. See Kovenock (2019) for further details. \n\nThese three high-performing parameter sets are made publicly available through the University of Washington ResearchWorks digital repository at http://hdl.handle.net/1773/43779.\n\n## Further Information\n__Details of the parameter ensemble and analysis herein:__\n\nKovenock, M. (2019). Ecosystem and large-scale climate impacts of plant leaf dynamics (Doctoral dissertation). Chapter 4: \"Within-canopy gradient of specific leaf area improves simulation of tropical forest structure and functioning in a demographic vegetation model.\" http://hdl.handle.net/1773/44061\n\n__Details of the Functionally Assembled Ecosystem Simulator (FATES):__\n\nGitHub code repository:
\nhttps://github.com/NGEET/fates\n\nFisher, R. A., Koven, C. D., Anderegg, W. R., Christoffersen, B. O., Dietze, M. C., Farrior, C. E., et al. (2018). Vegetation demographics in Earth System Models: A review of progress and priorities. Global Change Biology, 24(1), 35–54. https://doi.org/10.1111/gcb.13910\n\nFisher, R. A., Muszala, S., Verteinstein, M., Lawrence, P., Xu, C., McDowell, N. G., et al. (2015). Taking off the training wheels: the properties of a dynamic vegetation model without climate envelopes. _Geoscientific Model Development, 8_(4), 3293–3357. https://doi.org/10.5194/gmdd-8-3293-2015\n\n\n## References\n\nBaraloto, C., Molto, Q., Rabaud, S., Hérault, B., Valencia, R., Blanc, L., et al. (2013). Rapid simultaneous estimation of aboveground biomass and tree diversity across Neotropical forests: a comparison of field inventory methods. _Biotropica, 45_(3), 288–298. https://doi.org/10.1111/btp.12006\n\nCondit, R. (1998). Tropical forest census plots. Berlin, Germany, and Georgetown, Texas: Springer-Verlag and R. G. Landes Company.\n\nCondit, R. S., Aguilar, S., Perez, R., Lao, S., Hubbell, S. P., & Foster, R. B. (2017). Barro Colorado 50-ha Plot Taxonomy as of 2017. https://doi.org/10.25570/stri/10088/32990\n\nCondit, R., Lao, S., Pérez, R., Dolins, S. B., Foster, R., & Hubbell, S. (2012). Barro Colorado forest census plot data (version 2012). Center for Tropical Forest Science Databases. https://doi.org/10.5479/data.bci.20130603\n\nDetto, M., Wright, S. J., Calderón, O., & Muller-Landau, H. C. (2018). Resource acquisition and reproductive strategies of tropical forest in response to the El Niño$-$Southern Oscillation. _Nature Communications, 9_(1), 913. https://doi.org/10.1038/s41467-018-03306-9\n\nFaybishenko, B., Paton, S., Powell, T., Knox, R., Pastorello, G., Varadharajan, C., et al. (2018). QA/QC-ed BCI meteorological drivers. United States: Next-Generation Ecosystem Experiments Tropics; STRI; LBNL. https://doi.org/doi:10.15486/ngt/1423307\n\nFeeley, K. J., Davies, S. J., Ashton, P. S., Bunyavejchewin, S., Supardi, M. N., Kassim, A. R., et al. (2007). The role of gap phase processes in the biomass dynamics of tropical forests. _Proceedings of the Royal Society B: Biological Sciences, 274_(1627), 2857–2864. https://doi.org/10.1098/rspb.2007.0954\n\nFisher, R. A., Koven, C. D., Anderegg, W. R., Christoffersen, B. O., Dietze, M. C., Farrior, C. E., et al. (2018). Vegetation demographics in Earth System Models: A review of progress and priorities. _Global Change Biology, 24_(1), 35–54. https://doi.org/10.1111/gcb.13910\n\nFisher, R. A., Muszala, S., Verteinstein, M., Lawrence, P., Xu, C., McDowell, N. G., et al. (2015). Taking off the training wheels: the properties of a dynamic vegetation model without climate envelopes. _Geoscientific Model Development, 8_(4), 3293–3357. https://doi.org/10.5194/gmdd-8-3293-2015\n\nHubbell, S. P., Foster, R. B., O'Brien, S. T., Harms, K. E., Condit, R., Wechsler, B., et al. (1999). Light-gap disturbances, recruitment limitation, and tree diversity in a neotropical forest. _Science, 283_(5401), 554–557. https://doi.org/10.1126/science.283.5401.554 \n\nKoven, C. D., et al. (_in review_). Benchmarking and parameter sensitivity of physiological and vegetation dynamics using the Functionally Assembled Terrestrial Ecosystem Simulator (FATES) at Barro Colorado Island, Panama. _Biogeosciences Discussions_. https://doi.org/10.5194/bg-2019-409\n\nKovenock, M. (2019). Ecosystem and large-scale climate impacts of plant leaf dynamics (Doctoral dissertation). http://hdl.handle.net/1773/44061\n\nMeakem, V., Tepley, A. J., Gonzalez-Akre, E. B., Herrmann, V., Muller-Landau, H. C., Wright, S. J., et al. (2018). Role of tree size in moist tropical forest carbon cycling and water deficit responses. _New Phytologist, 219_, 947–958. https://doi.org/doi:10.1111/nph.14633\n\n", "meta": {"hexsha": "0a347982d0f40337e24707d65442ffc4608e6554", "size": 168660, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "fates_parameter_selection.ipynb", "max_stars_repo_name": "kovenock/FATES_Parameter_Selection", "max_stars_repo_head_hexsha": "eb38cc96b3cb6c02ae71426b6351e60b16ed8a56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fates_parameter_selection.ipynb", "max_issues_repo_name": "kovenock/FATES_Parameter_Selection", "max_issues_repo_head_hexsha": "eb38cc96b3cb6c02ae71426b6351e60b16ed8a56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fates_parameter_selection.ipynb", "max_forks_repo_name": "kovenock/FATES_Parameter_Selection", "max_forks_repo_head_hexsha": "eb38cc96b3cb6c02ae71426b6351e60b16ed8a56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 225.7831325301, "max_line_length": 65096, "alphanum_fraction": 0.8950610696, "converted": true, "num_tokens": 7787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.23633853129793364}} {"text": "\n# PHY321: Introduction to Classical Mechanics and plans for Spring 2020\n\n \n**[Morten Hjorth-Jensen](http://mhjgit.github.io/info/doc/web/)**, Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University, USA and Department of Physics, University of Oslo, Norway \n\n **[Scott Pratt](https://pa.msu.edu/profile/pratts/)**, Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University, USA \n\n **[Carl Schmidt](https://pa.msu.edu/profile/schmidt/)**, Department of Physics and Astronomy, Michigan State University, USA\n\nDate: **Dec 16, 2020**\n\nCopyright 1999-2020, [Morten Hjorth-Jensen](http://mhjgit.github.io/info/doc/web/). Released under CC Attribution-NonCommercial 4.0 license\n\n\n\n\n# Introduction\n\nClassical mechanics is a topic which has been taught intensively over\nseveral centuries. It is, with its many variants and ways of\npresenting the educational material, normally the first **real** physics\ncourse many of us meet and it lays the foundation for further physics\nstudies. Many of the equations and ways of reasoning about the\nunderlying laws of motion and pertinent forces, shape our approaches and understanding\nof the scientific method and discourse, as well as the way we develop our insights\nand deeper understanding about physical systems. \n\nThere is a wealth of\nwell-tested (from both a physics point of view and a pedagogical\nstandpoint) exercises and problems which can be solved\nanalytically. However, many of these problems represent idealized and\nless realistic situations. The large majority of these problems are\nsolved by paper and pencil and are traditionally aimed\nat what we normally refer to as continuous models from which we may find an analytical solution. As a consequence,\nwhen teaching mechanics, it implies that we can seldomly venture beyond an idealized case\nin order to develop our understandings and insights about the\nunderlying forces and laws of motion.\n\n\nOn the other hand, numerical algorithms call for approximate discrete\nmodels and much of the development of methods for continuous models\nare nowadays being replaced by methods for discrete models in science and\nindustry, simply because **much larger classes of problems can be addressed** with discrete models, often by simpler and more\ngeneric methodologies.\n\nAs we will see below, when properly scaling the equations at hand,\ndiscrete models open up for more advanced abstractions and the possibility to\nstudy real life systems, with the added bonus that we can explore and\ndeepen our basic understanding of various physical systems\n\nAnalytical solutions are as important as before. In addition, such\nsolutions provide us with invaluable benchmarks and tests for our\ndiscrete models. Such benchmarks, as we will see below, allow us \nto discuss possible sources of errors and their behaviors. And\nfinally, since most of our models are based on various algorithms from\nnumerical mathematics, we have a unique oppotunity to gain a deeper\nunderstanding of the mathematical approaches we are using.\n\n\n\nWith computing and data science as important elements in essentially\nall aspects of a modern society, we could then try to define Computing as\n**solving scientific problems using all possible tools, including\nsymbolic computing, computers and numerical algorithms, and analytical\npaper and pencil solutions**. \nComputing provides us with the tools to develope our own understanding of the scientific method by enhancing algorithmic thinking.\n\n\nThe way we will teach this course reflects\nthis definition of computing. The course contains both classical paper\nand pencil exercises as well as computational projects and exercises. The\nhope is that this will allow you to explore the physics of systems\ngoverned by the degrees of freedom of classical mechanics at a deeper\nlevel, and that these insights about the scientific method will help\nyou to develop a better understanding of how the underlying forces and\nequations of motion and how they impact a given system. Furthermore, by introducing various numerical methods\nvia computational projects and exercises, we aim at developing your competences and skills about these topics.\n\n\nThese competences will enable you to\n\n* understand how algorithms are used to solve mathematical problems,\n\n* derive, verify, and implement algorithms,\n\n* understand what can go wrong with algorithms,\n\n* use these algorithms to construct reproducible scientific outcomes and to engage in science in ethical ways, and\n\n* think algorithmically for the purposes of gaining deeper insights about scientific problems.\n\nAll these elements are central for maturing and gaining a better understanding of the modern scientific process *per se*.\n\nThe power of the scientific method lies in identifying a given problem\nas a special case of an abstract class of problems, identifying\ngeneral solution methods for this class of problems, and applying a\ngeneral method to the specific problem (applying means, in the case of\ncomputing, calculations by pen and paper, symbolic computing, or\nnumerical computing by ready-made and/or self-written software). This\ngeneric view on problems and methods is particularly important for\nunderstanding how to apply available, generic software to solve a\nparticular problem.\n\n*However, verification of algorithms and understanding their limitations requires much of the classical knowledge about continuous models.*\n\n\n\n## A well-known examples to illustrate many of the above concepts\n\nBefore we venture into a reminder on Python and mechanics relevant applications, let us briefly outline some of the\nabovementioned topics using an example many of you may have seen before in for example CMSE201. \nA simple algorithm for integration is the Trapezoidal rule. \nIntegration of a function $f(x)$ by the Trapezoidal Rule is given by following algorithm for an interval $x \\in [a,b]$\n\n$$\n\\int_a^b(f(x) dx = \\frac{1}{2}\\left [f(a)+2f(a+h)+\\dots+2f(b-h)+f(b)\\right] +O(h^2),\n$$\n\nwhere $h$ is the so-called stepsize defined by the number of integration points $N$ as $h=(b-a)/(n)$.\nPython offers an extremely versatile programming environment, allowing for\nthe inclusion of analytical studies in a numerical program. Here we show an\nexample code with the **trapezoidal rule**. We use also **SymPy** to evaluate the exact value of the integral and compute the absolute error\nwith respect to the numerically evaluated one of the integral\n$\\int_0^1 dx x^2 = 1/3$.\nThe following code for the trapezoidal rule allows you to plot the relative error by comparing with the exact result. By increasing to $10^8$ points one arrives at a region where numerical errors start to accumulate.\n\n\n```\n%matplotlib inline\n\nfrom math import log10\nimport numpy as np\nfrom sympy import Symbol, integrate\nimport matplotlib.pyplot as plt\n# function for the trapezoidal rule\ndef Trapez(a,b,f,n):\n h = (b-a)/float(n)\n s = 0\n x = a\n for i in range(1,n,1):\n x = x+h\n s = s+ f(x)\n s = 0.5*(f(a)+f(b)) +s\n return h*s\n# function to compute pi\ndef function(x):\n return x*x\n# define integration limits\na = 0.0; b = 1.0;\n# find result from sympy\n# define x as a symbol to be used by sympy\nx = Symbol('x')\nexact = integrate(function(x), (x, a, b))\n# set up the arrays for plotting the relative error\nn = np.zeros(9); y = np.zeros(9);\n# find the relative error as function of integration points\nfor i in range(1, 8, 1):\n npts = 10**i\n result = Trapez(a,b,function,npts)\n RelativeError = abs((exact-result)/exact)\n n[i] = log10(npts); y[i] = log10(RelativeError);\nplt.plot(n,y, 'ro')\nplt.xlabel('n')\nplt.ylabel('Relative error')\nplt.show()\n```\n\nThis example shows the potential of combining numerical algorithms with symbolic calculations, allowing us to \n\n* Validate and verify their algorithms. \n\n* Including concepts like unit testing, one has the possibility to test and test several or all parts of the code.\n\n* Validation and verification are then included *naturally* and one can develop a better attitude to what is meant with an ethically sound scientific approach.\n\n* The above example allows the student to also test the mathematical error of the algorithm for the trapezoidal rule by changing the number of integration points. The students get **trained from day one to think error analysis**. \n\n* With a Jupyter notebook you can keep exploring similar examples and turn them in as your own notebooks. \n\nIn this process we can easily bake in\n1. How to structure a code in terms of functions\n\n2. How to make a module\n\n3. How to read input data flexibly from the command line\n\n4. How to create graphical/web user interfaces\n\n5. How to write unit tests (test functions or doctests)\n\n6. How to refactor code in terms of classes (instead of functions only)\n\n7. How to conduct and automate large-scale numerical experiments\n\n8. How to write scientific reports in various formats (LaTeX, HTML)\n\nThe conventions and techniques outlined here will save you a lot of time when you incrementally extend software over time from simpler to more complicated problems. In particular, you will benefit from many good habits:\n1. New code is added in a modular fashion to a library (modules)\n\n2. Programs are run through convenient user interfaces\n\n3. It takes one quick command to let all your code undergo heavy testing \n\n4. Tedious manual work with running programs is automated,\n\n5. Your scientific investigations are reproducible, scientific reports with top quality typesetting are produced both for paper and electronic devices.\n\n# Space, Time, Motion, Reference Frames and Reminder on vectors and other mathematical quantities\n\nOur studies will start with the motion of different types of objects\nsuch as a falling ball, a runner, a bicycle etc etc. It means that an\nobject's position in space varies with time.\nIn order to study such systems we need to define\n* choice of origin\n\n* choice of the direction of the axes\n\n* choice of positive direction (left-handed or right-handed system of reference)\n\n* choice of units and dimensions\n\nThese choices lead to some important questions such as\n\n* is the physics of a system independent of the origin of the axes?\n\n* is the physics independent of the directions of the axes, that is are there privileged axes?\n\n* is the physics independent of the orientation of system?\n\n* is the physics independent of the scale of the length?\n\n### Dimension, units and labels\n\nThroughout this course we will use the standardized SI units. The standard unit for length is thus one meter 1m, for mass\none kilogram 1kg, for time one second 1s, for force one Newton 1kgm/s$^2$ and for energy 1 Joule 1kgm$^2$s$^{-2}$.\n\nWe will use the following notations for various variables (vectors are always boldfaced in these lecture notes):\n* position $\\boldsymbol{r}$, in one dimention we will normally just use $x$,\n\n* mass $m$,\n\n* time $t$,\n\n* velocity $\\boldsymbol{v}$ or just $v$ in one dimension,\n\n* acceleration $\\boldsymbol{a}$ or just $a$ in one dimension,\n\n* momentum $\\boldsymbol{p}$ or just $p$ in one dimension,\n\n* kinetic energy $K$,\n\n* potential energy $V$ and\n\n* frequency $\\omega$.\n\nMore variables will be defined as we need them.\n\nIt is also important to keep track of dimensionalities. Don't mix this up with a chosen unit for a given variable. We mark the dimensionality in these lectures as $[a]$, where $a$ is the quantity we are interested in. Thus\n\n* $[\\boldsymbol{r}]=$ length\n\n* $[m]=$ mass\n\n* $[K]=$ energy\n\n* $[t]=$ time\n\n* $[\\boldsymbol{v}]=$ length over time\n\n* $[\\boldsymbol{a}]=$ length over time squared\n\n* $[\\boldsymbol{p}]=$ mass times length over time\n\n* $[\\omega]=$ 1/time\n\n## Elements of Vector Algebra\n\n**Note**: This section is under revision\n\nIn these lectures we will use boldfaced lower-case letters to label a vector. A vector $\\boldsymbol{a}$ in three dimensions is thus defined as\n\n$$\n\\boldsymbol{a} =(a_x,a_y, a_z),\n$$\n\nand using the unit vectors in a cartesian system we have\n\n$$\n\\boldsymbol{a} = a_x\\boldsymbol{e}_x+a_y\\boldsymbol{e}_y+a_z\\boldsymbol{e}_z,\n$$\n\nwhere the unit vectors have magnitude $\\vert\\boldsymbol{e}_i\\vert = 1$ with $i=x,y,z$.\n\nUsing the fact that multiplication of reals is distributive we can show that\n\n$$\n\\boldsymbol{a}(\\boldsymbol{b}+\\boldsymbol{c})=\\boldsymbol{a}\\boldsymbol{b}+\\boldsymbol{a}\\boldsymbol{c},\n$$\n\nSimilarly we can also show that (using product rule for differentiating reals)\n\n$$\n\\frac{d}{dt}(\\boldsymbol{a}\\boldsymbol{b})=\\boldsymbol{a}\\frac{d\\boldsymbol{b}}{dt}+\\boldsymbol{b}\\frac{d\\boldsymbol{a}}{dt}.\n$$\n\nWe can repeat these operations for the cross products and show that they are distribuitive\n\n$$\n\\boldsymbol{a}\\times(\\boldsymbol{b}+\\boldsymbol{c})=\\boldsymbol{a}\\times\\boldsymbol{b}+\\boldsymbol{a}\\times\\boldsymbol{c}.\n$$\n\nWe have also that\n\n$$\n\\frac{d}{dt}(\\boldsymbol{a}\\times\\boldsymbol{b})=\\boldsymbol{a}\\times\\frac{d\\boldsymbol{b}}{dt}+\\boldsymbol{b}\\times\\frac{d\\boldsymbol{a}}{dt}.\n$$\n\nThe rotation of a three-dimensional vector $\\boldsymbol{a}=(a_x,a_y,a_z)$ in the $xy$ plane around an angle $\\phi$ results in a new vector $\\boldsymbol{b}=(b_x,b_y,b_z)$. This operation can be expressed in terms of linear algebra as a matrix (the rotation matrix) multiplied with a vector. We can write this as\n\n$$\n\\begin{bmatrix} b_x \\\\ b_y \\\\ b_z \\end{bmatrix} = \\begin{bmatrix} \\cos{\\phi} & \\sin{\\phi} & 0 \\\\ -\\sin{\\phi} & \\cos{\\phi} & 0 \\\\ 0 & 0 & 1\\end{bmatrix}\\begin{bmatrix} a_x \\\\ a_y \\\\ a_z \\end{bmatrix}.\n$$\n\nWe can write this in a more compact form as $\\boldsymbol{b} = \\boldsymbol{R}\\boldsymbol{a}$, where the rotation matrix is defined as\n\n$$\n\\boldsymbol{R} = \\begin{bmatrix} \\cos{\\phi} & \\sin{\\phi} & 0 \\\\ -\\sin{\\phi} & \\cos{\\phi} & 0 \\\\ 0 & 0 & 1\\end{bmatrix}.\n$$\n\n## Falling baseball in one dimension\n\nWe anticipate the mathematical model to come and assume that we have a\nmodel for the motion of a falling baseball without air resistance.\nOur system (the baseball) is at an initial height $y_0$ (which we will\nspecify in the program below) at the initial time $t_0=0$. In our program example here we will plot the position in steps of $\\Delta t$ up to a final time $t_f$. \nThe mathematical formula for the position $y(t)$ as function of time $t$ is\n\n$$\ny(t) = y_0-\\frac{1}{2}gt^2,\n$$\n\nwhere $g=9.80665=0.980655\\times 10^1$m/s${}^2$ is a constant representing the standard acceleration due to gravity.\nWe have here adopted the conventional standard value. This does not take into account other effects, such as buoyancy or drag.\nFurthermore, we stop when the ball hits the ground, which takes place at\n\n$$\ny(t) = 0= y_0-\\frac{1}{2}gt^2,\n$$\n\nwhich gives us a final time $t_f=\\sqrt{2y_0/g}$. \n\nAs of now we simply assume that we know the formula for the falling object. Afterwards, we will derive it.\n\n\n## Our Python Encounter\n\nWe start with preparing folders for storing our calculations, figures and if needed, specific data files we use as input or output files.\n\n\n```\n# Common imports\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport os\n\n# Where to save the figures and data files\nPROJECT_ROOT_DIR = \"Results\"\nFIGURE_ID = \"Results/FigureFiles\"\nDATA_ID = \"DataFiles/\"\n\nif not os.path.exists(PROJECT_ROOT_DIR):\n os.mkdir(PROJECT_ROOT_DIR)\n\nif not os.path.exists(FIGURE_ID):\n os.makedirs(FIGURE_ID)\n\nif not os.path.exists(DATA_ID):\n os.makedirs(DATA_ID)\n\ndef image_path(fig_id):\n return os.path.join(FIGURE_ID, fig_id)\n\ndef data_path(dat_id):\n return os.path.join(DATA_ID, dat_id)\n\ndef save_fig(fig_id):\n plt.savefig(image_path(fig_id) + \".png\", format='png')\n\n#in case we have an input file we wish to read in\n#infile = open(data_path(\"MassEval2016.dat\"),'r')\n```\n\nYou could also define a function for making our plots. You\ncan obviously avoid this and simply set up various **matplotlib**\ncommands every time you need them. You may however find it convenient\nto collect all such commands in one function and simply call this\nfunction.\n\n\n```\nfrom pylab import plt, mpl\nplt.style.use('seaborn')\nmpl.rcParams['font.family'] = 'serif'\n\ndef MakePlot(x,y, styles, labels, axlabels):\n plt.figure(figsize=(10,6))\n for i in range(len(x)):\n plt.plot(x[i], y[i], styles[i], label = labels[i])\n plt.xlabel(axlabels[0])\n plt.ylabel(axlabels[1])\n plt.legend(loc=0)\n```\n\nThereafter we start setting up the code for the falling object.\n\n\n```\n%matplotlib inline\nimport matplotlib.patches as mpatches\n\ng = 9.80655 #m/s^2\ny_0 = 10.0 # initial position in meters\nDeltaT = 0.1 # time step\n# final time when y = 0, t = sqrt(2*10/g)\ntfinal = np.sqrt(2.0*y_0/g)\n#set up arrays \nt = np.arange(0,tfinal,DeltaT)\ny =y_0 -g*.5*t**2\n# Then make a nice printout in table form using Pandas\nimport pandas as pd\nfrom IPython.display import display\ndata = {'t[s]': t,\n 'y[m]': y\n }\nRawData = pd.DataFrame(data)\ndisplay(RawData)\nplt.style.use('ggplot')\nplt.figure(figsize=(8,8))\nplt.scatter(t, y, color = 'b')\nblue_patch = mpatches.Patch(color = 'b', label = 'Height y as function of time t')\nplt.legend(handles=[blue_patch])\nplt.xlabel(\"t[s]\")\nplt.ylabel(\"y[m]\")\nsave_fig(\"FallingBaseball\")\nplt.show()\n```\n\nHere we used **pandas** (see below) to systemize the output of the position as function of time.\n\n\n\n## Average quantities\nWe define now the average velocity as\n\n$$\n\\overline{v}(t) = \\frac{y(t+\\Delta t)-y(t)}{\\Delta t}.\n$$\n\nIn the code we have set the time step $\\Delta t$ to a given value. We could define it in terms of the number of points $n$ as\n\n$$\n\\Delta t = \\frac{t_{\\mathrm{final}-}t_{\\mathrm{initial}}}{n+1}.\n$$\n\nSince we have discretized the variables, we introduce the counter $i$ and let $y(t)\\rightarrow y(t_i)=y_i$ and $t\\rightarrow t_i$\nwith $i=0,1,\\dots, n$. This gives us the following shorthand notations that we will use for the rest of this course. We define\n\n$$\ny_i = y(t_i),\\hspace{0.2cm} i=0,1,2,\\dots,n.\n$$\n\nThis applies to other variables which depend on say time. Examples are the velocities, accelerations, momenta etc.\nFurthermore we use the shorthand\n\n$$\ny_{i\\pm 1} = y(t_i\\pm \\Delta t),\\hspace{0.12cm} i=0,1,2,\\dots,n.\n$$\n\n## Compact equations\nWe can then rewrite in a more compact form the average velocity as\n\n$$\n\\overline{v}_i = \\frac{y_{i+1}-y_{i}}{\\Delta t}.\n$$\n\nThe velocity is defined as the change in position per unit time.\nIn the limit $\\Delta t \\rightarrow 0$ this defines the instantaneous velocity, which is nothing but the slope of the position at a time $t$.\nWe have thus\n\n$$\nv(t) = \\frac{dy}{dt}=\\lim_{\\Delta t \\rightarrow 0}\\frac{y(t+\\Delta t)-y(t)}{\\Delta t}.\n$$\n\nSimilarly, we can define the average acceleration as the change in velocity per unit time as\n\n$$\n\\overline{a}_i = \\frac{v_{i+1}-v_{i}}{\\Delta t},\n$$\n\nresulting in the instantaneous acceleration\n\n$$\na(t) = \\frac{dv}{dt}=\\lim_{\\Delta t\\rightarrow 0}\\frac{v(t+\\Delta t)-v(t)}{\\Delta t}.\n$$\n\n**A note on notations**: When writing for example the velocity as $v(t)$ we are then referring to the continuous and instantaneous value. A subscript like\n$v_i$ refers always to the discretized values.\n\n\n## A differential equation\n\nWe can rewrite the instantaneous acceleration as\n\n$$\na(t) = \\frac{dv}{dt}=\\frac{d}{dt}\\frac{dy}{dt}=\\frac{d^2y}{dt^2}.\n$$\n\nThis forms the starting point for our definition of forces later. It is a famous second-order differential equation. If the acceleration is constant we can now recover the formula for the falling ball we started with.\nThe acceleration can depend on the position and the velocity. To be more formal we should then write the above differential equation as\n\n$$\n\\frac{d^2y}{dt^2}=a(t,y(t),\\frac{dy}{dt}).\n$$\n\nWith given initial conditions for $y(t_0)$ and $v(t_0)$ we can then\nintegrate the above equation and find the velocities and positions at\na given time $t$.\n\nIf we multiply with mass, we have one of the famous expressions for Newton's second law,\n\n$$\nF(y,v,t)=m\\frac{d^2y}{dt^2}=ma(t,y(t),\\frac{dy}{dt}),\n$$\n\nwhere $F$ is the force acting on an object with mass $m$. We see that it also has the right dimension, mass times length divided by time squared.\nWe will come back to this soon.\n\n\n## Integrating our equations\n\nFormally we can then, starting with the acceleration (suppose we have measured it, how could we do that?)\ncompute say the height of a building. To see this we perform the following integrations from an initial time $t_0$ to a given time $t$\n\n$$\n\\int_{t_0}^t dt a(t) = \\int_{t_0}^t dt \\frac{dv}{dt} = v(t)-v(t_0),\n$$\n\nor as\n\n$$\nv(t)=v(t_0)+\\int_{t_0}^t dt a(t).\n$$\n\nWhen we know the velocity as function of time, we can find the position as function of time starting from the defintion of velocity as the derivative with respect to time, that is we have\n\n$$\n\\int_{t_0}^t dt v(t) = \\int_{t_0}^t dt \\frac{dy}{dt} = y(t)-y(t_0),\n$$\n\nor as\n\n$$\ny(t)=y(t_0)+\\int_{t_0}^t dt v(t).\n$$\n\nThese equations define what is called the integration method for\nfinding the position and the velocity as functions of time. There is\nno loss of generality if we extend these equations to more than one\nspatial dimension.\n\n\n## Constant acceleration case, the velocity\n\nLet us compute the velocity using the constant value for the acceleration given by $-g$. We have\n\n$$\nv(t)=v(t_0)+\\int_{t_0}^t dt a(t)=v(t_0)+\\int_{t_0}^t dt (-g).\n$$\n\nUsing our initial time as $t_0=0$s and setting the initial velocity $v(t_0)=v_0=0$m/s we get when integrating\n\n$$\nv(t)=-gt.\n$$\n\nThe more general case is\n\n$$\nv(t)=v_0-g(t-t_0).\n$$\n\nWe can then integrate the velocity and obtain the final formula for the position as function of time through\n\n$$\ny(t)=y(t_0)+\\int_{t_0}^t dt v(t)=y_0+\\int_{t_0}^t dt v(t)=y_0+\\int_{t_0}^t dt (-gt),\n$$\n\nWith $y_0=10$m and $t_0=0$s, we obtain the equation we started with\n\n$$\ny(t)=10-\\frac{1}{2}gt^2.\n$$\n\n## Computing the averages\n\nAfter this mathematical background we are now ready to compute the mean velocity using our data.\n\n\n```\n# Now we can compute the mean velocity using our data\n# We define first an array Vaverage\nn = np.size(t)\nVaverage = np.zeros(n)\nfor i in range(1,n-1):\n Vaverage[i] = (y[i+1]-y[i])/DeltaT\n# Now we can compute the mean accelearatio using our data\n# We define first an array Aaverage\nn = np.size(t)\nAaverage = np.zeros(n)\nAaverage[0] = -g\nfor i in range(1,n-1):\n Aaverage[i] = (Vaverage[i+1]-Vaverage[i])/DeltaT\ndata = {'t[s]': t,\n 'y[m]': y,\n 'v[m/s]': Vaverage,\n 'a[m/s^2]': Aaverage\n }\nNewData = pd.DataFrame(data)\ndisplay(NewData[0:n-2])\n```\n\nNote that we don't print the last values! \n\n\n\n\n## Including Air Resistance in our model\n\nIn our discussions till now of the falling baseball, we have ignored\nair resistance and simply assumed that our system is only influenced\nby the gravitational force. We will postpone the derivation of air\nresistance till later, after our discussion of Newton's laws and\nforces.\n\nFor our discussions here it suffices to state that the accelerations is now modified to\n\n$$\n\\boldsymbol{a}(t) = -g +D\\boldsymbol{v}(t)\\vert v(t)\\vert,\n$$\n\nwhere $\\vert v(t)\\vert$ is the absolute value of the velocity and $D$ is a constant which pertains to the specific object we are studying.\nSince we are dealing with motion in one dimension, we can simplify the above to\n\n$$\na(t) = -g +Dv^2(t).\n$$\n\nWe can rewrite this as a differential equation\n\n$$\na(t) = \\frac{dv}{dt}=\\frac{d^2y}{dt^2}= -g +Dv^2(t).\n$$\n\nUsing the integral equations discussed above we can integrate twice\nand obtain first the velocity as function of time and thereafter the\nposition as function of time.\n\nFor this particular case, we can actually obtain an analytical\nsolution for the velocity and for the position. Here we will first\ncompute the solutions analytically, thereafter we will derive Euler's\nmethod for solving these differential equations numerically.\n\n\n## Analytical solutions\n\nFor simplicity let us just write $v(t)$ as $v$. We have\n\n$$\n\\frac{dv}{dt}= -g +Dv^2(t).\n$$\n\nWe can solve this using the technique of separation of variables. We\nisolate on the left all terms that involve $v$ and on the right all\nterms that involve time. We get then\n\n$$\n\\frac{dv}{g -Dv^2(t) }= -dt,\n$$\n\nWe scale now the equation to the left by introducing a constant\n$v_T=\\sqrt{g/D}$. This constant has dimension length/time. Can you\nshow this?\n\nNext we integrate the left-hand side (lhs) from $v_0=0$ m/s to $v$ and\nthe right-hand side (rhs) from $t_0=0$ to $t$ and obtain\n\n$$\n\\int_{0}^v\\frac{dv}{g -Dv^2(t) }= \\frac{v_T}{g}\\mathrm{arctanh}(\\frac{v}{v_T}) =-\\int_0^tdt = -t.\n$$\n\nWe can reorganize these equations as\n\n$$\nv_T\\mathrm{arctanh}(\\frac{v}{v_T}) =-gt,\n$$\n\nwhich gives us $v$ as function of time\n\n$$\nv(t)=v_T\\tanh{-(\\frac{gt}{v_T})}.\n$$\n\n## Finding the final height\n\nWith the velocity we can then find the height $y(t)$ by integrating yet another time, that is\n\n$$\ny(t)=y(t_0)+\\int_{t_0}^t dt v(t)=\\int_{0}^t dt[v_T\\tanh{-(\\frac{gt}{v_T})}].\n$$\n\nThis integral is a little bit trickier but we can look it up in a table over \nknown integrals and we get\n\n$$\ny(t)=y(t_0)-\\frac{v_T^2}{g}\\log{[\\cosh{(\\frac{gt}{v_T})}]}.\n$$\n\nAlternatively we could have used the symbolic Python package **Sympy** (example will be inserted later). \n\nIn most cases however, we need to revert to numerical solutions. \n\n\n\n## Our first attempt at solving differential equations\n\nHere we will try the simplest possible approach to solving the second-order differential \nequation\n\n$$\na(t) =\\frac{d^2y}{dt^2}= -g +Dv^2(t).\n$$\n\nWe rewrite it as two coupled first-order equations (this is a standard approach)\n\n$$\n\\frac{dy}{dt} = v(t),\n$$\n\nwith initial condition $y(t_0)=y_0$ and\n\n$$\na(t) =\\frac{dv}{dt}= -g +Dv^2(t),\n$$\n\nwith initial condition $v(t_0)=v_0$.\n\nMany of the algorithms for solving differential equations start with simple Taylor equations.\nIf we now Taylor expand $y$ and $v$ around a value $t+\\Delta t$ we have\n\n$$\ny(t+\\Delta t) = y(t)+\\Delta t \\frac{dy}{dt}+\\frac{\\Delta t^2}{2!} \\frac{d^2y}{dt^2}+O(\\Delta t^3),\n$$\n\nand\n\n$$\nv(t+\\Delta t) = v(t)+\\Delta t \\frac{dv}{dt}+\\frac{\\Delta t^2}{2!} \\frac{d^2v}{dt^2}+O(\\Delta t^3).\n$$\n\nUsing the fact that $dy/dt = v$ and $dv/dt=a$ and keeping only terms up to $\\Delta t$ we have\n\n$$\ny(t+\\Delta t) = y(t)+\\Delta t v(t)+O(\\Delta t^2),\n$$\n\nand\n\n$$\nv(t+\\Delta t) = v(t)+\\Delta t a(t)+O(\\Delta t^2).\n$$\n\n## Discretizing our equations\n\nUsing our discretized versions of the equations with for example\n$y_{i}=y(t_i)$ and $y_{i\\pm 1}=y(t_i+\\Delta t)$, we can rewrite the\nabove equations as (and truncating at $\\Delta t$)\n\n$$\ny_{i+1} = y_i+\\Delta t v_i,\n$$\n\nand\n\n$$\nv_{i+1} = v_i+\\Delta t a_i.\n$$\n\nThese are the famous Euler equations (forward Euler).\n\nTo solve these equations numerically we start at a time $t_0$ and simply integrate up these equations to a final time $t_f$,\nThe step size $\\Delta t$ is an input parameter in our code.\nYou can define it directly in the code below as\n\n\n```\nDeltaT = 0.1\n```\n\nWith a given final time **tfinal** we can then find the number of integration points via the **ceil** function included in the **math** package of Python\nas\n\n\n```\n#define final time, assuming that initial time is zero\nfrom math import ceil\ntfinal = 0.5\nn = ceil(tfinal/DeltaT)\nprint(n)\n```\n\nThe **ceil** function returns the smallest integer not less than the input in say\n\n\n```\nx = 21.15\nprint(ceil(x))\n```\n\nwhich in the case here is 22.\n\n\n```\nx = 21.75\nprint(ceil(x))\n```\n\nwhich also yields 22. The **floor** function in the **math** package\nis used to return the closest integer value which is less than or equal to the specified expression or value.\nCompare the previous result to the usage of **floor**\n\n\n```\nfrom math import floor\nx = 21.75\nprint(floor(x))\n```\n\nAlternatively, we can define ourselves the number of integration(mesh) points. In this case we could have\n\n\n```\nn = 10\ntinitial = 0.0\ntfinal = 0.5\nDeltaT = (tfinal-tinitial)/(n)\nprint(DeltaT)\n```\n\nSince we will set up one-dimensional arrays that contain the values of\nvarious variables like time, position, velocity, acceleration etc, we\nneed to know the value of $n$, the number of data points (or\nintegration or mesh points). With $n$ we can initialize a given array\nby setting all elelements to zero, as done here\n\n\n```\n# define array a\na = np.zeros(n)\nprint(a)\n```\n\n## Code for implementing Euler's method\nIn the code here we implement this simple Eurler scheme choosing a value for $D=0.0245$ m/s.\n\n\n```\n# Common imports\nimport numpy as np\nimport pandas as pd\nfrom math import *\nimport matplotlib.pyplot as plt\nimport os\n\n# Where to save the figures and data files\nPROJECT_ROOT_DIR = \"Results\"\nFIGURE_ID = \"Results/FigureFiles\"\nDATA_ID = \"DataFiles/\"\n\nif not os.path.exists(PROJECT_ROOT_DIR):\n os.mkdir(PROJECT_ROOT_DIR)\n\nif not os.path.exists(FIGURE_ID):\n os.makedirs(FIGURE_ID)\n\nif not os.path.exists(DATA_ID):\n os.makedirs(DATA_ID)\n\ndef image_path(fig_id):\n return os.path.join(FIGURE_ID, fig_id)\n\ndef data_path(dat_id):\n return os.path.join(DATA_ID, dat_id)\n\ndef save_fig(fig_id):\n plt.savefig(image_path(fig_id) + \".png\", format='png')\n\n\ng = 9.80655 #m/s^2\nD = 0.00245 #m/s\nDeltaT = 0.1\n#set up arrays \ntfinal = 0.5\nn = ceil(tfinal/DeltaT)\n# define scaling constant vT\nvT = sqrt(g/D)\n# set up arrays for t, a, v, and y and we can compare our results with analytical ones\nt = np.zeros(n)\na = np.zeros(n)\nv = np.zeros(n)\ny = np.zeros(n)\nyanalytic = np.zeros(n)\n# Initial conditions\nv[0] = 0.0 #m/s\ny[0] = 10.0 #m\nyanalytic[0] = y[0]\n# Start integrating using Euler's method\nfor i in range(n-1):\n # expression for acceleration\n a[i] = -g + D*v[i]*v[i]\n # update velocity and position\n y[i+1] = y[i] + DeltaT*v[i]\n v[i+1] = v[i] + DeltaT*a[i]\n # update time to next time step and compute analytical answer\n t[i+1] = t[i] + DeltaT\n yanalytic[i+1] = y[0]-(vT*vT/g)*log(cosh(g*t[i+1]/vT))\n if ( y[i+1] < 0.0):\n break\na[n-1] = -g + D*v[n-1]*v[n-1]\ndata = {'t[s]': t,\n 'y[m]': y-yanalytic,\n 'v[m/s]': v,\n 'a[m/s^2]': a\n }\nNewData = pd.DataFrame(data)\ndisplay(NewData)\n#finally we plot the data\nfig, axs = plt.subplots(3, 1)\naxs[0].plot(t, y, t, yanalytic)\naxs[0].set_xlim(0, tfinal)\naxs[0].set_ylabel('y and exact')\naxs[1].plot(t, v)\naxs[1].set_ylabel('v[m/s]')\naxs[2].plot(t, a)\naxs[2].set_xlabel('time[s]')\naxs[2].set_ylabel('a[m/s^2]')\nfig.tight_layout()\nsave_fig(\"EulerIntegration\")\nplt.show()\n```\n\nTry different values for $\\Delta t$ and study the difference between the exact solution and the numerical solution.\n\n\n## Simple extension, the Euler-Cromer method\n\nThe Euler-Cromer method is a simple variant of the standard Euler\nmethod. We use the newly updated velocity $v_{i+1}$ as an input to the\nnew position, that is, instead of\n\n$$\ny_{i+1} = y_i+\\Delta t v_i,\n$$\n\nand\n\n$$\nv_{i+1} = v_i+\\Delta t a_i,\n$$\n\nwe use now the newly calculate for $v_{i+1}$ as input to $y_{i+1}$, that is \nwe compute first\n\n$$\nv_{i+1} = v_i+\\Delta t a_i,\n$$\n\nand then\n\n$$\ny_{i+1} = y_i+\\Delta t v_{i+1},\n$$\n\nImplementing the Euler-Cromer method yields a simple change to the previous code. We only need to change the following line in the loop over time\nsteps\n\n\n```\nfor i in range(n-1):\n # more codes in between here\n v[i+1] = v[i] + DeltaT*a[i]\n y[i+1] = y[i] + DeltaT*v[i+1]\n # more code\n```\n\n## Python practicalities, Software and needed installations\n\nWe will make extensive use of Python as programming language and its\nmyriad of available libraries. You will find\nJupyter notebooks invaluable in your work. \n\nIf you have Python installed (we strongly recommend Python3) and you feel\npretty familiar with installing different packages, we recommend that\nyou install the following Python packages via **pip** as \n\n1. pip install numpy scipy matplotlib ipython scikit-learn mglearn sympy pandas pillow \n\nFor Python3, replace **pip** with **pip3**.\n\nFor OSX users we recommend, after having installed Xcode, to\ninstall **brew**. Brew allows for a seamless installation of additional\nsoftware via for example \n\n1. brew install python3\n\nFor Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution,\nyou can use **pip** as well and simply install Python as \n\n1. sudo apt-get install python3 (or python for pyhton2.7)\n\netc etc. \n\n\n\n## Python installers\n\nIf you don't want to perform these operations separately and venture\ninto the hassle of exploring how to set up dependencies and paths, we\nrecommend two widely used distrubutions which set up all relevant\ndependencies for Python, namely \n\n* [Anaconda](https://docs.anaconda.com/), \n\nwhich is an open source\ndistribution of the Python and R programming languages for large-scale\ndata processing, predictive analytics, and scientific computing, that\naims to simplify package management and deployment. Package versions\nare managed by the package management system **conda**. \n\n* [Enthought canopy](https://www.enthought.com/product/canopy/) \n\nis a Python\ndistribution for scientific and analytic computing distribution and\nanalysis environment, available for free and under a commercial\nlicense.\n\nFurthermore, [Google's Colab](https://colab.research.google.com/notebooks/welcome.ipynb) is a free Jupyter notebook environment that requires \nno setup and runs entirely in the cloud. Try it out!\n\n## Useful Python libraries\nHere we list several useful Python libraries we strongly recommend (if you use anaconda many of these are already there)\n\n* [NumPy](https://www.numpy.org/) is a highly popular library for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays\n\n* [The pandas](https://pandas.pydata.org/) library provides high-performance, easy-to-use data structures and data analysis tools \n\n* [Xarray](http://xarray.pydata.org/en/stable/) is a Python package that makes working with labelled multi-dimensional arrays simple, efficient, and fun!\n\n* [Scipy](https://www.scipy.org/) (pronounced “Sigh Pie”) is a Python-based ecosystem of open-source software for mathematics, science, and engineering. \n\n* [Matplotlib](https://matplotlib.org/) is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.\n\n* [Autograd](https://github.com/HIPS/autograd) can automatically differentiate native Python and Numpy code. It can handle a large subset of Python's features, including loops, ifs, recursion and closures, and it can even take derivatives of derivatives of derivatives\n\n* [SymPy](https://www.sympy.org/en/index.html) is a Python library for symbolic mathematics. \n\n* [scikit-learn](https://scikit-learn.org/stable/) has simple and efficient tools for machine learning, data mining and data analysis\n\n* [TensorFlow](https://www.tensorflow.org/) is a Python library for fast numerical computing created and released by Google\n\n* [Keras](https://keras.io/) is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano\n\n* And many more such as [pytorch](https://pytorch.org/), [Theano](https://pypi.org/project/Theano/) etc \n\nYour jupyter notebook can easily be\nconverted into a nicely rendered **PDF** file or a Latex file for\nfurther processing. For example, convert to latex as\n\n pycod jupyter nbconvert filename.ipynb --to latex \n\n\nAnd to add more versatility, the Python package [SymPy](http://www.sympy.org/en/index.html) is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) and is entirely written in Python. \n\n\n\n## Numpy examples and Important Matrix and vector handling packages\n\nThere are several central software libraries for linear algebra and eigenvalue problems. Several of the more\npopular ones have been wrapped into ofter software packages like those from the widely used text **Numerical Recipes**. The original source codes in many of the available packages are often taken from the widely used\nsoftware package LAPACK, which follows two other popular packages\ndeveloped in the 1970s, namely EISPACK and LINPACK. We describe them shortly here.\n\n * LINPACK: package for linear equations and least square problems.\n\n * LAPACK:package for solving symmetric, unsymmetric and generalized eigenvalue problems. From LAPACK's website it is possible to download for free all source codes from this library. Both C/C++ and Fortran versions are available.\n\n * BLAS (I, II and III): (Basic Linear Algebra Subprograms) are routines that provide standard building blocks for performing basic vector and matrix operations. Blas I is vector operations, II vector-matrix operations and III matrix-matrix operations. Highly parallelized and efficient codes, all available for download from .\n\n## Basic Matrix Features\n\n**Matrix properties reminder.**\n\n$$\n\\mathbf{A} =\n \\begin{bmatrix} a_{11} & a_{12} & a_{13} & a_{14} \\\\\n a_{21} & a_{22} & a_{23} & a_{24} \\\\\n a_{31} & a_{32} & a_{33} & a_{34} \\\\\n a_{41} & a_{42} & a_{43} & a_{44}\n \\end{bmatrix}\\qquad\n\\mathbf{I} =\n \\begin{bmatrix} 1 & 0 & 0 & 0 \\\\\n 0 & 1 & 0 & 0 \\\\\n 0 & 0 & 1 & 0 \\\\\n 0 & 0 & 0 & 1\n \\end{bmatrix}\n$$\n\nThe inverse of a matrix is defined by\n\n$$\n\\mathbf{A}^{-1} \\cdot \\mathbf{A} = I\n$$\n\n\n\n\n\n\n\n\n\n\n\n\n
Relations Name matrix elements
$A = A^{T}$ symmetric $a_{ij} = a_{ji}$
$A = \\left (A^{T} \\right )^{-1}$ real orthogonal $\\sum_k a_{ik} a_{jk} = \\sum_k a_{ki} a_{kj} = \\delta_{ij}$
$A = A^{ * }$ real matrix $a_{ij} = a_{ij}^{ * }$
$A = A^{\\dagger}$ hermitian $a_{ij} = a_{ji}^{ * }$
$A = \\left (A^{\\dagger} \\right )^{-1}$ unitary $\\sum_k a_{ik} a_{jk}^{ * } = \\sum_k a_{ki}^{ * } a_{kj} = \\delta_{ij}$
\n\n\n\n\n### Some famous Matrices\n\n * Diagonal if $a_{ij}=0$ for $i\\ne j$\n\n * Upper triangular if $a_{ij}=0$ for $i > j$\n\n * Lower triangular if $a_{ij}=0$ for $i < j$\n\n * Upper Hessenberg if $a_{ij}=0$ for $i > j+1$\n\n * Lower Hessenberg if $a_{ij}=0$ for $i < j+1$\n\n * Tridiagonal if $a_{ij}=0$ for $|i -j| > 1$\n\n * Lower banded with bandwidth $p$: $a_{ij}=0$ for $i > j+p$\n\n * Upper banded with bandwidth $p$: $a_{ij}=0$ for $i < j+p$\n\n * Banded, block upper triangular, block lower triangular....\n\n### More Basic Matrix Features\n\n**Some Equivalent Statements.**\n\nFor an $N\\times N$ matrix $\\mathbf{A}$ the following properties are all equivalent\n\n * If the inverse of $\\mathbf{A}$ exists, $\\mathbf{A}$ is nonsingular.\n\n * The equation $\\mathbf{Ax}=0$ implies $\\mathbf{x}=0$.\n\n * The rows of $\\mathbf{A}$ form a basis of $R^N$.\n\n * The columns of $\\mathbf{A}$ form a basis of $R^N$.\n\n * $\\mathbf{A}$ is a product of elementary matrices.\n\n * $0$ is not eigenvalue of $\\mathbf{A}$.\n\n\n\n\n## Numpy and arrays\n[Numpy](http://www.numpy.org/) provides an easy way to handle arrays in Python. The standard way to import this library is as\n\n\n```\nimport numpy as np\n```\n\nHere follows a simple example where we set up an array of ten elements, all determined by random numbers drawn according to the normal distribution,\n\n\n```\nn = 10\nx = np.random.normal(size=n)\nprint(x)\n```\n\nWe defined a vector $x$ with $n=10$ elements with its values given by the Normal distribution $N(0,1)$.\nAnother alternative is to declare a vector as follows\n\n\n```\nimport numpy as np\nx = np.array([1, 2, 3])\nprint(x)\n```\n\nHere we have defined a vector with three elements, with $x_0=1$, $x_1=2$ and $x_2=3$. Note that both Python and C++\nstart numbering array elements from $0$ and on. This means that a vector with $n$ elements has a sequence of entities $x_0, x_1, x_2, \\dots, x_{n-1}$. We could also let (recommended) Numpy to compute the logarithms of a specific array as\n\n\n```\nimport numpy as np\nx = np.log(np.array([4, 7, 8]))\nprint(x)\n```\n\nIn the last example we used Numpy's unary function $np.log$. This function is\nhighly tuned to compute array elements since the code is vectorized\nand does not require looping. We normaly recommend that you use the\nNumpy intrinsic functions instead of the corresponding **log** function\nfrom Python's **math** module. The looping is done explicitely by the\n**np.log** function. The alternative, and slower way to compute the\nlogarithms of a vector would be to write\n\n\n```\nimport numpy as np\nfrom math import log\nx = np.array([4, 7, 8])\nfor i in range(0, len(x)):\n x[i] = log(x[i])\nprint(x)\n```\n\nWe note that our code is much longer already and we need to import the **log** function from the **math** module. \nThe attentive reader will also notice that the output is $[1, 1, 2]$. Python interprets automagically our numbers as integers (like the **automatic** keyword in C++). To change this we could define our array elements to be double precision numbers as\n\n\n```\nimport numpy as np\nx = np.log(np.array([4, 7, 8], dtype = np.float64))\nprint(x)\n```\n\nor simply write them as double precision numbers (Python uses 64 bits as default for floating point type variables), that is\n\n\n```\nimport numpy as np\nx = np.log(np.array([4.0, 7.0, 8.0])\nprint(x)\n```\n\nTo check the number of bytes (remember that one byte contains eight bits for double precision variables), you can use simple use the **itemsize** functionality (the array $x$ is actually an object which inherits the functionalities defined in Numpy) as\n\n\n```\nimport numpy as np\nx = np.log(np.array([4.0, 7.0, 8.0])\nprint(x.itemsize)\n```\n\n## Matrices in Python\n\nHaving defined vectors, we are now ready to try out matrices. We can\ndefine a $3 \\times 3 $ real matrix $\\hat{A}$ as (recall that we user\nlowercase letters for vectors and uppercase letters for matrices)\n\n\n```\nimport numpy as np\nA = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))\nprint(A)\n```\n\nIf we use the **shape** function we would get $(3, 3)$ as output, that is verifying that our matrix is a $3\\times 3$ matrix. We can slice the matrix and print for example the first column (Python organized matrix elements in a row-major order, see below) as\n\n\n```\nimport numpy as np\nA = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))\n# print the first column, row-major order and elements start with 0\nprint(A[:,0])\n```\n\nWe can continue this was by printing out other columns or rows. The example here prints out the second column\n\n\n```\nimport numpy as np\nA = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))\n# print the first column, row-major order and elements start with 0\nprint(A[1,:])\n```\n\nNumpy contains many other functionalities that allow us to slice, subdivide etc etc arrays. We strongly recommend that you look up the [Numpy website for more details](http://www.numpy.org/). Useful functions when defining a matrix are the **np.zeros** function which declares a matrix of a given dimension and sets all elements to zero\n\n\n```\nimport numpy as np\nn = 10\n# define a matrix of dimension 10 x 10 and set all elements to zero\nA = np.zeros( (n, n) )\nprint(A)\n```\n\nor initializing all elements to\n\n\n```\nimport numpy as np\nn = 10\n# define a matrix of dimension 10 x 10 and set all elements to one\nA = np.ones( (n, n) )\nprint(A)\n```\n\nor as unitarily distributed random numbers (see the material on random number generators in the statistics part)\n\n\n```\nimport numpy as np\nn = 10\n# define a matrix of dimension 10 x 10 and set all elements to random numbers with x \\in [0, 1]\nA = np.random.rand(n, n)\nprint(A)\n```\n\n## Meet the Pandas\n\n\n\n\n\n

\n\n\n\n\n\nAnother useful Python package is\n[pandas](https://pandas.pydata.org/), which is an open source library\nproviding high-performance, easy-to-use data structures and data\nanalysis tools for Python. **pandas** stands for panel data, a term borrowed from econometrics and is an efficient library for data analysis with an emphasis on tabular data.\n**pandas** has two major classes, the **DataFrame** class with two-dimensional data objects and tabular data organized in columns and the class **Series** with a focus on one-dimensional data objects. Both classes allow you to index data easily as we will see in the examples below. \n**pandas** allows you also to perform mathematical operations on the data, spanning from simple reshapings of vectors and matrices to statistical operations. \n\nThe following simple example shows how we can, in an easy way make tables of our data. Here we define a data set which includes names, place of birth and date of birth, and displays the data in an easy to read way. We will see repeated use of **pandas**, in particular in connection with classification of data.\n\n\n```\nimport pandas as pd\nfrom IPython.display import display\ndata = {'First Name': [\"Frodo\", \"Bilbo\", \"Aragorn II\", \"Samwise\"],\n 'Last Name': [\"Baggins\", \"Baggins\",\"Elessar\",\"Gamgee\"],\n 'Place of birth': [\"Shire\", \"Shire\", \"Eriador\", \"Shire\"],\n 'Date of Birth T.A.': [2968, 2890, 2931, 2980]\n }\ndata_pandas = pd.DataFrame(data)\ndisplay(data_pandas)\n```\n\nIn the above we have imported **pandas** with the shorthand **pd**, the latter has become the standard way we import **pandas**. We make then a list of various variables\nand reorganize the above lists into a **DataFrame** and then print out a neat table with specific column labels as *Name*, *place of birth* and *date of birth*.\nDisplaying these results, we see that the indices are given by the default numbers from zero to three.\n**pandas** is extremely flexible and we can easily change the above indices by defining a new type of indexing as\n\n\n```\ndata_pandas = pd.DataFrame(data,index=['Frodo','Bilbo','Aragorn','Sam'])\ndisplay(data_pandas)\n```\n\nThereafter we display the content of the row which begins with the index **Aragorn**\n\n\n```\ndisplay(data_pandas.loc['Aragorn'])\n```\n\nWe can easily append data to this, for example\n\n\n```\nnew_hobbit = {'First Name': [\"Peregrin\"],\n 'Last Name': [\"Took\"],\n 'Place of birth': [\"Shire\"],\n 'Date of Birth T.A.': [2990]\n }\ndata_pandas=data_pandas.append(pd.DataFrame(new_hobbit, index=['Pippin']))\ndisplay(data_pandas)\n```\n\nHere are other examples where we use the **DataFrame** functionality to handle arrays, now with more interesting features for us, namely numbers. We set up a matrix \nof dimensionality $10\\times 5$ and compute the mean value and standard deviation of each column. Similarly, we can perform mathematial operations like squaring the matrix elements and many other operations.\n\n\n```\nimport numpy as np\nimport pandas as pd\nfrom IPython.display import display\nnp.random.seed(100)\n# setting up a 10 x 5 matrix\nrows = 10\ncols = 5\na = np.random.randn(rows,cols)\ndf = pd.DataFrame(a)\ndisplay(df)\nprint(df.mean())\nprint(df.std())\ndisplay(df**2)\n```\n\nThereafter we can select specific columns only and plot final results\n\n\n```\ndf.columns = ['First', 'Second', 'Third', 'Fourth', 'Fifth']\ndf.index = np.arange(10)\n\ndisplay(df)\nprint(df['Second'].mean() )\nprint(df.info())\nprint(df.describe())\n\nfrom pylab import plt, mpl\nplt.style.use('seaborn')\nmpl.rcParams['font.family'] = 'serif'\n\ndf.cumsum().plot(lw=2.0, figsize=(10,6))\nplt.show()\n\n\ndf.plot.bar(figsize=(10,6), rot=15)\nplt.show()\n```\n\nWe can produce a $4\\times 4$ matrix\n\n\n```\nb = np.arange(16).reshape((4,4))\nprint(b)\ndf1 = pd.DataFrame(b)\nprint(df1)\n```\n\nand many other operations. \n\nThe **Series** class is another important class included in\n**pandas**. You can view it as a specialization of **DataFrame** but where\nwe have just a single column of data. It shares many of the same features as _DataFrame. As with **DataFrame**,\nmost operations are vectorized, achieving thereby a high performance when dealing with computations of arrays, in particular labeled arrays.\nAs we will see below it leads also to a very concice code close to the mathematical operations we may be interested in.\nFor multidimensional arrays, we recommend strongly [xarray](http://xarray.pydata.org/en/stable/). **xarray** has much of the same flexibility as **pandas**, but allows for the extension to higher dimensions than two.\n\n\n\n\n\n\n# Basic Steps of Scientific Investigations\n\nAn overarching aim in this course is to give you a deeper\nunderstanding of the scientific method. The problems we study will all\ninvolve cases where we can apply classical mechanics. In our previous\nmaterial we already assumed that we had a model for the motion of an\nobject. Alternatively we could have data from experiment (like Usain\nBolt's 100m world record run in 2008). Or we could have performed\nourselves an experiment and we want to understand which forces are at\nplay and whether these forces can be understood in terms of\nfundamental forces.\n\nOur first step consists in identifying the problem. What we sketch\nhere may include a mix of experiment and theoretical simulations, or\njust experiment or only theory.\n\n\n## Identifying our System\n\nHere we can ask questions like\n1. What kind of object is moving\n\n2. What kind of data do we have\n\n3. How do we measure position, velocity, acceleration etc\n\n4. Which initial conditions influence our system\n\n5. Other aspects which allow us to identify the system\n\n## Defining a Model\n\nWith our eventual data and observations we would now like to develop a\nmodel for the system. In the end we want obviously to be able to\nunderstand which forces are at play and how they influence our\nspecific system. That is, can we extract some deeper insights about a\nsystem?\n\nWe need then to\n1. Find the forces that act on our system\n\n2. Introduce models for the forces\n\n3. Identify the equations which can govern the system (Newton's second law for example)\n\n4. More elements we deem important for defining our model\n\n## Solving the Equations\n\nWith the model at hand, we can then solve the equations. In classical mechanics we normally end up with solving sets of coupled ordinary differential equations or partial differential equations.\n1. Using Newton's second law we have equations of the type $\\boldsymbol{F}=m\\boldsymbol{a}=md\\boldsymbol{v}/dt$\n\n2. We need to define the initial conditions (typically the initial velocity and position as functions of time) and/or initial conditions and boundary conditions\n\n3. The solution of the equations give us then the position, the velocity and other time-dependent quantities which may specify the motion of a given object.\n\nWe are not yet done. With our lovely solvers, we need to start thinking.\n\n\nNow it is time to ask the big questions. What do our results mean? Can we give a simple interpretation in terms of fundamental laws? What do our results mean? Are they correct?\nThus, typical questions we may ask are\n1. Are our results for say $\\boldsymbol{r}(t)$ valid? Do we trust what we did? Can you validate and verify the correctness of your results?\n\n2. Evaluate the answers and their implications\n\n3. Compare with experimental data if possible. Does our model make sense?\n\n4. and obviously many other questions.\n\nThe analysis stage feeds back to the first stage. It may happen that\nthe data we had were not good enough, there could be large statistical\nuncertainties. We may need to collect more data or perhaps we did a\nsloppy job in identifying the degrees of freedom.\n\nAll these steps are essential elements in a scientific\nenquiry. Hopefully, through a mix of numerical simulations, analytical\ncalculations and experiments we may gain a deeper insight about the\nphysics of a specific system.\n\nLet us now remind ourselves of Newton's laws, since these are the laws of motion we will study in this course.\n\n\n## Newton's Laws\n\nWhen analyzing a physical system we normally start with distinguishing between the object we are studying (we will label this in more general terms as our **system**) and how this system interacts with the environment (which often means everything else!)\n\nIn our investigations we will thus analyze a specific physics problem in terms of the system and the environment.\nIn doing so we need to identify the forces that act on the system and assume that the\nforces acting on the system must have a source, an identifiable cause in\nthe environment.\n\nA force acting on for example a falling object must be related to an interaction with something in the environment.\nThis also means that we do not consider internal forces. The latter are forces between\none part of the object and another part. In this course we will mainly focus on external forces.\n\nForces are either contact forces or long-range forces.\n\nContact forces, as evident from the name, are forces that occur at the contact between\nthe system and the environment. Well-known long-range forces are the gravitional force and the electromagnetic force.\n\n\n\n## Setting up a model for forces acting on an object\n\nIn order to set up the forces which act on an object, the following steps may be useful\n1. Divide the problem into system and environment.\n\n2. Draw a figure of the object and everything in contact with the object.\n\n3. Draw a closed curve around the system.\n\n4. Find contact points—these are the points where contact forces may act.\n\n5. Give names and symbols to all the contact forces.\n\n6. Identify the long-range forces.\n\n7. Make a drawing of the object. Draw the forces as arrows, vectors, starting from where the force is acting. The direction of the vector(s) indicates the (positive) direction of the force. Try to make the length of the arrow indicate the relative magnitude of the forces.\n\n8. Draw in the axes of the coordinate system. It is often convenient to make one axis parallel to the direction of motion. When you choose the direction of the axis you also choose the positive direction for the axis.\n\n## Newton's Laws, the Second one first\n\n\nNewton’s second law of motion: The force $\\boldsymbol{F}$ on an object of inertial mass $m$\nis related to the acceleration a of the object through\n\n$$\n\\boldsymbol{F} = m\\boldsymbol{a},\n$$\n\nwhere $\\boldsymbol{a}$ is the acceleration.\n\nNewton’s laws of motion are laws of nature that have been found by experimental\ninvestigations and have been shown to hold up to continued experimental investigations.\nNewton’s laws are valid over a wide range of length- and time-scales. We\nuse Newton’s laws of motion to describe everything from the motion of atoms to the\nmotion of galaxies.\n\nThe second law is a vector equation with the acceleration having the same\ndirection as the force. The acceleration is proportional to the force via the mass $m$ of the system under study.\n\n\nNewton’s second law introduces a new property of an object, the so-called \ninertial mass $m$. We determine the inertial mass of an object by measuring the\nacceleration for a given applied force.\n\n\n\n## Then the First Law\n\n\nWhat happens if the net external force on a body is zero? Applying Newton’s second\nlaw, we find:\n\n$$\n\\boldsymbol{F} = 0 = m\\boldsymbol{a},\n$$\n\nwhich gives using the definition of the acceleration\n\n$$\n\\boldsymbol{a} = \\frac{d\\boldsymbol{v}}{dt}=0.\n$$\n\nThe acceleration is zero, which means that the velocity of the object is constant. This\nis often referred to as Newton’s first law. An object in a state of uniform motion tends to remain in\nthat state unless an external force changes its state of motion.\nWhy do we need a separate law for this? Is it not simply a special case of Newton’s\nsecond law? Yes, Newton’s first law can be deduced from the second law as we have\nillustrated. However, the first law is often used for a different purpose: Newton’s\nFirst Law tells us about the limit of applicability of Newton’s Second law. Newton’s\nSecond law can only be used in reference systems where the First law is obeyed. But\nis not the First law always valid? No! The First law is only valid in reference systems\nthat are not accelerated. If you observe the motion of a ball from an accelerating\ncar, the ball will appear to accelerate even if there are no forces acting on it. We call\nsystems that are not accelerating inertial systems, and Newton’s first law is often\ncalled the law of inertia. Newton’s first and second laws of motion are only valid in\ninertial systems. \n\nA system is an inertial system if it is not accelerated. It means that the reference system\nmust not be accelerating linearly or rotating. Unfortunately, this means that most\nsystems we know are not really inertial systems. For example, the surface of the\nEarth is clearly not an inertial system, because the Earth is rotating. The Earth is also\nnot an inertial system, because it ismoving in a curved path around the Sun. However,\neven if the surface of the Earth is not strictly an inertial system, it may be considered\nto be approximately an inertial system for many laboratory-size experiments.\n\n\n## And finally the Third Law\n\n\nIf there is a force from object A on object B, there is also a force from object B on object A.\nThis fundamental principle of interactions is called Newton’s third law. We do not\nknow of any force that do not obey this law: All forces appear in pairs. Newton’s\nthird law is usually formulated as: For every action there is an equal and opposite\nreaction.\n\n\n\n## Motion of a Single Object\n\nHere we consider the motion of a single particle moving under\nthe influence of some set of forces. We will consider some problems where\nthe force does not depend on the position. In that case Newton's law\n$m\\dot{\\boldsymbol{v}}=\\boldsymbol{F}(\\boldsymbol{v})$ is a first-order differential\nequation and one solves for $\\boldsymbol{v}(t)$, then moves on to integrate\n$\\boldsymbol{v}$ to get the position. In essentially all of these cases we cna find an analytical solution.\n\n\n\n## Air Resistance in One Dimension\n\nAir resistance tends to scale as the square of the velocity. This is\nin contrast to many problems chosen for textbooks, where it is linear\nin the velocity. The choice of a linear dependence is motivated by\nmathematical simplicity (it keeps the differential equation linear)\nrather than by physics. One can see that the force should be quadratic\nin velocity by considering the momentum imparted on the air\nmolecules. If an object sweeps through a volume $dV$ of air in time\n$dt$, the momentum imparted on the air is\n\n\n
\n\n$$\n\\begin{equation}\ndP=\\rho_m dV v,\n\\label{_auto1} \\tag{1}\n\\end{equation}\n$$\n\nwhere $v$ is the velocity of the object and $\\rho_m$ is the mass\ndensity of the air. If the molecules bounce back as opposed to stop\nyou would double the size of the term. The opposite value of the\nmomentum is imparted onto the object itself. Geometrically, the\ndifferential volume is\n\n\n
\n\n$$\n\\begin{equation}\ndV=Avdt,\n\\label{_auto2} \\tag{2}\n\\end{equation}\n$$\n\nwhere $A$ is the cross-sectional area and $vdt$ is the distance the\nobject moved in time $dt$.\n\n\n## Resulting Acceleration\nPlugging this into the expression above,\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{dP}{dt}=-\\rho_m A v^2.\n\\label{_auto3} \\tag{3}\n\\end{equation}\n$$\n\nThis is the force felt by the particle, and is opposite to its\ndirection of motion. Now, because air doesn't stop when it hits an\nobject, but flows around the best it can, the actual force is reduced\nby a dimensionless factor $c_W$, called the drag coefficient.\n\n\n
\n\n$$\n\\begin{equation}\nF_{\\rm drag}=-c_W\\rho_m Av^2,\n\\label{_auto4} \\tag{4}\n\\end{equation}\n$$\n\nand the acceleration is\n\n$$\n\\begin{eqnarray}\n\\frac{dv}{dt}=-\\frac{c_W\\rho_mA}{m}v^2.\n\\end{eqnarray}\n$$\n\nFor a particle with initial velocity $v_0$, one can separate the $dt$\nto one side of the equation, and move everything with $v$s to the\nother side. We did this in our discussion of simple motion and will not repeat it here.\n\nOn more general terms,\nfor many systems, e.g. an automobile, there are multiple sources of\nresistance. In addition to wind resistance, where the force is\nproportional to $v^2$, there are dissipative effects of the tires on\nthe pavement, and in the axel and drive train. These other forces can\nhave components that scale proportional to $v$, and components that\nare independent of $v$. Those independent of $v$, e.g. the usual\n$f=\\mu_K N$ frictional force you consider in your first Physics courses, only set in\nonce the object is actually moving. As speeds become higher, the $v^2$\ncomponents begin to dominate relative to the others. For automobiles\nat freeway speeds, the $v^2$ terms are largely responsible for the\nloss of efficiency. To travel a distance $L$ at fixed speed $v$, the\nenergy/work required to overcome the dissipative forces are $fL$,\nwhich for a force of the form $f=\\alpha v^n$ becomes\n\n$$\n\\begin{eqnarray}\nW=\\int dx~f=\\alpha v^n L.\n\\end{eqnarray}\n$$\n\nFor $n=0$ the work is\nindependent of speed, but for the wind resistance, where $n=2$,\nslowing down is essential if one wishes to reduce fuel consumption. It\nis also important to consider that engines are designed to be most\nefficient at a chosen range of power output. Thus, some cars will get\nbetter mileage at higher speeds (They perform better at 50 mph than at\n5 mph) despite the considerations mentioned above.\n\n\n## Going Ballistic, Projectile Motion or a Softer Approach, Falling Raindrops\n\n\nAs an example of Newton's Laws we consider projectile motion (or a\nfalling raindrop or a ball we throw up in the air) with a drag force. Even though air resistance is\nlargely proportional to the square of the velocity, we will consider\nthe drag force to be linear to the velocity, $\\boldsymbol{F}=-m\\gamma\\boldsymbol{v}$,\nfor the purposes of this exercise. The acceleration for a projectile moving upwards,\n$\\boldsymbol{a}=\\boldsymbol{F}/m$, becomes\n\n$$\n\\begin{eqnarray}\n\\frac{dv_x}{dt}=-\\gamma v_x,\\\\\n\\nonumber\n\\frac{dv_y}{dt}=-\\gamma v_y-g,\n\\end{eqnarray}\n$$\n\nand $\\gamma$ has dimensions of inverse time. \n\nIf you on the other hand have a falling raindrop, how do these equations change? See for example Figure 2.1 in Taylor.\nLet us stay with a ball which is thrown up in the air at $t=0$. \n\n\n## Ways of solving these equations\n\nWe will go over two different ways to solve this equation. The first\nby direct integration, and the second as a differential equation. To\ndo this by direct integration, one simply multiplies both sides of the\nequations above by $dt$, then divide by the appropriate factors so\nthat the $v$s are all on one side of the equation and the $dt$ is on\nthe other. For the $x$ motion one finds an easily integrable equation,\n\n$$\n\\begin{eqnarray}\n\\frac{dv_x}{v_x}&=&-\\gamma dt,\\\\\n\\nonumber\n\\int_{v_{0x}}^{v_{x}}\\frac{dv_x}{v_x}&=&-\\gamma\\int_0^{t}dt,\\\\\n\\nonumber\n\\ln\\left(\\frac{v_{x}}{v_{0x}}\\right)&=&-\\gamma t,\\\\\n\\nonumber\nv_{x}(t)&=&v_{0x}e^{-\\gamma t}.\n\\end{eqnarray}\n$$\n\nThis is very much the result you would have written down\nby inspection. For the $y$-component of the velocity,\n\n$$\n\\begin{eqnarray}\n\\frac{dv_y}{v_y+g/\\gamma}&=&-\\gamma dt\\\\\n\\nonumber\n\\ln\\left(\\frac{v_{y}+g/\\gamma}{v_{0y}-g/\\gamma}\\right)&=&-\\gamma t_f,\\\\\n\\nonumber\nv_{fy}&=&-\\frac{g}{\\gamma}+\\left(v_{0y}+\\frac{g}{\\gamma}\\right)e^{-\\gamma t}.\n\\end{eqnarray}\n$$\n\nWhereas $v_x$ starts at some value and decays\nexponentially to zero, $v_y$ decays exponentially to the terminal\nvelocity, $v_t=-g/\\gamma$.\n\n\n## Solving as differential equations\n\nAlthough this direct integration is simpler than the method we invoke\nbelow, the method below will come in useful for some slightly more\ndifficult differential equations in the future. The differential\nequation for $v_x$ is straight-forward to solve. Because it is first\norder there is one arbitrary constant, $A$, and by inspection the\nsolution is\n\n\n
\n\n$$\n\\begin{equation}\nv_x=Ae^{-\\gamma t}.\n\\label{_auto5} \\tag{5}\n\\end{equation}\n$$\n\nThe arbitrary constants for equations of motion are usually determined\nby the initial conditions, or more generally boundary conditions. By\ninspection $A=v_{0x}$, the initial $x$ component of the velocity.\n\n\n\n## Differential Equations, contn\n\nThe differential equation for $v_y$ is a bit more complicated due to\nthe presence of $g$. Differential equations where all the terms are\nlinearly proportional to a function, in this case $v_y$, or to\nderivatives of the function, e.g., $v_y$, $dv_y/dt$,\n$d^2v_y/dt^2\\cdots$, are called linear differential equations. If\nthere are terms proportional to $v^2$, as would happen if the drag\nforce were proportional to the square of the velocity, the\ndifferential equation is not longer linear. Because this expression\nhas only one derivative in $v$ it is a first-order linear differential\nequation. If a term were added proportional to $d^2v/dt^2$ it would be\na second-order differential equation. In this case we have a term\ncompletely independent of $v$, the gravitational acceleration $g$, and\nthe usual strategy is to first rewrite the equation with all the\nlinear terms on one side of the equal sign,\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{dv_y}{dt}+\\gamma v_y=-g.\n\\label{_auto6} \\tag{6}\n\\end{equation}\n$$\n\n## Splitting into two parts\n\nNow, the solution to the equation can be broken into two\nparts. Because this is a first-order differential equation we know\nthat there will be one arbitrary constant. Physically, the arbitrary\nconstant will be determined by setting the initial velocity, though it\ncould be determined by setting the velocity at any given time. Like\nmost differential equations, solutions are not \"solved\". Instead,\none guesses at a form, then shows the guess is correct. For these\ntypes of equations, one first tries to find a single solution,\ni.e. one with no arbitrary constants. This is called the {\\it\nparticular} solution, $y_p(t)$, though it should really be called\n\"a\" particular solution because there are an infinite number of such\nsolutions. One then finds a solution to the {\\it homogenous} equation,\nwhich is the equation with zero on the right-hand side,\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{dv_{y,h}}{dt}+\\gamma v_{y,h}=0.\n\\label{_auto7} \\tag{7}\n\\end{equation}\n$$\n\nHomogenous solutions will have arbitrary constants. \n\nThe particular solution will solve the same equation as the original\ngeneral equation\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{dv_{y,p}}{dt}+\\gamma v_{y,p}=-g.\n\\label{_auto8} \\tag{8}\n\\end{equation}\n$$\n\nHowever, we don't need find one with arbitrary constants. Hence, it is\ncalled a **particular** solution.\n\nThe sum of the two,\n\n\n
\n\n$$\n\\begin{equation}\nv_y=v_{y,p}+v_{y,h},\n\\label{_auto9} \\tag{9}\n\\end{equation}\n$$\n\nis a solution of the total equation because of the linear nature of\nthe differential equation. One has now found a *general* solution\nencompassing all solutions, because it both satisfies the general\nequation (like the particular solution), and has an arbitrary constant\nthat can be adjusted to fit any initial condition (like the homogneous\nsolution). If the equation were not linear, e.g if there were a term\nsuch as $v_y^2$ or $v_y\\dot{v}_y$, this technique would not work.\n\n\n## More details\n\nReturning to the example above, the homogenous solution is the same as\nthat for $v_x$, because there was no gravitational acceleration in\nthat case,\n\n\n
\n\n$$\n\\begin{equation}\nv_{y,h}=Be^{-\\gamma t}.\n\\label{_auto10} \\tag{10}\n\\end{equation}\n$$\n\nIn this case a particular solution is one with constant velocity,\n\n\n
\n\n$$\n\\begin{equation}\nv_{y,p}=-g/\\gamma.\n\\label{_auto11} \\tag{11}\n\\end{equation}\n$$\n\nNote that this is the terminal velocity of a particle falling from a\ngreat height. The general solution is thus,\n\n\n
\n\n$$\n\\begin{equation}\nv_y=Be^{-\\gamma t}-g/\\gamma,\n\\label{_auto12} \\tag{12}\n\\end{equation}\n$$\n\nand one can find $B$ from the initial velocity,\n\n\n
\n\n$$\n\\begin{equation}\nv_{0y}=B-g/\\gamma,~~~B=v_{0y}+g/\\gamma.\n\\label{_auto13} \\tag{13}\n\\end{equation}\n$$\n\nPlugging in the expression for $B$ gives the $y$ motion given the initial velocity,\n\n\n
\n\n$$\n\\begin{equation}\nv_y=(v_{0y}+g/\\gamma)e^{-\\gamma t}-g/\\gamma.\n\\label{_auto14} \\tag{14}\n\\end{equation}\n$$\n\nIt is easy to see that this solution has $v_y=v_{0y}$ when $t=0$ and\n$v_y=-g/\\gamma$ when $t\\rightarrow\\infty$.\n\nOne can also integrate the two equations to find the coordinates $x$\nand $y$ as functions of $t$,\n\n$$\n\\begin{eqnarray}\nx&=&\\int_0^t dt'~v_{0x}(t')=\\frac{v_{0x}}{\\gamma}\\left(1-e^{-\\gamma t}\\right),\\\\\n\\nonumber\ny&=&\\int_0^t dt'~v_{0y}(t')=-\\frac{gt}{\\gamma}+\\frac{v_{0y}+g/\\gamma}{\\gamma}\\left(1-e^{-\\gamma t}\\right).\n\\end{eqnarray}\n$$\n\nIf the question was to find the position at a time $t$, we would be\nfinished. However, the more common goal in a projectile equation\nproblem is to find the range, i.e. the distance $x$ at which $y$\nreturns to zero. For the case without a drag force this was much\nsimpler. The solution for the $y$ coordinate would have been\n$y=v_{0y}t-gt^2/2$. One would solve for $t$ to make $y=0$, which would\nbe $t=2v_{0y}/g$, then plug that value for $t$ into $x=v_{0x}t$ to\nfind $x=2v_{0x}v_{0y}/g=v_0\\sin(2\\theta_0)/g$. One follows the same\nsteps here, except that the expression for $y(t)$ is more\ncomplicated. Searching for the time where $y=0$, and we get\n\n\n
\n\n$$\n\\begin{equation}\n0=-\\frac{gt}{\\gamma}+\\frac{v_{0y}+g/\\gamma}{\\gamma}\\left(1-e^{-\\gamma t}\\right).\n\\label{_auto15} \\tag{15}\n\\end{equation}\n$$\n\nThis cannot be inverted into a simple expression $t=\\cdots$. Such\nexpressions are known as \"transcendental equations\", and are not the\nrare instance, but are the norm. In the days before computers, one\nmight plot the right-hand side of the above graphically as\na function of time, then find the point where it crosses zero.\n\nNow, the most common way to solve for an equation of the above type\nwould be to apply Newton's method numerically. This involves the\nfollowing algorithm for finding solutions of some equation $F(t)=0$.\n\n1. First guess a value for the time, $t_{\\rm guess}$.\n\n2. Calculate $F$ and its derivative, $F(t_{\\rm guess})$ and $F'(t_{\\rm guess})$. \n\n3. Unless you guessed perfectly, $F\\ne 0$, and assuming that $\\Delta F\\approx F'\\Delta t$, one would choose \n\n4. $\\Delta t=-F(t_{\\rm guess})/F'(t_{\\rm guess})$.\n\n5. Now repeat step 1, but with $t_{\\rm guess}\\rightarrow t_{\\rm guess}+\\Delta t$.\n\nIf the $F(t)$ were perfectly linear in $t$, one would find $t$ in one\nstep. Instead, one typically finds a value of $t$ that is closer to\nthe final answer than $t_{\\rm guess}$. One breaks the loop once one\nfinds $F$ within some acceptable tolerance of zero. A program to do\nthis will be added shortly.\n\n\n## Motion in a Magnetic Field\n\n\nAnother example of a velocity-dependent force is magnetism,\n\n$$\n\\begin{eqnarray}\n\\boldsymbol{F}&=&q\\boldsymbol{v}\\times\\boldsymbol{B},\\\\\n\\nonumber\nF_i&=&q\\sum_{jk}\\epsilon_{ijk}v_jB_k.\n\\end{eqnarray}\n$$\n\nFor a uniform field in the $z$ direction $\\boldsymbol{B}=B\\hat{z}$, the force can only have $x$ and $y$ components,\n\n$$\n\\begin{eqnarray}\nF_x&=&qBv_y\\\\\n\\nonumber\nF_y&=&-qBv_x.\n\\end{eqnarray}\n$$\n\nThe differential equations are\n\n$$\n\\begin{eqnarray}\n\\dot{v}_x&=&\\omega_c v_y,\\omega_c= qB/m\\\\\n\\nonumber\n\\dot{v}_y&=&-\\omega_c v_x.\n\\end{eqnarray}\n$$\n\nOne can solve the equations by taking time derivatives of either equation, then substituting into the other equation,\n\n$$\n\\begin{eqnarray}\n\\ddot{v}_x=\\omega_c\\dot{v_y}=-\\omega_c^2v_x,\\\\\n\\nonumber\n\\ddot{v}_y&=&-\\omega_c\\dot{v}_x=-\\omega_cv_y.\n\\end{eqnarray}\n$$\n\nThe solution to these equations can be seen by inspection,\n\n$$\n\\begin{eqnarray}\nv_x&=&A\\sin(\\omega_ct+\\phi),\\\\\n\\nonumber\nv_y&=&A\\cos(\\omega_ct+\\phi).\n\\end{eqnarray}\n$$\n\nOne can integrate the equations to find the positions as a function of time,\n\n$$\n\\begin{eqnarray}\nx-x_0&=&\\int_{x_0}^x dx=\\int_0^t dt v(t)\\\\\n\\nonumber\n&=&\\frac{-A}{\\omega_c}\\cos(\\omega_ct+\\phi),\\\\\n\\nonumber\ny-y_0&=&\\frac{A}{\\omega_c}\\sin(\\omega_ct+\\phi).\n\\end{eqnarray}\n$$\n\nThe trajectory is a circle centered at $x_0,y_0$ with amplitude $A$ rotating in the clockwise direction.\n\nThe equations of motion for the $z$ motion are\n\n\n
\n\n$$\n\\begin{equation}\n\\dot{v_z}=0,\n\\label{_auto16} \\tag{16}\n\\end{equation}\n$$\n\nwhich leads to\n\n\n
\n\n$$\n\\begin{equation}\nz-z_0=V_zt.\n\\label{_auto17} \\tag{17}\n\\end{equation}\n$$\n\nAdded onto the circle, the motion is helical.\n\nNote that the kinetic energy,\n\n\n
\n\n$$\n\\begin{equation}\nT=\\frac{1}{2}m(v_x^2+v_y^2+v_z^2)=\\frac{1}{2}m(\\omega_c^2A^2+V_z^2),\n\\label{_auto18} \\tag{18}\n\\end{equation}\n$$\n\nis constant. This is because the force is perpendicular to the\nvelocity, so that in any differential time element $dt$ the work done\non the particle $\\boldsymbol{F}\\cdot{dr}=dt\\boldsymbol{F}\\cdot{v}=0$.\n\nOne should think about the implications of a velocity dependent\nforce. Suppose one had a constant magnetic field in deep space. If a\nparticle came through with velocity $v_0$, it would undergo cyclotron\nmotion with radius $R=v_0/\\omega_c$. However, if it were still its\nmotion would remain fixed. Now, suppose an observer looked at the\nparticle in one reference frame where the particle was moving, then\nchanged their velocity so that the particle's velocity appeared to be\nzero. The motion would change from circular to fixed. Is this\npossible?\n\nThe solution to the puzzle above relies on understanding\nrelativity. Imagine that the first observer believes $\\boldsymbol{B}\\ne 0$ and\nthat the electric field $\\boldsymbol{E}=0$. If the observer then changes\nreference frames by accelerating to a velocity $\\boldsymbol{v}$, in the new\nframe $\\boldsymbol{B}$ and $\\boldsymbol{E}$ both change. If the observer moved to the\nframe where the charge, originally moving with a small velocity $v$,\nis now at rest, the new electric field is indeed $\\boldsymbol{v}\\times\\boldsymbol{B}$,\nwhich then leads to the same acceleration as one had before. If the\nvelocity is not small compared to the speed of light, additional\n$\\gamma$ factors come into play,\n$\\gamma=1/\\sqrt{1-(v/c)^2}$. Relativistic motion will not be\nconsidered in this course.\n\n\n\n\n## Sliding Block tied to a Wall\n\nAnother classical case is that of simple harmonic oscillations, here represented by a block sliding on a horizontal frictionless surface. The block is tied to a wall with a spring. If the spring is not compressed or stretched too far, the force on the block at a given position $x$ is\n\n$$\nF=-kx.\n$$\n\nThe negative sign means that the force acts to restore the object to an equilibrium position. Newton's equation of motion for this idealized system is then\n\n$$\nm\\frac{d^2x}{dt^2}=-kx,\n$$\n\nor we could rephrase it as\n\n\n
\n\n$$\n\\frac{d^2x}{dt^2}=-\\frac{k}{m}x=-\\omega_0^2x,\n\\label{eq:newton1} \\tag{19}\n$$\n\nwith the angular frequency $\\omega_0^2=k/m$. \n\nThe above differential equation has the advantage that it can be solved analytically with solutions on the form\n\n$$\nx(t)=Acos(\\omega_0t+\\nu),\n$$\n\nwhere $A$ is the amplitude and $\\nu$ the phase constant. This provides in turn an important test for the numerical\nsolution and the development of a program for more complicated cases which cannot be solved analytically. \n\n\nWith the position $x(t)$ and the velocity $v(t)=dx/dt$ we can reformulate Newton's equation in the following way\n\n$$\n\\frac{dx(t)}{dt}=v(t),\n$$\n\nand\n\n$$\n\\frac{dv(t)}{dt}=-\\omega_0^2x(t).\n$$\n\nWe are now going to solve these equations using first the standard forward Euler method. Later we will try to improve upon this.\n\n\nBefore proceeding however, it is important to note that in addition to the exact solution, we have at least two further tests which can be used to check our solution. \n\nSince functions like $cos$ are periodic with a period $2\\pi$, then the solution $x(t)$ has also to be periodic. This means that\n\n$$\nx(t+T)=x(t),\n$$\n\nwith $T$ the period defined as\n\n$$\nT=\\frac{2\\pi}{\\omega_0}=\\frac{2\\pi}{\\sqrt{k/m}}.\n$$\n\nObserve that $T$ depends only on $k/m$ and not on the amplitude of the solution. \n\n\nIn addition to the periodicity test, the total energy has also to be conserved. \n\nSuppose we choose the initial conditions\n\n$$\nx(t=0)=1\\hspace{0.1cm} \\mathrm{m}\\hspace{1cm} v(t=0)=0\\hspace{0.1cm}\\mathrm{m/s},\n$$\n\nmeaning that block is at rest at $t=0$ but with a potential energy\n\n$$\nE_0=\\frac{1}{2}kx(t=0)^2=\\frac{1}{2}k.\n$$\n\nThe total energy at any time $t$ has however to be conserved, meaning that our solution has to fulfil the condition\n\n$$\nE_0=\\frac{1}{2}kx(t)^2+\\frac{1}{2}mv(t)^2.\n$$\n\nWe will derive this equation in our discussion on [energy conservation](https://mhjensen.github.io/Physics321/doc/pub/energyconserv/html/energyconserv.html).\n\n\nAn algorithm which implements these equations is included below.\n * Choose the initial position and speed, with the most common choice $v(t=0)=0$ and some fixed value for the position. \n\n * Choose the method you wish to employ in solving the problem.\n\n * Subdivide the time interval $[t_i,t_f] $ into a grid with step size\n\n$$\nh=\\frac{t_f-t_i}{N},\n$$\n\nwhere $N$ is the number of mesh points. \n * Calculate now the total energy given by\n\n$$\nE_0=\\frac{1}{2}kx(t=0)^2=\\frac{1}{2}k.\n$$\n\n* Choose ODE solver to obtain $x_{i+1}$ and $v_{i+1}$ starting from the previous values $x_i$ and $v_i$.\n\n * When we have computed $x(v)_{i+1}$ we upgrade $t_{i+1}=t_i+h$.\n\n * This iterative process continues till we reach the maximum time $t_f$.\n\n * The results are checked against the exact solution. Furthermore, one has to check the stability of the numerical solution against the chosen number of mesh points $N$. \n\nThe following python program ( code will be added shortly)\n\n\n```\n#\n# This program solves Newtons equation for a block sliding on\n# an horizontal frictionless surface.\n# The block is tied to the wall with a spring, so N's eq takes the form:\n#\n# m d^2x/dt^2 = - kx\n#\n# In order to make the solution dimless, we set k/m = 1.\n# This results in two coupled diff. eq's that may be written as:\n#\n# dx/dt = v\n# dv/dt = -x\n#\n# The user has to specify the initial velocity and position,\n# and the number of steps. The time interval is fixed to\n# t \\in [0, 4\\pi) (two periods)\n#\n```\n\n## The classical pendulum and scaling the equations\n\nThe angular equation of motion of the pendulum is given by\nNewton's equation and with no external force it reads\n\n\n
\n\n$$\n\\begin{equation}\n ml\\frac{d^2\\theta}{dt^2}+mgsin(\\theta)=0,\n\\label{_auto19} \\tag{20}\n\\end{equation}\n$$\n\nwith an angular velocity and acceleration given by\n\n\n
\n\n$$\n\\begin{equation}\n v=l\\frac{d\\theta}{dt},\n\\label{_auto20} \\tag{21}\n\\end{equation}\n$$\n\nand\n\n\n
\n\n$$\n\\begin{equation}\n a=l\\frac{d^2\\theta}{dt^2}.\n\\label{_auto21} \\tag{22}\n\\end{equation}\n$$\n\n## More on the Pendulum\n\nWe do however expect that the motion will gradually come to an end due a viscous drag torque acting on the pendulum. \nIn the presence of the drag, the above equation becomes\n\n\n
\n\n$$\n\\begin{equation}\n ml\\frac{d^2\\theta}{dt^2}+\\nu\\frac{d\\theta}{dt} +mgsin(\\theta)=0, \\label{eq:pend1} \\tag{23}\n\\end{equation}\n$$\n\nwhere $\\nu$ is now a positive constant parameterizing the viscosity\nof the medium in question. In order to maintain the motion against\nviscosity, it is necessary to add some external driving force. \nWe choose here a periodic driving force. The last equation becomes then\n\n\n
\n\n$$\n\\begin{equation}\n ml\\frac{d^2\\theta}{dt^2}+\\nu\\frac{d\\theta}{dt} +mgsin(\\theta)=Asin(\\omega t), \\label{eq:pend2} \\tag{24}\n\\end{equation}\n$$\n\nwith $A$ and $\\omega$ two constants representing the amplitude and \nthe angular frequency respectively. The latter is called the driving frequency.\n\n\n\n\n## More on the Pendulum\n\nWe define\n\n$$\n\\omega_0=\\sqrt{g/l},\n$$\n\nthe so-called natural frequency and the new dimensionless quantities\n\n$$\n\\hat{t}=\\omega_0t,\n$$\n\nwith the dimensionless driving frequency\n\n$$\n\\hat{\\omega}=\\frac{\\omega}{\\omega_0},\n$$\n\nand introducing the quantity $Q$, called the *quality factor*,\n\n$$\nQ=\\frac{mg}{\\omega_0\\nu},\n$$\n\nand the dimensionless amplitude\n\n$$\n\\hat{A}=\\frac{A}{mg}\n$$\n\nWe have\n\n$$\n\\frac{d^2\\theta}{d\\hat{t}^2}+\\frac{1}{Q}\\frac{d\\theta}{d\\hat{t}} \n +sin(\\theta)=\\hat{A}cos(\\hat{\\omega}\\hat{t}).\n$$\n\nThis equation can in turn be recast in terms of two coupled first-order differential equations as follows\n\n$$\n\\frac{d\\theta}{d\\hat{t}}=\\hat{v},\n$$\n\nand\n\n$$\n\\frac{d\\hat{v}}{d\\hat{t}}=-\\frac{\\hat{v}}{Q}-sin(\\theta)+\\hat{A}cos(\\hat{\\omega}\\hat{t}).\n$$\n\nThese are the equations to be solved. The factor $Q$ represents the number of oscillations of the undriven system that must occur before its energy is significantly reduced due to the viscous drag. The amplitude $\\hat{A}$ is measured in units of the maximum possible gravitational torque while $\\hat{\\omega}$ is the angular frequency of the external torque measured in units of the pendulum's natural frequency. \n\n\n\n\n\n# Work, Energy, Momentum and Conservation laws\n\nEnergy conservation is most convenient as a strategy for addressing\nproblems where time does not appear. For example, a particle goes\nfrom position $x_0$ with speed $v_0$, to position $x_f$; what is its\nnew speed? However, it can also be applied to problems where time\ndoes appear, such as in solving for the trajectory $x(t)$, or\nequivalently $t(x)$.\n\n\n\nMore material to be added here.\n\n\n\n## Energy Conservation\nEnergy is conserved in the case where the potential energy, $V(\\boldsymbol{r})$, depends only on position, and not on time. The force is determined by $V$,\n\n\n
\n\n$$\n\\begin{equation}\n\\boldsymbol{F}(\\boldsymbol{r})=-\\nabla V(\\boldsymbol{r}).\n\\label{_auto22} \\tag{25}\n\\end{equation}\n$$\n\nThe net energy, $E=V+K$ where $K$ is the kinetic energy, is then conserved,\n\n$$\n\\begin{eqnarray}\n\\frac{d}{dt}(K+V)&=&\\frac{d}{dt}\\left(\\frac{m}{2}(v_x^2+v_y^2+v_z^2)+V(\\boldsymbol{r})\\right)\\\\\n\\nonumber\n&=&m\\left(v_x\\frac{dv_x}{dt}+v_y\\frac{dv_y}{dt}+v_z\\frac{dv_z}{dt}\\right)\n+\\partial_xV\\frac{dx}{dt}+\\partial_yV\\frac{dy}{dt}+\\partial_zV\\frac{dz}{dt}\\\\\n\\nonumber\n&=&v_xF_x+v_yF_y+v_zF_z-F_xv_x-F_yv_y-F_zv_z=0.\n\\end{eqnarray}\n$$\n\nThe same proof can be written more compactly with vector notation,\n\n$$\n\\begin{eqnarray}\n\\frac{d}{dt}\\left(\\frac{m}{2}v^2+V(\\boldsymbol{r})\\right)\n&=&m\\boldsymbol{v}\\cdot\\dot{\\boldsymbol{v}}+\\nabla V(\\boldsymbol{r})\\cdot\\dot{\\boldsymbol{r}}\\\\\n\\nonumber\n&=&\\boldsymbol{v}\\cdot\\boldsymbol{F}-\\boldsymbol{F}\\cdot\\boldsymbol{v}=0.\n\\end{eqnarray}\n$$\n\nInverting the expression for kinetic energy,\n\n\n
\n\n$$\n\\begin{equation}\nv=\\sqrt{2K/m}=\\sqrt{2(E-V)/m},\n\\label{_auto23} \\tag{26}\n\\end{equation}\n$$\n\nallows one to solve for the one-dimensional trajectory $x(t)$, by finding $t(x)$,\n\n\n
\n\n$$\n\\begin{equation}\nt=\\int_{x_0}^x \\frac{dx'}{v(x')}=\\int_{x_0}^x\\frac{dx'}{\\sqrt{2(E-V(x'))/m}}.\n\\label{_auto24} \\tag{27}\n\\end{equation}\n$$\n\nNote this would be much more difficult in higher dimensions, because\nyou would have to determine which points, $x,y,z$, the particles might\nreach in the trajectory, whereas in one dimension you can typically\ntell by simply seeing whether the kinetic energy is positive at every\npoint between the old position and the new position.\n\n\nConsider a simple harmonic oscillator potential, $V(x)=kx^2/2$, with a particle emitted from $x=0$ with velocity $v_0$. Solve for the trajectory $t(x)$,\n\n$$\n\\begin{eqnarray}\nt&=&\\int_{0}^x \\frac{dx'}{\\sqrt{2(E-kx^2/2)/m}}\\\\\n\\nonumber\n&=&\\sqrt{m/k}\\int_0^x~\\frac{dx'}{\\sqrt{x_{\\rm max}^2-x^{\\prime 2}}},~~~x_{\\rm max}^2=2E/k.\n\\end{eqnarray}\n$$\n\nHere $E=mv_0^2/2$ and $x_{\\rm max}$ is defined as the maximum\ndisplacement before the particle turns around. This integral is done\nby the substitution $\\sin\\theta=x/x_{\\rm max}$.\n\n$$\n\\begin{eqnarray}\n(k/m)^{1/2}t&=&\\sin^{-1}(x/x_{\\rm max}),\\\\\n\\nonumber\nx&=&x_{\\rm max}\\sin\\omega t,~~~\\omega=\\sqrt{k/m}.\n\\end{eqnarray}\n$$\n\n## Conservation of Momentum\n\n\nNewton's third law which we met earlier states that **For every action there is an equal and opposite reaction**, is more accurately stated as\n**If two bodies exert forces on each other, these forces are equal in magnitude and opposite in direction**.\n\nThis means that for two bodies $i$ and $j$, if the force on $i$ due to $j$ is called $\\boldsymbol{F}_{ij}$, then\n\n\n
\n\n$$\n\\begin{equation}\n\\boldsymbol{F}_{ij}=-\\boldsymbol{F}_{ji}. \n\\label{_auto25} \\tag{28}\n\\end{equation}\n$$\n\nNewton's second law, $\\boldsymbol{F}=m\\boldsymbol{a}$, can be written for a particle $i$ as\n\n\n
\n\n$$\n\\begin{equation}\n\\boldsymbol{F}_i=\\sum_{j\\ne i} \\boldsymbol{F}_{ij}=m_i\\boldsymbol{a}_i,\n\\label{_auto26} \\tag{29}\n\\end{equation}\n$$\n\nwhere $\\boldsymbol{F}_i$ (a single subscript) denotes the net force acting on $i$. Because the mass of $i$ is fixed, one can see that\n\n\n
\n\n$$\n\\begin{equation}\n\\boldsymbol{F}_i=\\frac{d}{dt}m_i\\boldsymbol{v}_i=\\sum_{j\\ne i}\\boldsymbol{F}_{ij}.\n\\label{_auto27} \\tag{30}\n\\end{equation}\n$$\n\nNow, one can sum over all the particles and obtain\n\n$$\n\\begin{eqnarray}\n\\frac{d}{dt}\\sum_i m_iv_i&=&\\sum_{ij, i\\ne j}\\boldsymbol{F}_{ij}\\\\\n\\nonumber\n&=&0.\n\\end{eqnarray}\n$$\n\nThe last step made use of the fact that for every term $ij$, there is\nan equivalent term $ji$ with opposite force. Because the momentum is\ndefined as $m\\boldsymbol{v}$, for a system of particles,\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{d}{dt}\\sum_im_i\\boldsymbol{v}_i=0,~~{\\rm for~isolated~particles}.\n\\label{_auto28} \\tag{31}\n\\end{equation}\n$$\n\nBy \"isolated\" one means that the only force acting on any particle $i$\nare those originating from other particles in the sum, i.e. \"no\nexternal\" forces. Thus, Newton's third law leads to the conservation\nof total momentum,\n\n$$\n\\begin{eqnarray}\n\\boldsymbol{P}&=&\\sum_i m_i\\boldsymbol{v}_i,\\\\\n\\nonumber\n\\frac{d}{dt}\\boldsymbol{P}&=&0.\n\\end{eqnarray}\n$$\n\nConsider the rocket of mass $M$ moving with velocity $v$. After a\nbrief instant, the velocity of the rocket is $v+\\Delta v$ and the mass\nis $M-\\Delta M$. Momentum conservation gives\n\n$$\n\\begin{eqnarray*}\nMv&=&(M-\\Delta M)(v+\\Delta v)+\\Delta M(v-v_e)\\\\\n0&=&-\\Delta Mv+M\\Delta v+\\Delta M(v-v_e),\\\\\n0&=&M\\Delta v-\\Delta Mv_e.\n\\end{eqnarray*}\n$$\n\nIn the second step we ignored the term $\\Delta M\\Delta v$ because it is doubly small. The last equation gives\n\n$$\n\\begin{eqnarray}\n\\Delta v&=&\\frac{v_e}{M}\\Delta M,\\\\\n\\nonumber\n\\frac{dv}{dt}&=&\\frac{v_e}{M}\\frac{dM}{dt}.\n\\end{eqnarray}\n$$\n\nIntegrating the expression with lower limits $v_0=0$ and $M_0$, one finds\n\n$$\n\\begin{eqnarray*}\nv&=&v_e\\int_{M_0}^M \\frac{dM'}{M'}\\\\\nv&=&-v_e\\ln(M/M_0)\\\\\n&=&-v_e\\ln[(M_0-\\alpha t)/M_0].\n\\end{eqnarray*}\n$$\n\nBecause the total momentum of an isolated system is constant, one can\nalso quickly see that the center of mass of an isolated system is also\nconstant. The center of mass is the average position of a set of\nmasses weighted by the mass,\n\n\n
\n\n$$\n\\begin{equation}\n\\bar{x}=\\frac{\\sum_im_ix_i}{\\sum_i m_i}.\n\\label{_auto29} \\tag{32}\n\\end{equation}\n$$\n\nThe rate of change of $\\bar{x}$ is\n\n$$\n\\begin{eqnarray}\n\\dot{\\bar{x}}&=&\\frac{1}{M}\\sum_i m_i\\dot{x}_i=\\frac{1}{M}P_x.\n\\end{eqnarray}\n$$\n\nThus if the total momentum is constant the center of mass moves at a\nconstant velocity, and if the total momentum is zero the center of\nmass is fixed.\n\n\n\n## Conservation of Angular Momentum\n\n\nConsider a case where the force always points radially,\n\n\n
\n\n$$\n\\begin{equation}\n\\boldsymbol{F}(\\boldsymbol{r})=F(r)\\hat{r},\n\\label{_auto30} \\tag{33}\n\\end{equation}\n$$\n\nwhere $\\hat{r}$ is a unit vector pointing outward from the origin. The angular momentum is defined as\n\n\n
\n\n$$\n\\begin{equation}\n\\boldsymbol{L}=\\boldsymbol{r}\\times\\boldsymbol{p}=m\\boldsymbol{r}\\times\\boldsymbol{v}.\n\\label{_auto31} \\tag{34}\n\\end{equation}\n$$\n\nThe rate of change of the angular momentum is\n\n$$\n\\begin{eqnarray}\n\\frac{d\\boldsymbol{L}}{dt}&=&m\\boldsymbol{v}\\times\\boldsymbol{v}+m\\boldsymbol{r}\\times\\dot{\\boldsymbol{v}}\\\\\n\\nonumber\n&=&m\\boldsymbol{v}\\times\\boldsymbol{v}+\\boldsymbol{r}\\times{\\boldsymbol{F}}=0.\n\\end{eqnarray}\n$$\n\nThe first term is zero because $\\boldsymbol{v}$ is parallel to itself, and the\nsecond term is zero because $\\boldsymbol{F}$ is parallel to $\\boldsymbol{r}$.\n\nAs an aside, one can see from the Levi-Civita symbol that the cross\nproduct of a vector with itself is zero. Here, we consider a vector\n\n$$\n\\begin{eqnarray}\n\\boldsymbol{V}&=&\\boldsymbol{A}\\times\\boldsymbol{A},\\\\\n\\nonumber\nV_i&=&(\\boldsymbol{A}\\times\\boldsymbol{A})_i=\\sum_{jk}\\epsilon_{ijk}A_jA_k.\n\\end{eqnarray}\n$$\n\nFor any term $i$, there are two contributions. For example, for $i$\ndenoting the $x$ direction, either $j$ denotes the $y$ direction and\n$k$ denotes the $z$ direction, or vice versa, so\n\n\n
\n\n$$\n\\begin{equation}\nV_1=\\epsilon_{123}A_2A_3+\\epsilon_{132}A_3A_2.\n\\label{_auto32} \\tag{35}\n\\end{equation}\n$$\n\nThis is zero by the antisymmetry of $\\epsilon$ under permutations.\n\nIf the force is not radial, $\\boldsymbol{r}\\times\\boldsymbol{F}\\ne 0$ as above, and angular momentum is no longer conserved,\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{d\\boldsymbol{L}}{dt}=\\boldsymbol{r}\\times\\boldsymbol{F}\\equiv\\boldsymbol{\\tau},\n\\label{_auto33} \\tag{36}\n\\end{equation}\n$$\n\nwhere $\\boldsymbol{\\tau}$ is the torque.\n\nFor a system of isolated particles, one can write\n\n$$\n\\begin{eqnarray}\n\\frac{d}{dt}\\sum_i\\boldsymbol{L}_i&=&\\sum_{i\\ne j}\\boldsymbol{r}_i\\times \\boldsymbol{F}_{ij}\\\\\n\\nonumber\n&=&\\frac{1}{2}\\sum_{i\\ne j} \\boldsymbol{r}_i\\times \\boldsymbol{F}_{ij}+\\boldsymbol{r}_j\\times\\boldsymbol{F}_{ji}\\\\\n\\nonumber\n&=&\\frac{1}{2}\\sum_{i\\ne j} (\\boldsymbol{r}_i-\\boldsymbol{r}_j)\\times\\boldsymbol{F}_{ij}=0,\n\\end{eqnarray}\n$$\n\nwhere the last step used Newton's third law,\n$\\boldsymbol{F}_{ij}=-\\boldsymbol{F}_{ji}$. If the forces between the particles are\nradial, i.e. $\\boldsymbol{F}_{ij} ~||~ (\\boldsymbol{r}_i-\\boldsymbol{r}_j)$, then each term in\nthe sum is zero and the net angular momentum is fixed. Otherwise, you\ncould imagine an isolated system that would start spinning\nspontaneously.\n\nOne can write the torque about a given axis, which we will denote as $\\hat{z}$, in polar coordinates, where\n\n$$\n\\begin{eqnarray}\nx&=&r\\sin\\theta\\cos\\phi,~~y=r\\sin\\theta\\cos\\phi,~~z=r\\cos\\theta,\n\\end{eqnarray}\n$$\n\nto find the $z$ component of the torque,\n\n$$\n\\begin{eqnarray}\n\\tau_z&=&xF_y-yF_x\\\\\n\\nonumber\n&=&-r\\sin\\theta\\left\\{\\cos\\phi \\partial_y-\\sin\\phi \\partial_x\\right\\}V(x,y,z).\n\\end{eqnarray}\n$$\n\nOne can use the chain rule to write the partial derivative w.r.t. $\\phi$ (keeping $r$ and $\\theta$ fixed),\n\n$$\n\\begin{eqnarray}\n\\partial_\\phi&=&\\frac{\\partial x}{\\partial\\phi}\\partial_x+\\frac{\\partial_y}{\\partial\\phi}\\partial_y\n+\\frac{\\partial z}{\\partial\\phi}\\partial_z\\\\\n\\nonumber\n&=&-r\\sin\\theta\\sin\\phi\\partial_x+\\sin\\theta\\cos\\phi\\partial_y.\n\\end{eqnarray}\n$$\n\nCombining the two equations,\n\n$$\n\\begin{eqnarray}\n\\tau_z&=&-\\partial_\\phi V(r,\\theta,\\phi).\n\\end{eqnarray}\n$$\n\nThus, if the potential is independent of the azimuthal angle $\\phi$,\nthere is no torque about the $z$ axis and $L_z$ is conserved.\n\n\n\n## Symmetries and Conservation Laws\n\nWhen we derived the conservation of energy, we assumed that the\npotential depended only on position, not on time. If it depended\nexplicitly on time, one can quickly see that the energy would have\nchanged at a rate $\\partial_tV(x,y,z,t)$. Note that if there is no\nexplicit dependence on time, i.e. $V(x,y,z)$, the potential energy can\ndepend on time through the variations of $x,y,z$ with time. However,\nthat variation does not lead to energy non-conservation. Further, we\njust saw that if a potential does not depend on the azimuthal angle\nabout some axis, $\\phi$, that the angular momentum about that axis is\nconserved.\n\nNow, we relate momentum conservation to translational\ninvariance. Considering a system of particles with positions,\n$\\boldsymbol{r}_i$, if one changed the coordinate system by a translation by a\ndifferential distance $\\boldsymbol{\\epsilon}$, the net potential would change\nby\n\n$$\n\\begin{eqnarray}\n\\delta V(\\boldsymbol{r}_1,\\boldsymbol{r}_2\\cdots)&=&\\sum_i \\boldsymbol{\\epsilon}\\cdot\\nabla_i V(\\boldsymbol{r}_1,\\boldsymbol{r}_2,\\cdots)\\\\\n\\nonumber\n&=&-\\sum_i \\boldsymbol{\\epsilon}\\cdot\\boldsymbol{F}_i\\\\\n\\nonumber\n&=&-\\frac{d}{dt}\\sum_i \\boldsymbol{\\epsilon}\\cdot\\boldsymbol{p}_i.\n\\end{eqnarray}\n$$\n\nThus, if the potential is unchanged by a translation of the coordinate\nsystem, the total momentum is conserved. If the potential is\ntranslationally invariant in a given direction, defined by a unit\nvector, $\\hat{\\epsilon}$ in the $\\boldsymbol{\\epsilon}$ direction, one can see\nthat\n\n$$\n\\begin{eqnarray}\n\\hat{\\epsilon}\\cdot\\nabla_i V(\\boldsymbol{r}_i)&=&0.\n\\end{eqnarray}\n$$\n\nThe component of the total momentum along that axis is conserved. This\nis rather obvious for a single particle. If $V(\\boldsymbol{r})$ does not\ndepend on some coordinate $x$, then the force in the $x$ direction is\n$F_x=-\\partial_xV=0$, and momentum along the $x$ direction is\nconstant.\n\nWe showed how the total momentum of an isolated system of particle was conserved, even if the particles feel internal forces in all directions. In that case the potential energy could be written\n\n$$\n\\begin{eqnarray}\nV=\\sum_{i,j\\le i}V_{ij}(\\boldsymbol{r}_i-\\boldsymbol{r}_j).\n\\end{eqnarray}\n$$\n\nIn this case, a translation leads to $\\boldsymbol{r}_i\\rightarrow\n\\boldsymbol{r}_i+\\boldsymbol{\\epsilon}$, with the translation equally affecting the\ncoordinates of each particle. Because the potential depends only on\nthe relative coordinates, $\\delta V$ is manifestly zero. If one were\nto go through the exercise of calculating $\\delta V$ for small\n$\\boldsymbol{\\epsilon}$, one would find that the term\n$\\nabla_i V(\\boldsymbol{r}_i-\\boldsymbol{r}_j)$ would be canceled by the term\n$\\nabla_jV(\\boldsymbol{r}_i-\\boldsymbol{r}_j)$.\n\nThe relation between symmetries of the potential and conserved\nquantities (also called constants of motion) is one of the most\nprofound concepts one should gain from this course. It plays a\ncritical role in all fields of physics. This is especially true in\nquantum mechanics, where a quantity $A$ is conserved if its operator\ncommutes with the Hamiltonian. For example if the momentum operator\n$-i\\hbar\\partial_x$ commutes with the Hamiltonian, momentum is\nconserved, and clearly this operator commutes if the Hamiltonian\n(which represents the total energy, not just the potential) does not\ndepend on $x$. Also in quantum mechanics the angular momentum operator\nis $L_z=-i\\hbar\\partial_\\phi$. In fact, if the potential is unchanged\nby rotations about some axis, angular momentum about that axis is\nconserved. We return to this concept, from a more formal perspective,\nlater in the course when Lagrangian mechanics is presented.\n\n\n## Bulding a code for the Earth-Sun system\n\nWe will now venture into a study of a system which is energy\nconserving. The aim is to see if we (since it is not possible to solve\nthe general equations analytically) we can develop stable numerical\nalgorithms whose results we can trust!\n\nWe solve the equations of motion numerically. We will also compute\nquantities like the energy numerically.\n\nWe start with a simpler case first, the Earth-Sun system in two dimensions only. The gravitational force $F_G$ on the earth from the sun is\n\n$$\n\\boldsymbol{F}_G=-\\frac{GM_{\\odot}M_E}{r^3}\\boldsymbol{r},\n$$\n\nwhere $G$ is the gravitational constant,\n\n$$\nM_E=6\\times 10^{24}\\mathrm{Kg},\n$$\n\nthe mass of Earth,\n\n$$\nM_{\\odot}=2\\times 10^{30}\\mathrm{Kg},\n$$\n\nthe mass of the Sun and\n\n$$\nr=1.5\\times 10^{11}\\mathrm{m},\n$$\n\nis the distance between Earth and the Sun. The latter defines what we call an astronomical unit **AU**.\nFrom Newton's second law we have then for the $x$ direction\n\n$$\n\\frac{d^2x}{dt^2}=-\\frac{F_{x}}{M_E},\n$$\n\nand\n\n$$\n\\frac{d^2y}{dt^2}=-\\frac{F_{y}}{M_E},\n$$\n\nfor the $y$ direction.\n\nHere we will use that $x=r\\cos{(\\theta)}$, $y=r\\sin{(\\theta)}$ and\n\n$$\nr = \\sqrt{x^2+y^2}.\n$$\n\nWe can rewrite\n\n$$\nF_{x}=-\\frac{GM_{\\odot}M_E}{r^2}\\cos{(\\theta)}=-\\frac{GM_{\\odot}M_E}{r^3}x,\n$$\n\nand\n\n$$\nF_{y}=-\\frac{GM_{\\odot}M_E}{r^2}\\sin{(\\theta)}=-\\frac{GM_{\\odot}M_E}{r^3}y,\n$$\n\nfor the $y$ direction.\n\n\nWe can rewrite these two equations\n\n$$\nF_{x}=-\\frac{GM_{\\odot}M_E}{r^2}\\cos{(\\theta)}=-\\frac{GM_{\\odot}M_E}{r^3}x,\n$$\n\nand\n\n$$\nF_{y}=-\\frac{GM_{\\odot}M_E}{r^2}\\sin{(\\theta)}=-\\frac{GM_{\\odot}M_E}{r^3}y,\n$$\n\nas four first-order coupled differential equations\n\n1\n5\n8\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n1\n5\n9\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n1\n6\n0\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\frac{dy}{dt}=v_y.\n$$\n\n## Building a code for the solar system, final coupled equations\n\nThe four coupled differential equations\n\n1\n6\n2\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n1\n6\n3\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n1\n6\n4\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\frac{dy}{dt}=v_y,\n$$\n\ncan be turned into dimensionless equations or we can introduce astronomical units with $1$ AU = $1.5\\times 10^{11}$. \n\nUsing the equations from circular motion (with $r =1\\mathrm{AU}$)\n\n$$\n\\frac{M_E v^2}{r} = F = \\frac{GM_{\\odot}M_E}{r^2},\n$$\n\nwe have\n\n$$\nGM_{\\odot}=v^2r,\n$$\n\nand using that the velocity of Earth (assuming circular motion) is\n$v = 2\\pi r/\\mathrm{yr}=2\\pi\\mathrm{AU}/\\mathrm{yr}$, we have\n\n$$\nGM_{\\odot}= v^2r = 4\\pi^2 \\frac{(\\mathrm{AU})^3}{\\mathrm{yr}^2}.\n$$\n\n## Building a code for the solar system, discretized equations\n\nThe four coupled differential equations can then be discretized using Euler's method as (with step length $h$)\n\n1\n6\n9\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n1\n7\n0\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n1\n7\n1\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\ny_{i+1}=y_i+hv_{y,i},\n$$\n\n## Code Example with Euler's Method\n\nThe code here implements Euler's method for the Earth-Sun system using a more compact way of representing the vectors. Alternatively, you could have spelled out all the variables $v_x$, $v_y$, $x$ and $y$ as one-dimensional arrays.\n\n\n```\n# Common imports\nimport numpy as np\nimport pandas as pd\nfrom math import *\nimport matplotlib.pyplot as plt\nimport os\n\n# Where to save the figures and data files\nPROJECT_ROOT_DIR = \"Results\"\nFIGURE_ID = \"Results/FigureFiles\"\nDATA_ID = \"DataFiles/\"\n\nif not os.path.exists(PROJECT_ROOT_DIR):\n os.mkdir(PROJECT_ROOT_DIR)\n\nif not os.path.exists(FIGURE_ID):\n os.makedirs(FIGURE_ID)\n\nif not os.path.exists(DATA_ID):\n os.makedirs(DATA_ID)\n\ndef image_path(fig_id):\n return os.path.join(FIGURE_ID, fig_id)\n\ndef data_path(dat_id):\n return os.path.join(DATA_ID, dat_id)\n\ndef save_fig(fig_id):\n plt.savefig(image_path(fig_id) + \".png\", format='png')\n\n\nDeltaT = 0.001\n#set up arrays \ntfinal = 10 # in years\nn = ceil(tfinal/DeltaT)\n# set up arrays for t, a, v, and x\nt = np.zeros(n)\nv = np.zeros((n,2))\nr = np.zeros((n,2))\n# Initial conditions as compact 2-dimensional arrays\nr0 = np.array([1.0,0.0])\nv0 = np.array([0.0,2*pi])\nr[0] = r0\nv[0] = v0\nFourpi2 = 4*pi*pi\n# Start integrating using Euler's method\nfor i in range(n-1):\n # Set up the acceleration\n # Here you could have defined your own function for this\n rabs = sqrt(sum(r[i]*r[i]))\n a = -Fourpi2*r[i]/(rabs**3)\n # update velocity, time and position using Euler's forward method\n v[i+1] = v[i] + DeltaT*a\n r[i+1] = r[i] + DeltaT*v[i]\n t[i+1] = t[i] + DeltaT\n# Plot position as function of time \nfig, ax = plt.subplots()\n#ax.set_xlim(0, tfinal)\nax.set_ylabel('x[m]')\nax.set_xlabel('y[m]')\nax.plot(r[:,0], r[:,1])\nfig.tight_layout()\nsave_fig(\"EarthSunEuler\")\nplt.show()\n```\n\n## Problems with Euler's Method\n\nWe notice here that Euler's method doesn't give a stable orbit. It\nmeans that we cannot trust Euler's method. In a deeper way, as we will\nsee in homework 5, Euler's method does not conserve energy. It is an\nexample of an integrator which is not\n[symplectic](https://en.wikipedia.org/wiki/Symplectic_integrator).\n\nHere we present thus two methods, which with simple changes allow us to avoid these pitfalls. The simplest possible extension is the so-called Euler-Cromer method.\nThe changes we need to make to our code are indeed marginal here.\nWe need simply to replace\n\n\n```\n r[i+1] = r[i] + DeltaT*v[i]\n```\n\nin the above code with the velocity at the new time $t_{i+1}$\n\n\n```\n r[i+1] = r[i] + DeltaT*v[i+1]\n```\n\nBy this simple caveat we get stable orbits.\nBelow we derive the Euler-Cromer method as well as one of the most utlized algorithms for sovling the above type of problems, the so-called Velocity-Verlet method. \n\n\n## Deriving the Euler-Cromer Method\n\nLet us repeat Euler's method.\nWe have a differential equation\n\n\n
\n\n$$\n\\begin{equation}\ny'(t_i)=f(t_i,y_i) \n\\label{_auto34} \\tag{37}\n\\end{equation}\n$$\n\nand if we truncate at the first derivative, we have from the Taylor expansion\n\n\n
\n\n$$\n\\begin{equation}\ny_{i+1}=y(t_i) + (\\Delta t) f(t_i,y_i) + O(\\Delta t^2), \\label{eq:euler} \\tag{38}\n\\end{equation}\n$$\n\nwhich when complemented with $t_{i+1}=t_i+\\Delta t$ forms\nthe algorithm for the well-known Euler method. \nNote that at every step we make an approximation error\nof the order of $O(\\Delta t^2)$, however the total error is the sum over all\nsteps $N=(b-a)/(\\Delta t)$ for $t\\in [a,b]$, yielding thus a global error which goes like\n$NO(\\Delta t^2)\\approx O(\\Delta t)$. \n\nTo make Euler's method more precise we can obviously\ndecrease $\\Delta t$ (increase $N$), but this can lead to loss of numerical precision.\nEuler's method is not recommended for precision calculation,\nalthough it is handy to use in order to get a first\nview on how a solution may look like.\n\nEuler's method is asymmetric in time, since it uses information about the derivative at the beginning\nof the time interval. This means that we evaluate the position at $y_1$ using the velocity\nat $v_0$. A simple variation is to determine $x_{n+1}$ using the velocity at\n$v_{n+1}$, that is (in a slightly more generalized form)\n\n\n
\n\n$$\n\\begin{equation} \ny_{n+1}=y_{n}+ v_{n+1}+O(\\Delta t^2)\n\\label{_auto35} \\tag{39}\n\\end{equation}\n$$\n\nand\n\n\n
\n\n$$\n\\begin{equation}\nv_{n+1}=v_{n}+(\\Delta t) a_{n}+O(\\Delta t^2).\n\\label{_auto36} \\tag{40}\n\\end{equation}\n$$\n\nThe acceleration $a_n$ is a function of $a_n(y_n, v_n, t_n)$ and needs to be evaluated\nas well. This is the Euler-Cromer method.\n\n**Exercise**: go back to the above code with Euler's method and add the Euler-Cromer method. \n\n\n\n## Deriving the Velocity-Verlet Method\n\nLet us stay with $x$ (position) and $v$ (velocity) as the quantities we are interested in.\n\nWe have the Taylor expansion for the position given by\n\n$$\nx_{i+1} = x_i+(\\Delta t)v_i+\\frac{(\\Delta t)^2}{2}a_i+O((\\Delta t)^3).\n$$\n\nThe corresponding expansion for the velocity is\n\n$$\nv_{i+1} = v_i+(\\Delta t)a_i+\\frac{(\\Delta t)^2}{2}v^{(2)}_i+O((\\Delta t)^3).\n$$\n\nVia Newton's second law we have normally an analytical expression for the derivative of the velocity, namely\n\n$$\na_i= \\frac{d^2 x}{dt^2}\\vert_{i}=\\frac{d v}{dt}\\vert_{i}= \\frac{F(x_i,v_i,t_i)}{m}.\n$$\n\nIf we add to this the corresponding expansion for the derivative of the velocity\n\n$$\nv^{(1)}_{i+1} = a_{i+1}= a_i+(\\Delta t)v^{(2)}_i+O((\\Delta t)^2)=a_i+(\\Delta t)v^{(2)}_i+O((\\Delta t)^2),\n$$\n\nand retain only terms up to the second derivative of the velocity since our error goes as $O(h^3)$, we have\n\n$$\n(\\Delta t)v^{(2)}_i\\approx a_{i+1}-a_i.\n$$\n\nWe can then rewrite the Taylor expansion for the velocity as\n\n$$\nv_{i+1} = v_i+\\frac{(\\Delta t)}{2}\\left( a_{i+1}+a_{i}\\right)+O((\\Delta t)^3).\n$$\n\n## The velocity Verlet method\n\nOur final equations for the position and the velocity become then\n\n$$\nx_{i+1} = x_i+(\\Delta t)v_i+\\frac{(\\Delta t)^2}{2}a_{i}+O((\\Delta t)^3),\n$$\n\nand\n\n$$\nv_{i+1} = v_i+\\frac{(\\Delta t)}{2}\\left(a_{i+1}+a_{i}\\right)+O((\\Delta t)^3).\n$$\n\nNote well that the term $a_{i+1}$ depends on the position at $x_{i+1}$. This means that you need to calculate \nthe position at the updated time $t_{i+1}$ before the computing the next velocity. Note also that the derivative of the velocity at the time\n$t_i$ used in the updating of the position can be reused in the calculation of the velocity update as well. \n\n\n## Adding the Velocity-Verlet Method\n\nWe can now easily add the Verlet method to our original code as\n\n\n```\nDeltaT = 0.01\n#set up arrays \ntfinal = 10\nn = ceil(tfinal/DeltaT)\n# set up arrays for t, a, v, and x\nt = np.zeros(n)\nv = np.zeros((n,2))\nr = np.zeros((n,2))\n# Initial conditions as compact 2-dimensional arrays\nr0 = np.array([1.0,0.0])\nv0 = np.array([0.0,2*pi])\nr[0] = r0\nv[0] = v0\nFourpi2 = 4*pi*pi\n# Start integrating using the Velocity-Verlet method\nfor i in range(n-1):\n # Set up forces, air resistance FD, note now that we need the norm of the vecto\n # Here you could have defined your own function for this\n rabs = sqrt(sum(r[i]*r[i]))\n a = -Fourpi2*r[i]/(rabs**3)\n # update velocity, time and position using the Velocity-Verlet method\n r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a\n rabs = sqrt(sum(r[i+1]*r[i+1]))\n anew = -4*(pi**2)*r[i+1]/(rabs**3)\n v[i+1] = v[i] + 0.5*DeltaT*(a+anew)\n t[i+1] = t[i] + DeltaT\n# Plot position as function of time \nfig, ax = plt.subplots()\nax.set_ylabel('x[m]')\nax.set_xlabel('y[m]')\nax.plot(r[:,0], r[:,1])\nfig.tight_layout()\nsave_fig(\"EarthSunVV\")\nplt.show()\n```\n\nYou can easily generalize the calculation of the forces by defining a function\nwhich takes in as input the various variables. We leave this as a challenge to you.\n\n\n## Studying Energy Conservation\n\nIn order to study the conservation of energy, we will need to perform\na numerical integration, unless we can integrate analytically. Here we\npresent the Trapezoidal rule as a the simplest possible approximation.\n\n\n\n\n\n## Numerical Integration\n\nIt is also useful to consider methods to integrate numerically.\nLet us consider the following case.\nWe have classical electron which moves in the $x$-direction along a surface. The force from the surface is\n\n$$\n\\boldsymbol{F}(x)=-F_0\\sin{(\\frac{2\\pi x}{b})}\\boldsymbol{e}_x.\n$$\n\nThe constant $b$ represents the distance between atoms at the surface of the material, $F_0$ is a constant and $x$ is the position of the electron.\n Using the work-energy theorem we can find the work $W$ done when moving an electron from a position $x_0$ to a final position $x$ through the\n integral\n\n$$\nW=-\\int_{x_0}^x \\boldsymbol{F}(x')dx' = \\int_{x_0}^x F_0\\sin{(\\frac{2\\pi x'}{b})} dx',\n$$\n\nwhich results in\n\n$$\nW=\\frac{F_0b}{2\\pi}\\left[\\cos{(\\frac{2\\pi x}{b})}-\\cos{(\\frac{2\\pi x_0}{b})}\\right].\n$$\n\n## Numerical Integration\n\nThere are several numerical algorithms for finding an integral\nnumerically. The more familiar ones like the rectangular rule or the\ntrapezoidal rule have simple geometric interpretations.\n\nLet us look at the mathematical details of what are called equal-step methods, also known as Newton-Cotes quadrature.\n\n\n## Newton-Cotes Quadrature or equal-step methods\nThe integral\n\n\n
\n\n$$\n\\begin{equation}\n I=\\int_a^bf(x) dx\n\\label{eq:integraldef} \\tag{41}\n\\end{equation}\n$$\n\nhas a very simple meaning. The integral is the\narea enscribed by the function $f(x)$ starting from $x=a$ to $x=b$. It is subdivided in several smaller areas whose evaluation is to be approximated by different techniques. The areas under the curve can for example be approximated by rectangular boxes or trapezoids.\n\n\n\n\n## Basic philosophy of equal-step methods\nIn considering equal step methods, our basic approach is that of approximating\na function $f(x)$ with a polynomial of at most \ndegree $N-1$, given $N$ integration points. If our polynomial is of degree $1$,\nthe function will be approximated with $f(x)\\approx a_0+a_1x$.\n\n\n\n\nThe algorithm for these integration methods is rather simple, and the number of approximations perhaps unlimited!\n\n* Choose a step size $h=(b-a)/N$ where $N$ is the number of steps and $a$ and $b$ the lower and upper limits of integration.\n\n* With a given step length we rewrite the integral as\n\n$$\n\\int_a^bf(x) dx= \\int_a^{a+h}f(x)dx + \\int_{a+h}^{a+2h}f(x)dx+\\dots \\int_{b-h}^{b}f(x)dx.\n$$\n\n* The strategy then is to find a reliable polynomial approximation for $f(x)$ in the various intervals. Choosing a given approximation for $f(x)$, we obtain a specific approximation to the integral.\n\n* With this approximation to $f(x)$ we perform the integration by computing the integrals over all subintervals.\n\nOne possible strategy then is to find a reliable polynomial expansion for $f(x)$ in the smaller\nsubintervals. Consider for example evaluating\n\n$$\n\\int_a^{a+2h}f(x)dx,\n$$\n\nwhich we rewrite as\n\n\n
\n\n$$\n\\begin{equation}\n\\int_a^{a+2h}f(x)dx=\\int_{x_0-h}^{x_0+h}f(x)dx.\n\\label{eq:hhint} \\tag{42}\n\\end{equation}\n$$\n\nWe have chosen a midpoint $x_0$ and have defined $x_0=a+h$.\n\n\n\n\n## The rectangle method\n\nA very simple approach is the so-called midpoint or rectangle method.\nIn this case the integration area is split in a given number of rectangles with length $h$ and height given by the mid-point value of the function. This gives the following simple rule for approximating an integral\n\n\n
\n\n$$\n\\begin{equation}\nI=\\int_a^bf(x) dx \\approx h\\sum_{i=1}^N f(x_{i-1/2}), \n\\label{eq:rectangle} \\tag{43}\n\\end{equation}\n$$\n\nwhere $f(x_{i-1/2})$ is the midpoint value of $f$ for a given rectangle. We will discuss its truncation \nerror below. It is easy to implement this algorithm, as shown below\n\n\nThe correct mathematical expression for the local error for the rectangular rule $R_i(h)$ for element $i$ is\n\n$$\n\\int_{-h}^hf(x)dx - R_i(h)=-\\frac{h^3}{24}f^{(2)}(\\xi),\n$$\n\nand the global error reads\n\n$$\n\\int_a^bf(x)dx -R_h(f)=-\\frac{b-a}{24}h^2f^{(2)}(\\xi),\n$$\n\nwhere $R_h$ is the result obtained with rectangular rule and $\\xi \\in [a,b]$.\n\n\nWe go back to our simple example above and set $F_0=b=1$ and choose $x_0=0$ and $x=1/2$, and have\n\n$$\nW=\\frac{1}{\\pi}.\n$$\n\nThe code here computes the integral using the rectangle rule and $n=100$ integration points we have a relative error of\n$10^{-5}$.\n\n\n```\nfrom math import sin, pi\nimport numpy as np\nfrom sympy import Symbol, integrate\n# function for the Rectangular rule \ndef Rectangular(a,b,f,n):\n h = (b-a)/float(n)\n s = 0\n for i in range(0,n,1):\n x = (i+0.5)*h\n s = s+ f(x)\n return h*s\n# function to integrate\ndef function(x):\n return sin(2*pi*x)\n# define integration limits and integration points \na = 0.0; b = 0.5;\nn = 100\nExact = 1./pi\nprint(\"Relative error= \", abs( (Rectangular(a,b,function,n)-Exact)/Exact))\n```\n\n## The trapezoidal rule\n\nThe other integral gives\n\n$$\n\\int_{x_0-h}^{x_0}f(x)dx=\\frac{h}{2}\\left(f(x_0) + f(x_0-h)\\right)+O(h^3),\n$$\n\nand adding up we obtain\n\n\n
\n\n$$\n\\begin{equation}\n \\int_{x_0-h}^{x_0+h}f(x)dx=\\frac{h}{2}\\left(f(x_0+h) + 2f(x_0) + f(x_0-h)\\right)+O(h^3),\n\\label{eq:trapez} \\tag{44}\n\\end{equation}\n$$\n\nwhich is the well-known trapezoidal rule. Concerning the error in the approximation made,\n$O(h^3)=O((b-a)^3/N^3)$, you should note \nthat this is the local error. Since we are splitting the integral from\n$a$ to $b$ in $N$ pieces, we will have to perform approximately $N$ \nsuch operations.\n\nThis means that the *global error* goes like $\\approx O(h^2)$. \nThe trapezoidal reads then\n\n\n
\n\n$$\n\\begin{equation}\n I=\\int_a^bf(x) dx=h\\left(f(a)/2 + f(a+h) +f(a+2h)+\n \\dots +f(b-h)+ f_{b}/2\\right),\n\\label{eq:trapez1} \\tag{45}\n\\end{equation}\n$$\n\nwith a global error which goes like $O(h^2)$. \n\nHereafter we use the shorthand notations $f_{-h}=f(x_0-h)$, $f_{0}=f(x_0)$\nand $f_{h}=f(x_0+h)$.\n\n\nThe correct mathematical expression for the local error for the trapezoidal rule is\n\n$$\n\\int_a^bf(x)dx -\\frac{b-a}{2}\\left[f(a)+f(b)\\right]=-\\frac{h^3}{12}f^{(2)}(\\xi),\n$$\n\nand the global error reads\n\n$$\n\\int_a^bf(x)dx -T_h(f)=-\\frac{b-a}{12}h^2f^{(2)}(\\xi),\n$$\n\nwhere $T_h$ is the trapezoidal result and $\\xi \\in [a,b]$.\n\n\n## Algorithm for the trapezoidal rule\nThe trapezoidal rule is easy to implement numerically \nthrough the following simple algorithm\n\n * Choose the number of mesh points and fix the step length.\n\n * calculate $f(a)$ and $f(b)$ and multiply with $h/2$.\n\n * Perform a loop over $n=1$ to $n-1$ ($f(a)$ and $f(b)$ are known) and sum up the terms $f(a+h) +f(a+2h)+f(a+3h)+\\dots +f(b-h)$. Each step in the loop corresponds to a given value $a+nh$.\n\n * Multiply the final result by $h$ and add $hf(a)/2$ and $hf(b)/2$.\n\n\n\n\n\n\nWe use the same function and integrate now using the trapoezoidal rule.\n\n\n```\nimport numpy as np\nfrom sympy import Symbol, integrate\n# function for the trapezoidal rule\ndef Trapez(a,b,f,n):\n h = (b-a)/float(n)\n s = 0\n x = a\n for i in range(1,n,1):\n x = x+h\n s = s+ f(x)\n s = 0.5*(f(a)+f(b)) +s\n return h*s\n# function to integrate\ndef function(x):\n return sin(2*pi*x)\n# define integration limits and integration points \na = 0.0; b = 0.5;\nn = 100\nExact = 1./pi\nprint(\"Relative error= \", abs( (Trapez(a,b,function,n)-Exact)/Exact))\n```\n\n## Simpsons' rule\n\nInstead of using the above first-order polynomials \napproximations for $f$, we attempt at using a second-order polynomials.\nIn this case we need three points in order to define a second-order \npolynomial approximation\n\n$$\nf(x) \\approx P_2(x)=a_0+a_1x+a_2x^2.\n$$\n\nUsing again Lagrange's interpolation formula we have\n\n$$\nP_2(x)=\\frac{(x-x_0)(x-x_1)}{(x_2-x_0)(x_2-x_1)}y_2+\n \\frac{(x-x_0)(x-x_2)}{(x_1-x_0)(x_1-x_2)}y_1+\n \\frac{(x-x_1)(x-x_2)}{(x_0-x_1)(x_0-x_2)}y_0.\n$$\n\nInserting this formula in the integral of Eq. ([42](#eq:hhint)) we obtain\n\n$$\n\\int_{-h}^{+h}f(x)dx=\\frac{h}{3}\\left(f_h + 4f_0 + f_{-h}\\right)+O(h^5),\n$$\n\nwhich is Simpson's rule. \n\n\n\n\nNote that the improved accuracy in the evaluation of\nthe derivatives gives a better error approximation, $O(h^5)$ vs.\\ $O(h^3)$ .\nBut this is again the *local error approximation*. \nUsing Simpson's rule we can easily compute\nthe integral of Eq. ([41](#eq:integraldef)) to be\n\n\n
\n\n$$\n\\begin{equation}\n I=\\int_a^bf(x) dx=\\frac{h}{3}\\left(f(a) + 4f(a+h) +2f(a+2h)+\n \\dots +4f(b-h)+ f_{b}\\right),\n\\label{eq:simpson} \\tag{46}\n\\end{equation}\n$$\n\nwith a global error which goes like $O(h^4)$. \n\n\n\nMore formal expressions for the local and global errors are for the local error\n\n$$\n\\int_a^bf(x)dx -\\frac{b-a}{6}\\left[f(a)+4f((a+b)/2)+f(b)\\right]=-\\frac{h^5}{90}f^{(4)}(\\xi),\n$$\n\nand for the global error\n\n$$\n\\int_a^bf(x)dx -S_h(f)=-\\frac{b-a}{180}h^4f^{(4)}(\\xi).\n$$\n\nwith $\\xi\\in[a,b]$ and $S_h$ the results obtained with Simpson's method.\n\n\n\n## Algorithm for Simpson's rule\nThe method \ncan easily be implemented numerically through the following simple algorithm\n\n * Choose the number of mesh points and fix the step.\n\n * calculate $f(a)$ and $f(b)$\n\n * Perform a loop over $n=1$ to $n-1$ ($f(a)$ and $f(b)$ are known) and sum up the terms $4f(a+h) +2f(a+2h)+4f(a+3h)+\\dots +4f(b-h)$. Each step in the loop corresponds to a given value $a+nh$. Odd values of $n$ give $4$ as factor while even values yield $2$ as factor.\n\n * Multiply the final result by $\\frac{h}{3}$.\n\n## Code example\n\n\n```\nfrom math import sin, pi\nimport numpy as np\nfrom sympy import Symbol, integrate\n# function for the trapezoidal rule \ndef Simpson(a,b,f,n):\n h = (b-a)/float(n)\n sum = f(a)/float(2);\n for i in range(1,n):\n sum = sum + f(a+i*h)*(3+(-1)**(i+1))\n sum = sum + f(b)/float(2)\n return sum*h/3.0\n# function to integrate \ndef function(x):\n return sin(2*pi*x)\n# define integration limits and integration points \na = 0.0; b = 0.5;\nn = 100\nExact = 1./pi\nprint(\"Relative error= \", abs( (Simpson(a,b,function,n)-Exact)/Exact))\n```\n\nWe see that Simpson's rule gives a much better estimation of the relative error with the same amount of points as we had for the Rectangle rule and the Trapezoidal rule. \n\n\n\n\n\n# Harmonic Oscillations\n\nThe harmonic oscillator is omnipresent in physics. Although you may think \nof this as being related to springs, it, or an equivalent\nmathematical representation, appears in just about any problem where a\nmode is sitting near its potential energy minimum. At that point,\n$\\partial_x V(x)=0$, and the first non-zero term (aside from a\nconstant) in the potential energy is that of a harmonic oscillator. In\na solid, sound modes (phonons) are built on a picture of coupled\nharmonic oscillators, and in relativistic field theory the fundamental\ninteractions are also built on coupled oscillators positioned\ninfinitesimally close to one another in space. The phenomena of a\nresonance of an oscillator driven at a fixed frequency plays out\nrepeatedly in atomic, nuclear and high-energy physics, when quantum\nmechanically the evolution of a state oscillates according to\n$e^{-iEt}$ and exciting discrete quantum states has very similar\nmathematics as exciting discrete states of an oscillator.\n\nThe potential energy for a single particle as a function of its position $x$ can be written as a Taylor expansion about some point $x_0$\n\n\n
\n\n$$\n\\begin{equation}\nV(x)=V(x_0)+(x-x_0)\\left.\\partial_xV(x)\\right|_{x_0}+\\frac{1}{2}(x-x_0)^2\\left.\\partial_x^2V(x)\\right|_{x_0}\n+\\frac{1}{3!}\\left.\\partial_x^3V(x)\\right|_{x_0}+\\cdots\n\\label{_auto37} \\tag{47}\n\\end{equation}\n$$\n\nIf the position $x_0$ is at the minimum of the resonance, the first two non-zero terms of the potential are\n\n$$\n\\begin{eqnarray}\nV(x)&\\approx& V(x_0)+\\frac{1}{2}(x-x_0)^2\\left.\\partial_x^2V(x)\\right|_{x_0},\\\\\n\\nonumber\n&=&V(x_0)+\\frac{1}{2}k(x-x_0)^2,~~~~k\\equiv \\left.\\partial_x^2V(x)\\right|_{x_0},\\\\\n\\nonumber\nF&=&-\\partial_xV(x)=-k(x-x_0).\n\\end{eqnarray}\n$$\n\nPut into Newton's 2nd law (assuming $x_0=0$),\n\n$$\n\\begin{eqnarray}\nm\\ddot{x}&=&-kx,\\\\\nx&=&A\\cos(\\omega_0 t-\\phi),~~~\\omega_0=\\sqrt{k/m}.\n\\end{eqnarray}\n$$\n\nHere $A$ and $\\phi$ are arbitrary. Equivalently, one could have\nwritten this as $A\\cos(\\omega_0 t)+B\\sin(\\omega_0 t)$, or as the real\npart of $Ae^{i\\omega_0 t}$. In this last case $A$ could be an\narbitrary complex constant. Thus, there are 2 arbitrary constants\n(either $A$ and $B$ or $A$ and $\\phi$, or the real and imaginary part\nof one complex constant. This is the expectation for a second order\ndifferential equation, and also agrees with the physical expectation\nthat if you know a particle's initial velocity and position you should\nbe able to define its future motion, and that those two arbitrary\nconditions should translate to two arbitrary constants.\n\nA key feature of harmonic motion is that the system repeats itself\nafter a time $T=1/f$, where $f$ is the frequency, and $\\omega=2\\pi f$\nis the angular frequency. The period of the motion is independent of\nthe amplitude. However, this independence is only exact when one can\nneglect higher terms of the potential, $x^3, x^4\\cdots$. Once can\nneglect these terms for sufficiently small amplitudes, and for larger\namplitudes the motion is no longer purely sinusoidal, and even though\nthe motion repeats itself, the time for repeating the motion is no\nlonger independent of the amplitude.\n\nOne can also calculate the velocity and the kinetic energy as a function of time,\n\n$$\n\\begin{eqnarray}\n\\dot{x}&=&-\\omega_0A\\sin(\\omega_0 t-\\phi),\\\\\n\\nonumber\nK&=&\\frac{1}{2}m\\dot{x}^2=\\frac{m\\omega_0^2A^2}{2}\\sin^2(\\omega_0t-\\phi),\\\\\n\\nonumber\n&=&\\frac{k}{2}A^2\\sin^2(\\omega_0t-\\phi).\n\\end{eqnarray}\n$$\n\nThe total energy is then\n\n\n
\n\n$$\n\\begin{equation}\nE=K+V=\\frac{1}{2}m\\dot{x}^2+\\frac{1}{2}kx^2=\\frac{1}{2}kA^2.\n\\label{_auto38} \\tag{48}\n\\end{equation}\n$$\n\nThe total energy then goes as the square of the amplitude.\n\n\nA pendulum is an example of a harmonic oscillator. By expanding the\nkinetic and potential energies for small angles find the frequency for\na pendulum of length $L$ with all the mass $m$ centered at the end by\nwriting the eq.s of motion in the form of a harmonic oscillator.\n\nThe potential energy and kinetic energies are (for $x$ being the displacement)\n\n$$\n\\begin{eqnarray*}\nV&=&mgL(1-\\cos\\theta)\\approx mgL\\frac{x^2}{2L^2},\\\\\nK&=&\\frac{1}{2}mL^2\\dot{\\theta}^2\\approx \\frac{m}{2}\\dot{x}^2.\n\\end{eqnarray*}\n$$\n\nFor small $x$ Newton's 2nd law becomes\n\n$$\nm\\ddot{x}=-\\frac{mg}{L}x,\n$$\n\nand the spring constant would appear to be $k=mg/L$, which makes the\nfrequency equal to $\\omega_0=\\sqrt{g/L}$. Note that the frequency is\nindependent of the mass.\n\n\n## Damped Oscillators\n\nWe consider only the case where the damping force is proportional to\nthe velocity. This is counter to dragging friction, where the force is\nproportional in strength to the normal force and independent of\nvelocity, and is also inconsistent with wind resistance, where the\nmagnitude of the drag force is proportional the square of the\nvelocity. Rolling resistance does seem to be mainly proportional to\nthe velocity. However, the main motivation for considering damping\nforces proportional to the velocity is that the math is more\nfriendly. This is because the differential equation is linear,\ni.e. each term is of order $x$, $\\dot{x}$, $\\ddot{x}\\cdots$, or even\nterms with no mention of $x$, and there are no terms such as $x^2$ or\n$x\\ddot{x}$. The equations of motion for a spring with damping force\n$-b\\dot{x}$ are\n\n\n
\n\n$$\n\\begin{equation}\nm\\ddot{x}+b\\dot{x}+kx=0.\n\\label{_auto39} \\tag{49}\n\\end{equation}\n$$\n\nJust to make the solution a bit less messy, we rewrite this equation as\n\n\n
\n\n$$\n\\begin{equation}\n\\label{eq:dampeddiffyq} \\tag{50}\n\\ddot{x}+2\\beta\\dot{x}+\\omega_0^2x=0,~~~~\\beta\\equiv b/2m,~\\omega_0\\equiv\\sqrt{k/m}.\n\\end{equation}\n$$\n\nBoth $\\beta$ and $\\omega$ have dimensions of inverse time. To find solutions (see appendix C in the text) you must make an educated guess at the form of the solution. To do this, first realize that the solution will need an arbitrary normalization $A$ because the equation is linear. Secondly, realize that if the form is\n\n\n
\n\n$$\n\\begin{equation}\nx=Ae^{rt}\n\\label{_auto40} \\tag{51}\n\\end{equation}\n$$\n\nthat each derivative simply brings out an extra power of $r$. This\nmeans that the $Ae^{rt}$ factors out and one can simply solve for an\nequation for $r$. Plugging this form into Eq. ([50](#eq:dampeddiffyq)),\n\n\n
\n\n$$\n\\begin{equation}\nr^2+2\\beta r+\\omega_0^2=0.\n\\label{_auto41} \\tag{52}\n\\end{equation}\n$$\n\nBecause this is a quadratic equation there will be two solutions,\n\n\n
\n\n$$\n\\begin{equation}\nr=-\\beta\\pm\\sqrt{\\beta^2-\\omega_0^2}.\n\\label{_auto42} \\tag{53}\n\\end{equation}\n$$\n\nWe refer to the two solutions as $r_1$ and $r_2$ corresponding to the\n$+$ and $-$ roots. As expected, there should be two arbitrary\nconstants involved in the solution,\n\n\n
\n\n$$\n\\begin{equation}\nx=A_1e^{r_1t}+A_2e^{r_2t},\n\\label{_auto43} \\tag{54}\n\\end{equation}\n$$\n\nwhere the coefficients $A_1$ and $A_2$ are determined by initial\nconditions.\n\nThe roots listed above, $\\sqrt{\\omega_0^2-\\beta_0^2}$, will be\nimaginary if the damping is small and $\\beta<\\omega_0$. In that case,\n$r$ is complex and the factor $e{rt}$ will have some oscillatory\nbehavior. If the roots are real, there will only be exponentially\ndecaying solutions. There are three cases:\n\n\n\n### Underdamped: $\\beta<\\omega_0$\n\n$$\n\\begin{eqnarray}\nx&=&A_1e^{-\\beta t}e^{i\\omega't}+A_2e^{-\\beta t}e^{-i\\omega't},~~\\omega'\\equiv\\sqrt{\\omega_0^2-\\beta^2}\\\\\n\\nonumber\n&=&(A_1+A_2)e^{-\\beta t}\\cos\\omega't+i(A_1-A_2)e^{-\\beta t}\\sin\\omega't.\n\\end{eqnarray}\n$$\n\nHere we have made use of the identity\n$e^{i\\omega't}=\\cos\\omega't+i\\sin\\omega't$. Because the constants are\narbitrary, and because the real and imaginary parts are both solutions\nindividually, we can simply consider the real part of the solution\nalone:\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:homogsolution} \\tag{55}\nx&=&B_1e^{-\\beta t}\\cos\\omega't+B_2e^{-\\beta t}\\sin\\omega't,\\\\\n\\nonumber \n\\omega'&\\equiv&\\sqrt{\\omega_0^2-\\beta^2}.\n\\end{eqnarray}\n$$\n\n### Critical dampling: $\\beta=\\omega_0$\n\nIn this case the two terms involving $r_1$ and $r_2$ are identical\nbecause $\\omega'=0$. Because we need to arbitrary constants, there\nneeds to be another solution. This is found by simply guessing, or by\ntaking the limit of $\\omega'\\rightarrow 0$ from the underdamped\nsolution. The solution is then\n\n\n
\n\n$$\n\\begin{equation}\n\\label{eq:criticallydamped} \\tag{56}\nx=Ae^{-\\beta t}+Bte^{-\\beta t}.\n\\end{equation}\n$$\n\nThe critically damped solution is interesting because the solution\napproaches zero quickly, but does not oscillate. For a problem with\nzero initial velocity, the solution never crosses zero. This is a good\nchoice for designing shock absorbers or swinging doors.\n\n### Overdamped: $\\beta>\\omega_0$\n\n$$\n\\begin{eqnarray}\nx&=&A_1\\exp{-(\\beta+\\sqrt{\\beta^2-\\omega_0^2})t}+A_2\\exp{-(\\beta-\\sqrt{\\beta^2-\\omega_0^2})t}\n\\end{eqnarray}\n$$\n\nThis solution will also never pass the origin more than once, and then\nonly if the initial velocity is strong and initially toward zero.\n\n\n\n\nGiven $b$, $m$ and $\\omega_0$, find $x(t)$ for a particle whose\ninitial position is $x=0$ and has initial velocity $v_0$ (assuming an\nunderdamped solution).\n\nThe solution is of the form,\n\n$$\n\\begin{eqnarray*}\nx&=&e^{-\\beta t}\\left[A_1\\cos(\\omega' t)+A_2\\sin\\omega't\\right],\\\\\n\\dot{x}&=&-\\beta x+\\omega'e^{-\\beta t}\\left[-A_1\\sin\\omega't+A_2\\cos\\omega't\\right].\\\\\n\\omega'&\\equiv&\\sqrt{\\omega_0^2-\\beta^2},~~~\\beta\\equiv b/2m.\n\\end{eqnarray*}\n$$\n\nFrom the initial conditions, $A_1=0$ because $x(0)=0$ and $\\omega'A_2=v_0$. So\n\n$$\nx=\\frac{v_0}{\\omega'}e^{-\\beta t}\\sin\\omega't.\n$$\n\nHere we study first the case without additional friction term and scale our equation\nin terms of a dimensionless time $\\tau$.\n\nLet us remind ourselves about the differential equation we want to solve (the general case with damping due to friction)\n\n$$\nm\\frac{d^2x}{dt^2} + b\\frac{dx}{dt}+kx(t) =0.\n$$\n\nWe divide by $m$ and introduce $\\omega_0^2=\\sqrt{k/m}$ and obtain\n\n$$\n\\frac{d^2x}{dt^2} + \\frac{b}{m}\\frac{dx}{dt}+\\omega_0^2x(t) =0.\n$$\n\nThereafter we introduce a dimensionless time $\\tau = t\\omega_0$ (check\nthat the dimensionality is correct) and rewrite our equation as\n\n$$\n\\frac{d^2x}{d\\tau^2} + \\frac{b}{m\\omega_0}\\frac{dx}{d\\tau}+x(\\tau) =0,\n$$\n\nwhich gives us\n\n$$\n\\frac{d^2x}{d\\tau^2} + \\frac{b}{m\\omega_0}\\frac{dx}{d\\tau}+x(\\tau) =0.\n$$\n\nWe then define $\\gamma = b/(2m\\omega_0)$ and rewrite our equations as\n\n$$\n\\frac{d^2x}{d\\tau^2} + 2\\gamma\\frac{dx}{d\\tau}+x(\\tau) =0.\n$$\n\nThis is the equation we will code below. The first version employs the Euler-Cromer method.\n\n\n```\n# Common imports\nimport numpy as np\nimport pandas as pd\nfrom math import *\nimport matplotlib.pyplot as plt\nimport os\n\n# Where to save the figures and data files\nPROJECT_ROOT_DIR = \"Results\"\nFIGURE_ID = \"Results/FigureFiles\"\nDATA_ID = \"DataFiles/\"\n\nif not os.path.exists(PROJECT_ROOT_DIR):\n os.mkdir(PROJECT_ROOT_DIR)\n\nif not os.path.exists(FIGURE_ID):\n os.makedirs(FIGURE_ID)\n\nif not os.path.exists(DATA_ID):\n os.makedirs(DATA_ID)\n\ndef image_path(fig_id):\n return os.path.join(FIGURE_ID, fig_id)\n\ndef data_path(dat_id):\n return os.path.join(DATA_ID, dat_id)\n\ndef save_fig(fig_id):\n plt.savefig(image_path(fig_id) + \".png\", format='png')\n\n\nfrom pylab import plt, mpl\nplt.style.use('seaborn')\nmpl.rcParams['font.family'] = 'serif'\n\nDeltaT = 0.001\n#set up arrays \ntfinal = 20 # in years\nn = ceil(tfinal/DeltaT)\n# set up arrays for t, v, and x\nt = np.zeros(n)\nv = np.zeros(n)\nx = np.zeros(n)\n# Initial conditions as simple one-dimensional arrays of time\nx0 = 1.0 \nv0 = 0.0\nx[0] = x0\nv[0] = v0\ngamma = 0.0\n# Start integrating using Euler-Cromer's method\nfor i in range(n-1):\n # Set up the acceleration\n # Here you could have defined your own function for this\n a = -2*gamma*v[i]-x[i]\n # update velocity, time and position\n v[i+1] = v[i] + DeltaT*a\n x[i+1] = x[i] + DeltaT*v[i+1]\n t[i+1] = t[i] + DeltaT\n# Plot position as function of time \nfig, ax = plt.subplots()\n#ax.set_xlim(0, tfinal)\nax.set_ylabel('x[m]')\nax.set_xlabel('t[s]')\nax.plot(t, x)\nfig.tight_layout()\nsave_fig(\"BlockEulerCromer\")\nplt.show()\n```\n\nWhen setting up the value of $\\gamma$ we see that for $\\gamma=0$ we get the simple oscillatory motion with no damping.\nChoosing $\\gamma < 1$ leads to the classical underdamped case with oscillatory motion, but where the motion comes to an end.\n\nChoosing $\\gamma =1$ leads to what normally is called critical damping and $\\gamma> 1$ leads to critical overdamping.\nTry it out and try also to change the initial position and velocity. Setting $\\gamma=1$\nyields a situation, as discussed above, where the solution approaches quickly zero and does not oscillate. With zero initial velocity it will never cross zero. \n\n\n## Sinusoidally Driven Oscillators\n\nHere, we consider the force\n\n\n
\n\n$$\n\\begin{equation}\nF=-kx-b\\dot{x}+F_0\\cos\\omega t,\n\\label{_auto44} \\tag{57}\n\\end{equation}\n$$\n\nwhich leads to the differential equation\n\n\n
\n\n$$\n\\begin{equation}\n\\label{eq:drivenosc} \\tag{58}\n\\ddot{x}+2\\beta\\dot{x}+\\omega_0^2x=(F_0/m)\\cos\\omega t.\n\\end{equation}\n$$\n\nConsider a single solution with no arbitrary constants, which we will\ncall a {\\it particular solution}, $x_p(t)$. It should be emphasized\nthat this is {\\bf A} particular solution, because there exists an\ninfinite number of such solutions because the general solution should\nhave two arbitrary constants. Now consider solutions to the same\nequation without the driving term, which include two arbitrary\nconstants. These are called either {\\it homogenous solutions} or {\\it\ncomplementary solutions}, and were given in the previous section,\ne.g. Eq. ([55](#eq:homogsolution)) for the underdamped case. The\nhomogenous solution already incorporates the two arbitrary constants,\nso any sum of a homogenous solution and a particular solution will\nrepresent the {\\it general solution} of the equation. The general\nsolution incorporates the two arbitrary constants $A$ and $B$ to\naccommodate the two initial conditions. One could have picked a\ndifferent particular solution, i.e. the original particular solution\nplus any homogenous solution with the arbitrary constants $A_p$ and\n$B_p$ chosen at will. When one adds in the homogenous solution, which\nhas adjustable constants with arbitrary constants $A'$ and $B'$, to\nthe new particular solution, one can get the same general solution by\nsimply adjusting the new constants such that $A'+A_p=A$ and\n$B'+B_p=B$. Thus, the choice of $A_p$ and $B_p$ are irrelevant, and\nwhen choosing the particular solution it is best to make the simplest\nchoice possible.\n\nTo find a particular solution, one first guesses at the form,\n\n\n
\n\n$$\n\\begin{equation}\n\\label{eq:partform} \\tag{59}\nx_p(t)=D\\cos(\\omega t-\\delta),\n\\end{equation}\n$$\n\nand rewrite the differential equation as\n\n\n
\n\n$$\n\\begin{equation}\nD\\left\\{-\\omega^2\\cos(\\omega t-\\delta)-2\\beta\\omega\\sin(\\omega t-\\delta)+\\omega_0^2\\cos(\\omega t-\\delta)\\right\\}=\\frac{F_0}{m}\\cos(\\omega t).\n\\label{_auto45} \\tag{60}\n\\end{equation}\n$$\n\nOne can now use angle addition formulas to get\n\n$$\n\\begin{eqnarray}\nD\\left\\{(-\\omega^2\\cos\\delta+2\\beta\\omega\\sin\\delta+\\omega_0^2\\cos\\delta)\\cos(\\omega t)\\right.&&\\\\\n\\nonumber\n\\left.+(-\\omega^2\\sin\\delta-2\\beta\\omega\\cos\\delta+\\omega_0^2\\sin\\delta)\\sin(\\omega t)\\right\\}\n&=&\\frac{F_0}{m}\\cos(\\omega t).\n\\end{eqnarray}\n$$\n\nBoth the $\\cos$ and $\\sin$ terms need to equate if the expression is to hold at all times. Thus, this becomes two equations\n\n$$\n\\begin{eqnarray}\nD\\left\\{-\\omega^2\\cos\\delta+2\\beta\\omega\\sin\\delta+\\omega_0^2\\cos\\delta\\right\\}&=&\\frac{F_0}{m}\\\\\n\\nonumber\n-\\omega^2\\sin\\delta-2\\beta\\omega\\cos\\delta+\\omega_0^2\\sin\\delta&=&0.\n\\end{eqnarray}\n$$\n\nAfter dividing by $\\cos\\delta$, the lower expression leads to\n\n\n
\n\n$$\n\\begin{equation}\n\\tan\\delta=\\frac{2\\beta\\omega}{\\omega_0^2-\\omega^2}.\n\\label{_auto46} \\tag{61}\n\\end{equation}\n$$\n\nUsing the identities $\\tan^2+1=\\csc^2$ and $\\sin^2+\\cos^2=1$, one can also express $\\sin\\delta$ and $\\cos\\delta$,\n\n$$\n\\begin{eqnarray}\n\\sin\\delta&=&\\frac{2\\beta\\omega}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\omega^2\\beta^2}},\\\\\n\\nonumber\n\\cos\\delta&=&\\frac{(\\omega_0^2-\\omega^2)}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\omega^2\\beta^2}}\n\\end{eqnarray}\n$$\n\nInserting the expressions for $\\cos\\delta$ and $\\sin\\delta$ into the expression for $D$,\n\n\n
\n\n$$\n\\begin{equation}\n\\label{eq:Ddrive} \\tag{62}\nD=\\frac{F_0/m}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\omega^2\\beta^2}}.\n\\end{equation}\n$$\n\nFor a given initial condition, e.g. initial displacement and velocity,\none must add the homogenous solution then solve for the two arbitrary\nconstants. However, because the homogenous solutions decay with time\nas $e^{-\\beta t}$, the particular solution is all that remains at\nlarge times, and is therefore the steady state solution. Because the\narbitrary constants are all in the homogenous solution, all memory of\nthe initial conditions are lost at large times, $t>>1/\\beta$.\n\nThe amplitude of the motion, $D$, is linearly proportional to the\ndriving force ($F_0/m$), but also depends on the driving frequency\n$\\omega$. For small $\\beta$ the maximum will occur at\n$\\omega=\\omega_0$. This is referred to as a resonance. In the limit\n$\\beta\\rightarrow 0$ the amplitude at resonance approaches infinity.\n\n\n## Alternative Derivation for Driven Oscillators\n\nHere, we derive the same expressions as in Equations ([59](#eq:partform)) and ([62](#eq:Ddrive)) but express the driving forces as\n\n$$\n\\begin{eqnarray}\nF(t)&=&F_0e^{i\\omega t},\n\\end{eqnarray}\n$$\n\nrather than as $F_0\\cos\\omega t$. The real part of $F$ is the same as before. For the differential equation,\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:compdrive} \\tag{63}\n\\ddot{x}+2\\beta\\dot{x}+\\omega_0^2x&=&\\frac{F_0}{m}e^{i\\omega t},\n\\end{eqnarray}\n$$\n\none can treat $x(t)$ as an imaginary function. Because the operations\n$d^2/dt^2$ and $d/dt$ are real and thus do not mix the real and\nimaginary parts of $x(t)$, Eq. ([63](#eq:compdrive)) is effectively 2\nequations. Because $e^{\\omega t}=\\cos\\omega t+i\\sin\\omega t$, the real\npart of the solution for $x(t)$ gives the solution for a driving force\n$F_0\\cos\\omega t$, and the imaginary part of $x$ corresponds to the\ncase where the driving force is $F_0\\sin\\omega t$. It is rather easy\nto solve for the complex $x$ in this case, and by taking the real part\nof the solution, one finds the answer for the $\\cos\\omega t$ driving\nforce.\n\nWe assume a simple form for the particular solution\n\n\n
\n\n$$\n\\begin{equation}\nx_p=De^{i\\omega t},\n\\label{_auto47} \\tag{64}\n\\end{equation}\n$$\n\nwhere $D$ is a complex constant.\n\nFrom Eq. ([63](#eq:compdrive)) one inserts the form for $x_p$ above to get\n\n$$\n\\begin{eqnarray}\nD\\left\\{-\\omega^2+2i\\beta\\omega+\\omega_0^2\\right\\}e^{i\\omega t}=(F_0/m)e^{i\\omega t},\\\\\n\\nonumber\nD=\\frac{F_0/m}{(\\omega_0^2-\\omega^2)+2i\\beta\\omega}.\n\\end{eqnarray}\n$$\n\nThe norm and phase for $D=|D|e^{-i\\delta}$ can be read by inspection,\n\n\n
\n\n$$\n\\begin{equation}\n|D|=\\frac{F_0/m}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\beta^2\\omega^2}},~~~~\\tan\\delta=\\frac{2\\beta\\omega}{\\omega_0^2-\\omega^2}.\n\\label{_auto48} \\tag{65}\n\\end{equation}\n$$\n\nThis is the same expression for $\\delta$ as before. One then finds $x_p(t)$,\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:fastdriven1} \\tag{66}\nx_p(t)&=&\\Re\\frac{(F_0/m)e^{i\\omega t-i\\delta}}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\beta^2\\omega^2}}\\\\\n\\nonumber\n&=&\\frac{(F_0/m)\\cos(\\omega t-\\delta)}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\beta^2\\omega^2}}.\n\\end{eqnarray}\n$$\n\nThis is the same answer as before.\nIf one wished to solve for the case where $F(t)= F_0\\sin\\omega t$, the imaginary part of the solution would work\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:fastdriven2} \\tag{67}\nx_p(t)&=&\\Im\\frac{(F_0/m)e^{i\\omega t-i\\delta}}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\beta^2\\omega^2}}\\\\\n\\nonumber\n&=&\\frac{(F_0/m)\\sin(\\omega t-\\delta)}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\beta^2\\omega^2}}.\n\\end{eqnarray}\n$$\n\nConsider the damped and driven harmonic oscillator worked out above. Given $F_0, m,\\beta$ and $\\omega_0$, solve for the complete solution $x(t)$ for the case where $F=F_0\\sin\\omega t$ with initial conditions $x(t=0)=0$ and $v(t=0)=0$. Assume the underdamped case.\n\nThe general solution including the arbitrary constants includes both the homogenous and particular solutions,\n\n$$\n\\begin{eqnarray*}\nx(t)&=&\\frac{F_0}{m}\\frac{\\sin(\\omega t-\\delta)}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\beta^2\\omega^2}}\n+A\\cos\\omega't e^{-\\beta t}+B\\sin\\omega't e^{-\\beta t}.\n\\end{eqnarray*}\n$$\n\nThe quantities $\\delta$ and $\\omega'$ are given earlier in the\nsection, $\\omega'=\\sqrt{\\omega_0^2-\\beta^2},\n\\delta=\\tan^{-1}(2\\beta\\omega/(\\omega_0^2-\\omega^2)$. Here, solving\nthe problem means finding the arbitrary constants $A$ and\n$B$. Satisfying the initial conditions for the initial position and\nvelocity:\n\n$$\n\\begin{eqnarray*}\nx(t=0)=0&=&-\\eta\\sin\\delta+A,\\\\\nv(t=0)=0&=&\\omega\\eta\\cos\\delta-\\beta A+\\omega'B,\\\\\n\\eta&\\equiv&\\frac{F_0}{m}\\frac{1}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\beta^2\\omega^2}}.\n\\end{eqnarray*}\n$$\n\nThe problem is now reduced to 2 equations and 2 unknowns, $A$ and $B$. The solution is\n\n$$\n\\begin{eqnarray}\nA&=& \\eta\\sin\\delta ,~~~B=\\frac{-\\omega\\eta\\cos\\delta+\\beta\\eta\\sin\\delta}{\\omega'}.\n\\end{eqnarray}\n$$\n\n## Resonance Widths; the $Q$ factor\n\nFrom the previous two sections, the particular solution for a driving force, $F=F_0\\cos\\omega t$, is\n\n$$\n\\begin{eqnarray}\nx_p(t)&=&\\frac{F_0/m}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\omega^2\\beta^2}}\\cos(\\omega_t-\\delta),\\\\\n\\nonumber\n\\delta&=&\\tan^{-1}\\left(\\frac{2\\beta\\omega}{\\omega_0^2-\\omega^2}\\right).\n\\end{eqnarray}\n$$\n\nIf one fixes the driving frequency $\\omega$ and adjusts the\nfundamental frequency $\\omega_0=\\sqrt{k/m}$, the maximum amplitude\noccurs when $\\omega_0=\\omega$ because that is when the term from the\ndenominator $(\\omega_0^2-\\omega^2)^2+4\\omega^2\\beta^2$ is at a\nminimum. This is akin to dialing into a radio station. However, if one\nfixes $\\omega_0$ and adjusts the driving frequency one minimize with\nrespect to $\\omega$, e.g. set\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{d}{d\\omega}\\left[(\\omega_0^2-\\omega^2)^2+4\\omega^2\\beta^2\\right]=0,\n\\label{_auto49} \\tag{68}\n\\end{equation}\n$$\n\nand one finds that the maximum amplitude occurs when\n$\\omega=\\sqrt{\\omega_0^2-2\\beta^2}$. If $\\beta$ is small relative to\n$\\omega_0$, one can simply state that the maximum amplitude is\n\n\n
\n\n$$\n\\begin{equation}\nx_{\\rm max}\\approx\\frac{F_0}{2m\\beta \\omega_0}.\n\\label{_auto50} \\tag{69}\n\\end{equation}\n$$\n\n$$\n\\begin{eqnarray}\n\\frac{4\\omega^2\\beta^2}{(\\omega_0^2-\\omega^2)^2+4\\omega^2\\beta^2}=\\frac{1}{2}.\n\\end{eqnarray}\n$$\n\nFor small damping this occurs when $\\omega=\\omega_0\\pm \\beta$, so the $FWHM\\approx 2\\beta$. For the purposes of tuning to a specific frequency, one wants the width to be as small as possible. The ratio of $\\omega_0$ to $FWHM$ is known as the {\\it quality} factor, or $Q$ factor,\n\n\n
\n\n$$\n\\begin{equation}\nQ\\equiv \\frac{\\omega_0}{2\\beta}.\n\\label{_auto51} \\tag{70}\n\\end{equation}\n$$\n\n## Numerical Studies of Driven Oscillations\n\nSolving the problem of driven oscillations numerically gives us much\nmore flexibility to study different types of driving forces. We can\nreuse our earlier code by simply adding a driving force. If we stay in\nthe $x$-direction only this can be easily done by adding a term\n$F_{\\mathrm{ext}}(x,t)$. Note that we have kept it rather general\nhere, allowing for both a spatial and a temporal dependence.\n\nBefore we dive into the code, we need to briefly remind ourselves\nabout the equations we started with for the case with damping, namely\n\n$$\nm\\frac{d^2x}{dt^2} + b\\frac{dx}{dt}+kx(t) =0,\n$$\n\nwith no external force applied to the system.\n\nLet us now for simplicty assume that our external force is given by\n\n$$\nF_{\\mathrm{ext}}(t) = F_0\\cos{(\\omega t)},\n$$\n\nwhere $F_0$ is a constant (what is its dimension?) and $\\omega$ is the frequency of the applied external driving force.\n**Small question:** would you expect energy to be conserved now?\n\n\nIntroducing the external force into our lovely differential equation\nand dividing by $m$ and introducing $\\omega_0^2=\\sqrt{k/m}$ we have\n\n$$\n\\frac{d^2x}{dt^2} + \\frac{b}{m}\\frac{dx}{dt}+\\omega_0^2x(t) =\\frac{F_0}{m}\\cos{(\\omega t)},\n$$\n\nThereafter we introduce a dimensionless time $\\tau = t\\omega_0$\nand a dimensionless frequency $\\tilde{\\omega}=\\omega/\\omega_0$. We have then\n\n$$\n\\frac{d^2x}{d\\tau^2} + \\frac{b}{m\\omega_0}\\frac{dx}{d\\tau}+x(\\tau) =\\frac{F_0}{m\\omega_0^2}\\cos{(\\tilde{\\omega}\\tau)},\n$$\n\nIntroducing a new amplitude $\\tilde{F} =F_0/(m\\omega_0^2)$ (check dimensionality again) we have\n\n$$\n\\frac{d^2x}{d\\tau^2} + \\frac{b}{m\\omega_0}\\frac{dx}{d\\tau}+x(\\tau) =\\tilde{F}\\cos{(\\tilde{\\omega}\\tau)}.\n$$\n\nOur final step, as we did in the case of various types of damping, is\nto define $\\gamma = b/(2m\\omega_0)$ and rewrite our equations as\n\n$$\n\\frac{d^2x}{d\\tau^2} + 2\\gamma\\frac{dx}{d\\tau}+x(\\tau) =\\tilde{F}\\cos{(\\tilde{\\omega}\\tau)}.\n$$\n\nThis is the equation we will code below using the Euler-Cromer method.\n\n\n```\nDeltaT = 0.001\n#set up arrays \ntfinal = 20 # in years\nn = ceil(tfinal/DeltaT)\n# set up arrays for t, v, and x\nt = np.zeros(n)\nv = np.zeros(n)\nx = np.zeros(n)\n# Initial conditions as one-dimensional arrays of time\nx0 = 1.0 \nv0 = 0.0\nx[0] = x0\nv[0] = v0\ngamma = 0.2\nOmegatilde = 0.5\nFtilde = 1.0\n# Start integrating using Euler-Cromer's method\nfor i in range(n-1):\n # Set up the acceleration\n # Here you could have defined your own function for this\n a = -2*gamma*v[i]-x[i]+Ftilde*cos(t[i]*Omegatilde)\n # update velocity, time and position\n v[i+1] = v[i] + DeltaT*a\n x[i+1] = x[i] + DeltaT*v[i+1]\n t[i+1] = t[i] + DeltaT\n# Plot position as function of time \nfig, ax = plt.subplots()\nax.set_ylabel('x[m]')\nax.set_xlabel('t[s]')\nax.plot(t, x)\nfig.tight_layout()\nsave_fig(\"ForcedBlockEulerCromer\")\nplt.show()\n```\n\nIn the above example we have focused on the Euler-Cromer method. This\nmethod has a local truncation error which is proportional to $\\Delta t^2$\nand thereby a global error which is proportional to $\\Delta t$.\nWe can improve this by using the Runge-Kutta family of\nmethods. The widely popular Runge-Kutta to fourth order or just **RK4**\nhas indeed a much better truncation error. The RK4 method has a global\nerror which is proportional to $\\Delta t$.\n\nLet us revisit this method and see how we can implement it for the above example.\n\n\n\n## Differential Equations, Runge-Kutta methods\n\nRunge-Kutta (RK) methods are based on Taylor expansion formulae, but yield\nin general better algorithms for solutions of an ordinary differential equation.\nThe basic philosophy is that it provides an intermediate step in the computation of $y_{i+1}$.\n\nTo see this, consider first the following definitions\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{dy}{dt}=f(t,y), \n\\label{_auto52} \\tag{71}\n\\end{equation}\n$$\n\nand\n\n\n
\n\n$$\n\\begin{equation}\ny(t)=\\int f(t,y) dt, \n\\label{_auto53} \\tag{72}\n\\end{equation}\n$$\n\nand\n\n\n
\n\n$$\n\\begin{equation}\ny_{i+1}=y_i+ \\int_{t_i}^{t_{i+1}} f(t,y) dt.\n\\label{_auto54} \\tag{73}\n\\end{equation}\n$$\n\nTo demonstrate the philosophy behind RK methods, let us consider\nthe second-order RK method, RK2.\nThe first approximation consists in Taylor expanding $f(t,y)$\naround the center of the integration interval $t_i$ to $t_{i+1}$,\nthat is, at $t_i+h/2$, $h$ being the step.\nUsing the midpoint formula for an integral, \ndefining $y(t_i+h/2) = y_{i+1/2}$ and \n$t_i+h/2 = t_{i+1/2}$, we obtain\n\n\n
\n\n$$\n\\begin{equation}\n\\int_{t_i}^{t_{i+1}} f(t,y) dt \\approx hf(t_{i+1/2},y_{i+1/2}) +O(h^3).\n\\label{_auto55} \\tag{74}\n\\end{equation}\n$$\n\nThis means in turn that we have\n\n\n
\n\n$$\n\\begin{equation}\ny_{i+1}=y_i + hf(t_{i+1/2},y_{i+1/2}) +O(h^3).\n\\label{_auto56} \\tag{75}\n\\end{equation}\n$$\n\nHowever, we do not know the value of $y_{i+1/2}$. Here comes thus the next approximation, namely, we use Euler's\nmethod to approximate $y_{i+1/2}$. We have then\n\n\n
\n\n$$\n\\begin{equation}\ny_{(i+1/2)}=y_i + \\frac{h}{2}\\frac{dy}{dt}=y(t_i) + \\frac{h}{2}f(t_i,y_i).\n\\label{_auto57} \\tag{76}\n\\end{equation}\n$$\n\nThis means that we can define the following algorithm for \nthe second-order Runge-Kutta method, RK2.\n\n2\n6\n7\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n\n
\n\n$$\n\\begin{equation}\nk_2=hf(t_{i+1/2},y_i+k_1/2),\n\\label{_auto59} \\tag{78}\n\\end{equation}\n$$\n\nwith the final value\n\n\n
\n\n$$\n\\begin{equation} \ny_{i+i}\\approx y_i + k_2 +O(h^3). \n\\label{_auto60} \\tag{79}\n\\end{equation}\n$$\n\nThe difference between the previous one-step methods \nis that we now need an intermediate step in our evaluation,\nnamely $t_i+h/2 = t_{(i+1/2)}$ where we evaluate the derivative $f$. \nThis involves more operations, but the gain is a better stability\nin the solution.\n\nThe fourth-order Runge-Kutta, RK4, has the following algorithm\n\n2\n7\n0\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\nk_3=hf(t_i+h/2,y_i+k_2/2)\\hspace{0.5cm} k_4=hf(t_i+h,y_i+k_3)\n$$\n\nwith the final result\n\n$$\ny_{i+1}=y_i +\\frac{1}{6}\\left( k_1 +2k_2+2k_3+k_4\\right).\n$$\n\nThus, the algorithm consists in first calculating $k_1$ \nwith $t_i$, $y_1$ and $f$ as inputs. Thereafter, we increase the step\nsize by $h/2$ and calculate $k_2$, then $k_3$ and finally $k_4$. The global error goes as $O(h^4)$.\n\n\nHowever, at this stage, if we keep adding different methods in our\nmain program, the code will quickly become messy and ugly. Before we\nproceed thus, we will now introduce functions that enbody the various\nmethods for solving differential equations. This means that we can\nseparate out these methods in own functions and files (and later as classes and more\ngeneric functions) and simply call them when needed. Similarly, we\ncould easily encapsulate various forces or other quantities of\ninterest in terms of functions. To see this, let us bring up the code\nwe developed above for the simple sliding block, but now only with the simple forward Euler method. We introduce\ntwo functions, one for the simple Euler method and one for the\nforce.\n\nNote that here the forward Euler method does not know the specific force function to be called.\nIt receives just an input the name. We can easily change the force by adding another function.\n\n\n```\ndef ForwardEuler(v,x,t,n,Force):\n for i in range(n-1):\n v[i+1] = v[i] + DeltaT*Force(v[i],x[i],t[i])\n x[i+1] = x[i] + DeltaT*v[i]\n t[i+1] = t[i] + DeltaT\n```\n\n\n```\ndef SpringForce(v,x,t):\n# note here that we have divided by mass and we return the acceleration\n return -2*gamma*v-x+Ftilde*cos(t*Omegatilde)\n```\n\nIt is easy to add a new method like the Euler-Cromer\n\n\n```\ndef ForwardEulerCromer(v,x,t,n,Force):\n for i in range(n-1):\n a = Force(v[i],x[i],t[i])\n v[i+1] = v[i] + DeltaT*a\n x[i+1] = x[i] + DeltaT*v[i+1]\n t[i+1] = t[i] + DeltaT\n```\n\nand the Velocity Verlet method (be careful with time-dependence here, it is not an ideal method for non-conservative forces))\n\n\n```\ndef VelocityVerlet(v,x,t,n,Force):\n for i in range(n-1):\n a = Force(v[i],x[i],t[i])\n x[i+1] = x[i] + DeltaT*v[i]+0.5*a\n anew = Force(v[i],x[i+1],t[i+1])\n v[i+1] = v[i] + 0.5*DeltaT*(a+anew)\n t[i+1] = t[i] + DeltaT\n```\n\nFinally, we can now add the Runge-Kutta2 method via a new function\n\n\n```\ndef RK2(v,x,t,n,Force):\n for i in range(n-1):\n# Setting up k1\n k1x = DeltaT*v[i]\n k1v = DeltaT*Force(v[i],x[i],t[i])\n# Setting up k2\n vv = v[i]+k1v*0.5\n xx = x[i]+k1x*0.5\n k2x = DeltaT*vv\n k2v = DeltaT*Force(vv,xx,t[i]+DeltaT*0.5)\n# Final result\n x[i+1] = x[i]+k2x\n v[i+1] = v[i]+k2v\n\tt[i+1] = t[i]+DeltaT\n```\n\nFinally, we can now add the Runge-Kutta2 method via a new function\n\n\n```\ndef RK4(v,x,t,n,Force):\n for i in range(n-1):\n# Setting up k1\n k1x = DeltaT*v[i]\n k1v = DeltaT*Force(v[i],x[i],t[i])\n# Setting up k2\n vv = v[i]+k1v*0.5\n xx = x[i]+k1x*0.5\n k2x = DeltaT*vv\n k2v = DeltaT*Force(vv,xx,t[i]+DeltaT*0.5)\n# Setting up k3\n vv = v[i]+k2v*0.5\n xx = x[i]+k2x*0.5\n k3x = DeltaT*vv\n k3v = DeltaT*Force(vv,xx,t[i]+DeltaT*0.5)\n# Setting up k4\n vv = v[i]+k3v\n xx = x[i]+k3x\n k4x = DeltaT*vv\n k4v = DeltaT*Force(vv,xx,t[i]+DeltaT)\n# Final result\n x[i+1] = x[i]+(k1x+2*k2x+2*k3x+k4x)/6.\n v[i+1] = v[i]+(k1v+2*k2v+2*k3v+k4v)/6.\n t[i+1] = t[i] + DeltaT\n```\n\nThe Runge-Kutta family of methods are particularly useful when we have a time-dependent acceleration.\nIf we have forces which depend only the spatial degrees of freedom (no velocity and/or time-dependence), then energy conserving methods like the Velocity Verlet or the Euler-Cromer method are preferred. As soon as we introduce an explicit time-dependence and/or add dissipitave forces like friction or air resistance, then methods like the family of Runge-Kutta methods are well suited for this. \nThe code below uses the Runge-Kutta4 methods.\n\n\n```\nDeltaT = 0.001\n#set up arrays \ntfinal = 20 # in years\nn = ceil(tfinal/DeltaT)\n# set up arrays for t, v, and x\nt = np.zeros(n)\nv = np.zeros(n)\nx = np.zeros(n)\n# Initial conditions (can change to more than one dim)\nx0 = 1.0 \nv0 = 0.0\nx[0] = x0\nv[0] = v0\ngamma = 0.2\nOmegatilde = 0.5\nFtilde = 1.0\n# Start integrating using Euler's method\n# Note that we define the force function as a SpringForce\nRK4(v,x,t,n,SpringForce)\n\n# Plot position as function of time \nfig, ax = plt.subplots()\nax.set_ylabel('x[m]')\nax.set_xlabel('t[s]')\nax.plot(t, x)\nfig.tight_layout()\nsave_fig(\"ForcedBlockRK4\")\nplt.show()\n```\n\n## Principle of Superposition and Periodic Forces (Fourier Transforms)\n\nIf one has several driving forces, $F(t)=\\sum_n F_n(t)$, one can find\nthe particular solution to each $F_n$, $x_{pn}(t)$, and the particular\nsolution for the entire driving force is\n\n\n
\n\n$$\n\\begin{equation}\nx_p(t)=\\sum_nx_{pn}(t).\n\\label{_auto61} \\tag{80}\n\\end{equation}\n$$\n\nThis is known as the principal of superposition. It only applies when\nthe homogenous equation is linear. If there were an anharmonic term\nsuch as $x^3$ in the homogenous equation, then when one summed various\nsolutions, $x=(\\sum_n x_n)^2$, one would get cross\nterms. Superposition is especially useful when $F(t)$ can be written\nas a sum of sinusoidal terms, because the solutions for each\nsinusoidal (sine or cosine) term is analytic, as we saw above.\n\nDriving forces are often periodic, even when they are not\nsinusoidal. Periodicity implies that for some time $\\tau$\n\n$$\n\\begin{eqnarray}\nF(t+\\tau)=F(t). \n\\end{eqnarray}\n$$\n\nOne example of a non-sinusoidal periodic force is a square wave. Many\ncomponents in electric circuits are non-linear, e.g. diodes, which\nmakes many wave forms non-sinusoidal even when the circuits are being\ndriven by purely sinusoidal sources.\n\nThe code here shows a typical example of such a square wave generated using the functionality included in the **scipy** Python package. We have used a period of $\\tau=0.2$.\n\n\n```\nimport numpy as np\nimport math\nfrom scipy import signal\nimport matplotlib.pyplot as plt\n\n# number of points \nn = 500\n# start and final times \nt0 = 0.0\ntn = 1.0\n# Period \nt = np.linspace(t0, tn, n, endpoint=False)\nSqrSignal = np.zeros(n)\nSqrSignal = 1.0+signal.square(2*np.pi*5*t)\nplt.plot(t, SqrSignal)\nplt.ylim(-0.5, 2.5)\nplt.show()\n```\n\nFor the sinusoidal example studied in the previous subsections the\nperiod is $\\tau=2\\pi/\\omega$. However, higher harmonics can also\nsatisfy the periodicity requirement. In general, any force that\nsatisfies the periodicity requirement can be expressed as a sum over\nharmonics,\n\n\n
\n\n$$\n\\begin{equation}\nF(t)=\\frac{f_0}{2}+\\sum_{n>0} f_n\\cos(2n\\pi t/\\tau)+g_n\\sin(2n\\pi t/\\tau).\n\\label{_auto62} \\tag{81}\n\\end{equation}\n$$\n\nFrom the previous subsection, one can write down the answer for\n$x_{pn}(t)$, by substituting $f_n/m$ or $g_n/m$ for $F_0/m$ into Eq.s\n([66](#eq:fastdriven1)) or ([67](#eq:fastdriven2)) respectively. By\nwriting each factor $2n\\pi t/\\tau$ as $n\\omega t$, with $\\omega\\equiv\n2\\pi/\\tau$,\n\n\n
\n\n$$\n\\begin{equation}\n\\label{eq:fourierdef1} \\tag{82}\nF(t)=\\frac{f_0}{2}+\\sum_{n>0}f_n\\cos(n\\omega t)+g_n\\sin(n\\omega t).\n\\end{equation}\n$$\n\nThe solutions for $x(t)$ then come from replacing $\\omega$ with\n$n\\omega$ for each term in the particular solution in Equations\n([59](#eq:partform)) and ([62](#eq:Ddrive)),\n\n$$\n\\begin{eqnarray}\nx_p(t)&=&\\frac{f_0}{2k}+\\sum_{n>0} \\alpha_n\\cos(n\\omega t-\\delta_n)+\\beta_n\\sin(n\\omega t-\\delta_n),\\\\\n\\nonumber\n\\alpha_n&=&\\frac{f_n/m}{\\sqrt{((n\\omega)^2-\\omega_0^2)+4\\beta^2n^2\\omega^2}},\\\\\n\\nonumber\n\\beta_n&=&\\frac{g_n/m}{\\sqrt{((n\\omega)^2-\\omega_0^2)+4\\beta^2n^2\\omega^2}},\\\\\n\\nonumber\n\\delta_n&=&\\tan^{-1}\\left(\\frac{2\\beta n\\omega}{\\omega_0^2-n^2\\omega^2}\\right).\n\\end{eqnarray}\n$$\n\nBecause the forces have been applied for a long time, any non-zero\ndamping eliminates the homogenous parts of the solution, so one need\nonly consider the particular solution for each $n$.\n\nThe problem will considered solved if one can find expressions for the\ncoefficients $f_n$ and $g_n$, even though the solutions are expressed\nas an infinite sum. The coefficients can be extracted from the\nfunction $F(t)$ by\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:fourierdef2} \\tag{83}\nf_n&=&\\frac{2}{\\tau}\\int_{-\\tau/2}^{\\tau/2} dt~F(t)\\cos(2n\\pi t/\\tau),\\\\\n\\nonumber\ng_n&=&\\frac{2}{\\tau}\\int_{-\\tau/2}^{\\tau/2} dt~F(t)\\sin(2n\\pi t/\\tau).\n\\end{eqnarray}\n$$\n\nTo check the consistency of these expressions and to verify\nEq. ([83](#eq:fourierdef2)), one can insert the expansion of $F(t)$ in\nEq. ([82](#eq:fourierdef1)) into the expression for the coefficients in\nEq. ([83](#eq:fourierdef2)) and see whether\n\n$$\n\\begin{eqnarray}\nf_n&=?&\\frac{2}{\\tau}\\int_{-\\tau/2}^{\\tau/2} dt~\\left\\{\n\\frac{f_0}{2}+\\sum_{m>0}f_m\\cos(m\\omega t)+g_m\\sin(m\\omega t)\n\\right\\}\\cos(n\\omega t).\n\\end{eqnarray}\n$$\n\nImmediately, one can throw away all the terms with $g_m$ because they\nconvolute an even and an odd function. The term with $f_0/2$\ndisappears because $\\cos(n\\omega t)$ is equally positive and negative\nover the interval and will integrate to zero. For all the terms\n$f_m\\cos(m\\omega t)$ appearing in the sum, one can use angle addition\nformulas to see that $\\cos(m\\omega t)\\cos(n\\omega\nt)=(1/2)(\\cos[(m+n)\\omega t]+\\cos[(m-n)\\omega t]$. This will integrate\nto zero unless $m=n$. In that case the $m=n$ term gives\n\n\n
\n\n$$\n\\begin{equation}\n\\int_{-\\tau/2}^{\\tau/2}dt~\\cos^2(m\\omega t)=\\frac{\\tau}{2},\n\\label{_auto63} \\tag{84}\n\\end{equation}\n$$\n\nand\n\n$$\n\\begin{eqnarray}\nf_n&=?&\\frac{2}{\\tau}\\int_{-\\tau/2}^{\\tau/2} dt~f_n/2\\\\\n\\nonumber\n&=&f_n~\\checkmark.\n\\end{eqnarray}\n$$\n\nThe same method can be used to check for the consistency of $g_n$.\n\n\nConsider the driving force:\n\n\n
\n\n$$\n\\begin{equation}\nF(t)=At/\\tau,~~-\\tau/2\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:fouriersolution} \\tag{86}\ng_n&=&\\frac{2}{\\tau}\\int_{-\\tau/2}^{\\tau/2}dt~\\sin(n\\omega t) \\frac{At}{\\tau}\\\\\n\\nonumber\nu&=&t,~dv=\\sin(n\\omega t)dt,~v=-\\cos(n\\omega t)/(n\\omega),\\\\\n\\nonumber\ng_n&=&\\frac{-2A}{n\\omega \\tau^2}\\int_{-\\tau/2}^{\\tau/2}dt~\\cos(n\\omega t)\n+\\left.2A\\frac{-t\\cos(n\\omega t)}{n\\omega\\tau^2}\\right|_{-\\tau/2}^{\\tau/2}.\n\\end{eqnarray}\n$$\n\nThe first term is zero because $\\cos(n\\omega t)$ will be equally\npositive and negative over the interval. Using the fact that\n$\\omega\\tau=2\\pi$,\n\n$$\n\\begin{eqnarray}\ng_n&=&-\\frac{2A}{2n\\pi}\\cos(n\\omega\\tau/2)\\\\\n\\nonumber\n&=&-\\frac{A}{n\\pi}\\cos(n\\pi)\\\\\n\\nonumber\n&=&\\frac{A}{n\\pi}(-1)^{n+1}.\n\\end{eqnarray}\n$$\n\n## Fourier Series\n\nMore text will come here, chpater 5.7-5.8 of Taylor are discussed\nduring the lectures. The code here uses the Fourier series discussed\nin chapter 5.7 for a square wave signal. The equations for the\ncoefficients are are discussed in Taylor section 5.7, see Example\n5.4. The code here visualizes the various approximations given by\nFourier series compared with a square wave with period $T=0.2$, witth\n$0.1$ and max value $F=2$. We see that when we increase the number of\ncomponents in the Fourier series, the Fourier series approximation gets closes and closes to the square wave signal.\n\n\n```\nimport numpy as np\nimport math\nfrom scipy import signal\nimport matplotlib.pyplot as plt\n\n# number of points \nn = 500\n# start and final times \nt0 = 0.0\ntn = 1.0\n# Period \nT =0.2\n# Max value of square signal \nFmax= 2.0\n# Width of signal \nWidth = 0.1\nt = np.linspace(t0, tn, n, endpoint=False)\nSqrSignal = np.zeros(n)\nFourierSeriesSignal = np.zeros(n)\nSqrSignal = 1.0+signal.square(2*np.pi*5*t+np.pi*Width/T)\na0 = Fmax*Width/T\nFourierSeriesSignal = a0\nFactor = 2.0*Fmax/np.pi\nfor i in range(1,500):\n FourierSeriesSignal += Factor/(i)*np.sin(np.pi*i*Width/T)*np.cos(i*t*2*np.pi/T)\nplt.plot(t, SqrSignal)\nplt.plot(t, FourierSeriesSignal)\nplt.ylim(-0.5, 2.5)\nplt.show()\n```\n\n## Solving differential equations with Fouries series\n\nThe material here was discussed during the lecture of February 19 and 21.\nIt is also covered by Taylor in section 5.8.\n\n\nConsider a particle at rest in the bottom of an underdamped harmonic\noscillator, that then feels a sudden impulse, or change in momentum,\n$I=F\\Delta t$ at $t=0$. This increases the velocity immediately by an\namount $v_0=I/m$ while not changing the position. One can then solve\nthe trajectory by solving Eq. ([55](#eq:homogsolution)) with initial\nconditions $v_0=I/m$ and $x_0=0$. This gives\n\n\n
\n\n$$\n\\begin{equation}\nx(t)=\\frac{I}{m\\omega'}e^{-\\beta t}\\sin\\omega't, ~~t>0.\n\\label{_auto65} \\tag{87}\n\\end{equation}\n$$\n\nHere, $\\omega'=\\sqrt{\\omega_0^2-\\beta^2}$. For an impulse $I_i$ that\noccurs at time $t_i$ the trajectory would be\n\n\n
\n\n$$\n\\begin{equation}\nx(t)=\\frac{I_i}{m\\omega'}e^{-\\beta (t-t_i)}\\sin[\\omega'(t-t_i)] \\Theta(t-t_i),\n\\label{_auto66} \\tag{88}\n\\end{equation}\n$$\n\nwhere $\\Theta(t-t_i)$ is a step function, i.e. $\\Theta(x)$ is zero for\n$x<0$ and unity for $x>0$. If there were several impulses linear\nsuperposition tells us that we can sum over each contribution,\n\n\n
\n\n$$\n\\begin{equation}\nx(t)=\\sum_i\\frac{I_i}{m\\omega'}e^{-\\beta(t-t_i)}\\sin[\\omega'(t-t_i)]\\Theta(t-t_i)\n\\label{_auto67} \\tag{89}\n\\end{equation}\n$$\n\nNow one can consider a series of impulses at times separated by\n$\\Delta t$, where each impulse is given by $F_i\\Delta t$. The sum\nabove now becomes an integral,\n\n\n
\n\n$$\n\\begin{eqnarray}\\label{eq:Greeny} \\tag{90}\nx(t)&=&\\int_{-\\infty}^\\infty dt'~F(t')\\frac{e^{-\\beta(t-t')}\\sin[\\omega'(t-t')]}{m\\omega'}\\Theta(t-t')\\\\\n\\nonumber\n&=&\\int_{-\\infty}^\\infty dt'~F(t')G(t-t'),\\\\\n\\nonumber\nG(\\Delta t)&=&\\frac{e^{-\\beta\\Delta t}\\sin[\\omega' \\Delta t]}{m\\omega'}\\Theta(\\Delta t)\n\\end{eqnarray}\n$$\n\nThe quantity\n$e^{-\\beta(t-t')}\\sin[\\omega'(t-t')]/m\\omega'\\Theta(t-t')$ is called a\nGreen's function, $G(t-t')$. It describes the response at $t$ due to a\nforce applied at a time $t'$, and is a function of $t-t'$. The step\nfunction ensures that the response does not occur before the force is\napplied. One should remember that the form for $G$ would change if the\noscillator were either critically- or over-damped.\n\nWhen performing the integral in Eq. ([90](#eq:Greeny)) one can use\nangle addition formulas to factor out the part with the $t'$\ndependence in the integrand,\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:Greeny2} \\tag{91}\nx(t)&=&\\frac{1}{m\\omega'}e^{-\\beta t}\\left[I_c(t)\\sin(\\omega't)-I_s(t)\\cos(\\omega't)\\right],\\\\\n\\nonumber\nI_c(t)&\\equiv&\\int_{-\\infty}^t dt'~F(t')e^{\\beta t'}\\cos(\\omega't'),\\\\\n\\nonumber\nI_s(t)&\\equiv&\\int_{-\\infty}^t dt'~F(t')e^{\\beta t'}\\sin(\\omega't').\n\\end{eqnarray}\n$$\n\nIf the time $t$ is beyond any time at which the force acts,\n$F(t'>t)=0$, the coefficients $I_c$ and $I_s$ become independent of\n$t$.\n\n\nConsider an undamped oscillator ($\\beta\\rightarrow 0$), with\ncharacteristic frequency $\\omega_0$ and mass $m$, that is at rest\nuntil it feels a force described by a Gaussian form,\n\n$$\n\\begin{eqnarray*}\nF(t)&=&F_0 \\exp\\left\\{\\frac{-t^2}{2\\tau^2}\\right\\}.\n\\end{eqnarray*}\n$$\n\nFor large times ($t>>\\tau$), where the force has died off, find\n$x(t)$.\\\\ Solve for the coefficients $I_c$ and $I_s$ in\nEq. ([91](#eq:Greeny2)). Because the Gaussian is an even function,\n$I_s=0$, and one need only solve for $I_c$,\n\n$$\n\\begin{eqnarray*}\nI_c&=&F_0\\int_{-\\infty}^\\infty dt'~e^{-t^{\\prime 2}/(2\\tau^2)}\\cos(\\omega_0 t')\\\\\n&=&\\Re F_0 \\int_{-\\infty}^\\infty dt'~e^{-t^{\\prime 2}/(2\\tau^2)}e^{i\\omega_0 t'}\\\\\n&=&\\Re F_0 \\int_{-\\infty}^\\infty dt'~e^{-(t'-i\\omega_0\\tau^2)^2/(2\\tau^2)}e^{-\\omega_0^2\\tau^2/2}\\\\\n&=&F_0\\tau \\sqrt{2\\pi} e^{-\\omega_0^2\\tau^2/2}.\n\\end{eqnarray*}\n$$\n\nThe third step involved completing the square, and the final step used the fact that the integral\n\n$$\n\\begin{eqnarray*}\n\\int_{-\\infty}^\\infty dx~e^{-x^2/2}&=&\\sqrt{2\\pi}.\n\\end{eqnarray*}\n$$\n\nTo see that this integral is true, consider the square of the integral, which you can change to polar coordinates,\n\n$$\n\\begin{eqnarray*}\nI&=&\\int_{-\\infty}^\\infty dx~e^{-x^2/2}\\\\\nI^2&=&\\int_{-\\infty}^\\infty dxdy~e^{-(x^2+y^2)/2}\\\\\n&=&2\\pi\\int_0^\\infty rdr~e^{-r^2/2}\\\\\n&=&2\\pi.\n\\end{eqnarray*}\n$$\n\nFinally, the expression for $x$ from Eq. ([91](#eq:Greeny2)) is\n\n$$\n\\begin{eqnarray*}\nx(t>>\\tau)&=&\\frac{F_0\\tau}{m\\omega_0} \\sqrt{2\\pi} e^{-\\omega_0^2\\tau^2/2}\\sin(\\omega_0t).\n\\end{eqnarray*}\n$$\n\n## The classical pendulum and scaling the equations\n\nLet us end our discussion of oscillations with another classical case, the pendulum.\n\nThe angular equation of motion of the pendulum is given by\nNewton's equation and with no external force it reads\n\n\n
\n\n$$\n\\begin{equation}\n ml\\frac{d^2\\theta}{dt^2}+mgsin(\\theta)=0,\n\\label{_auto68} \\tag{92}\n\\end{equation}\n$$\n\nwith an angular velocity and acceleration given by\n\n\n
\n\n$$\n\\begin{equation}\n v=l\\frac{d\\theta}{dt},\n\\label{_auto69} \\tag{93}\n\\end{equation}\n$$\n\nand\n\n\n
\n\n$$\n\\begin{equation}\n a=l\\frac{d^2\\theta}{dt^2}.\n\\label{_auto70} \\tag{94}\n\\end{equation}\n$$\n\nWe do however expect that the motion will gradually come to an end due a viscous drag torque acting on the pendulum. \nIn the presence of the drag, the above equation becomes\n\n\n
\n\n$$\n\\begin{equation}\n ml\\frac{d^2\\theta}{dt^2}+\\nu\\frac{d\\theta}{dt} +mgsin(\\theta)=0, \n\\label{_auto71} \\tag{95}\n\\end{equation}\n$$\n\nwhere $\\nu$ is now a positive constant parameterizing the viscosity\nof the medium in question. In order to maintain the motion against\nviscosity, it is necessary to add some external driving force. \nWe choose here a periodic driving force. The last equation becomes then\n\n\n
\n\n$$\n\\begin{equation}\n ml\\frac{d^2\\theta}{dt^2}+\\nu\\frac{d\\theta}{dt} +mgsin(\\theta)=Asin(\\omega t), \n\\label{_auto72} \\tag{96}\n\\end{equation}\n$$\n\nwith $A$ and $\\omega$ two constants representing the amplitude and \nthe angular frequency respectively. The latter is called the driving frequency.\n\n\n\nWe define\n\n$$\n\\omega_0=\\sqrt{g/l},\n$$\n\nthe so-called natural frequency and the new dimensionless quantities\n\n$$\n\\hat{t}=\\omega_0t,\n$$\n\nwith the dimensionless driving frequency\n\n$$\n\\hat{\\omega}=\\frac{\\omega}{\\omega_0},\n$$\n\nand introducing the quantity $Q$, called the *quality factor*,\n\n$$\nQ=\\frac{mg}{\\omega_0\\nu},\n$$\n\nand the dimensionless amplitude\n\n$$\n\\hat{A}=\\frac{A}{mg}\n$$\n\nWe have\n\n$$\n\\frac{d^2\\theta}{d\\hat{t}^2}+\\frac{1}{Q}\\frac{d\\theta}{d\\hat{t}} \n +sin(\\theta)=\\hat{A}cos(\\hat{\\omega}\\hat{t}).\n$$\n\nThis equation can in turn be recast in terms of two coupled first-order differential equations as follows\n\n$$\n\\frac{d\\theta}{d\\hat{t}}=\\hat{v},\n$$\n\nand\n\n$$\n\\frac{d\\hat{v}}{d\\hat{t}}=-\\frac{\\hat{v}}{Q}-sin(\\theta)+\\hat{A}cos(\\hat{\\omega}\\hat{t}).\n$$\n\nThese are the equations to be solved. The factor $Q$ represents the\nnumber of oscillations of the undriven system that must occur before\nits energy is significantly reduced due to the viscous drag. The\namplitude $\\hat{A}$ is measured in units of the maximum possible\ngravitational torque while $\\hat{\\omega}$ is the angular frequency of\nthe external torque measured in units of the pendulum's natural\nfrequency.\n\n# Gravity and Central Forces\n\n\nThe gravitational potential energy and forces involving two masses $a$ and $b$ are\n\n$$\n\\begin{eqnarray}\nU_{ab}&=&-\\frac{Gm_am_b}{|\\boldsymbol{r}_a-\\boldsymbol{r}_b|},\\\\\n\\nonumber\nF_{ba}&=&-\\frac{Gm_am_b}{|\\boldsymbol{r}_a-\\boldsymbol{r}_b|^2}\\hat{r}_{ab},\\\\\n\\nonumber\n\\hat{r}_{ab}&=&\\frac{\\boldsymbol{r}_b-\\boldsymbol{r}_a}{|\\boldsymbol{r}_a-\\boldsymbol{r}_b|}.\n\\end{eqnarray}\n$$\n\nHere $G=6.67\\times 10^{-11}$ Nm$^2$/kg$^2$, and $F_{ba}$ is the force\non $b$ due to $a$. By inspection, one can see that the force on $b$\ndue to $a$ and the force on $a$ due to $b$ are equal and opposite. The\nnet potential energy for a large number of masses would be\n\n\n
\n\n$$\n\\begin{equation}\nU=\\sum_{a\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:radialeqofmotion} \\tag{98}\n\\frac{d}{dt}r^2&=&\\frac{d}{dt}(x^2+y^2)=2x\\dot{x}+2y\\dot{y}=2r\\dot{r},\\\\\n\\nonumber\n\\dot{r}&=&\\frac{x}{r}\\dot{x}+\\frac{y}{r}\\dot{y},\\\\\n\\nonumber\n\\ddot{r}&=&\\frac{x}{r}\\ddot{x}+\\frac{y}{r}\\ddot{y}\n+\\frac{\\dot{x}^2+\\dot{y}^2}{r}\n-\\frac{\\dot{r}^2}{r}.\n\\end{eqnarray}\n$$\n\nRecognizing that the numerator of the third term is the velocity squared, and that it can be written in polar coordinates,\n\n\n
\n\n$$\n\\begin{equation}\nv^2=\\dot{x}^2+\\dot{y}^2=\\dot{r}^2+r^2\\dot{\\theta}^2,\n\\label{_auto74} \\tag{99}\n\\end{equation}\n$$\n\none can write $\\ddot{r}$ as\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:radialeqofmotion2} \\tag{100}\n\\ddot{r}&=&\\frac{F_x\\cos\\theta+F_y\\sin\\theta}{m}+\\frac{\\dot{r}^2+r^2\\dot{\\theta}^2}{r}-\\frac{\\dot{r}^2}{r}\\\\\n\\nonumber\n&=&\\frac{F}{m}+\\frac{r^2\\dot{\\theta}^2}{r}\\\\\n\\nonumber\nm\\ddot{r}&=&F+\\frac{L^2}{mr^3}.\n\\end{eqnarray}\n$$\n\nThis derivation used the fact that the force was radial,\n$F=F_r=F_x\\cos\\theta+F_y\\sin\\theta$, and that angular momentum is\n$L=mrv_{\\theta}=mr^2\\dot{\\theta}$. The term $L^2/mr^3=mv^2/r$ behaves\nlike an additional force. Sometimes this is referred to as a\ncentrifugal force, but it is not a force. Instead, it is the\nconsequence of considering the motion in a rotating (and therefore\naccelerating) frame.\n\nNow, we switch to the particular case of an attractive inverse square\nforce, $F=-\\alpha/r^2$, and show that the trajectory, $r(\\theta)$, is\nan ellipse. To do this we transform derivatives w.r.t. time to\nderivatives w.r.t. $\\theta$ using the chain rule combined with angular\nmomentum conservation, $\\dot{\\theta}=L/mr^2$.\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:rtotheta} \\tag{101}\n\\dot{r}&=&\\frac{dr}{d\\theta}\\dot{\\theta}=\\frac{dr}{d\\theta}\\frac{L}{mr^2},\\\\\n\\nonumber\n\\ddot{r}&=&\\frac{d^2r}{d\\theta^2}\\dot{\\theta}^2\n+\\frac{dr}{d\\theta}\\left(\\frac{d}{dr}\\frac{L}{mr^2}\\right)\\dot{r}\\\\\n\\nonumber\n&=&\\frac{d^2r}{d\\theta^2}\\left(\\frac{L}{mr^2}\\right)^2\n-2\\frac{dr}{d\\theta}\\frac{L}{mr^3}\\dot{r}\\\\\n\\nonumber\n&=&\\frac{d^2r}{d\\theta^2}\\left(\\frac{L}{mr^2}\\right)^2\n-\\frac{2}{r}\\left(\\frac{dr}{d\\theta}\\right)^2\\left(\\frac{L}{mr^2}\\right)^2\n\\end{eqnarray}\n$$\n\nEquating the two expressions for $\\ddot{r}$ in Eq.s ([100](#eq:radialeqofmotion2)) and ([101](#eq:rtotheta)) eliminates all the derivatives w.r.t. time, and provides a differential equation with only derivatives w.r.t. $\\theta$,\n\n\n
\n\n$$\n\\begin{equation}\n\\label{eq:rdotdot} \\tag{102}\n\\frac{d^2r}{d\\theta^2}\\left(\\frac{L}{mr^2}\\right)^2\n-\\frac{2}{r}\\left(\\frac{dr}{d\\theta}\\right)^2\\left(\\frac{L}{mr^2}\\right)^2\n=\\frac{F}{m}+\\frac{L^2}{m^2r^3},\n\\end{equation}\n$$\n\nthat when solved yields the trajectory, i.e. $r(\\theta)$. Up to this\npoint the expressions work for any radial force, not just forces that\nfall as $1/r^2$.\n\nThe trick to simplifying this differential equation for the inverse\nsquare problems is to make a substitution, $u\\equiv 1/r$, and rewrite\nthe differential equation for $u(\\theta)$.\n\n$$\n\\begin{eqnarray}\nr&=&1/u,\\\\\n\\nonumber\n\\frac{dr}{d\\theta}&=&-\\frac{1}{u^2}\\frac{du}{d\\theta},\\\\\n\\nonumber\n\\frac{d^2r}{d\\theta^2}&=&\\frac{2}{u^3}\\left(\\frac{du}{d\\theta}\\right)^2-\\frac{1}{u^2}\\frac{d^2u}{d\\theta^2}.\n\\end{eqnarray}\n$$\n\nPlugging these expressions into Eq. ([102](#eq:rdotdot)) gives an\nexpression in terms of $u$, $du/d\\theta$, and $d^2u/d\\theta^2$. After\nsome tedious algebra,\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{d^2u}{d\\theta^2}=-u-\\frac{F m}{L^2u^2}.\n\\label{_auto75} \\tag{103}\n\\end{equation}\n$$\n\nFor the attractive inverse square law force, $F=-\\alpha u^2$,\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{d^2u}{d\\theta^2}=-u+\\frac{m\\alpha}{L^2}.\n\\label{_auto76} \\tag{104}\n\\end{equation}\n$$\n\nThe solution has two arbitrary constants, $A$ and $\\theta_0$,\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:Ctrajectory} \\tag{105}\nu&=&\\frac{m\\alpha}{L^2}+A\\cos(\\theta-\\theta_0),\\\\\n\\nonumber\nr&=&\\frac{1}{(m\\alpha/L^2)+A\\cos(\\theta-\\theta_0)}.\n\\end{eqnarray}\n$$\n\nThe radius will be at a minimum when $\\theta=\\theta_0$ and at a\nmaximum when $\\theta=\\theta_0+\\pi$. The constant $A$ is related to the\neccentricity of the orbit. When $A=0$ the radius is a constant\n$r=L^2/(m\\alpha)$, and the motion is circular. If one solved the\nexpression $mv^2/r=-\\alpha/r^2$ for a circular orbit, using the\nsubstitution $v=L/(mr)$, one would reproduce the expression\n$r=L^2/(m\\alpha)$.\n\nThe form describing the elliptical trajectory in\nEq. ([105](#eq:Ctrajectory)) can be identified as an ellipse with one\nfocus being the center of the ellipse by considering the definition of\nan ellipse as being the points such that the sum of the two distances\nbetween the two foci are a constant. Making that distance $2D$, the\ndistance between the two foci as $2a$, and putting one focus at the\norigin,\n\n$$\n\\begin{eqnarray}\n2D&=&r+\\sqrt{(r\\cos\\theta-2a)^2+r^2\\sin^2\\theta},\\\\\n\\nonumber\n4D^2+r^2-4Dr&=&r^2+4a^2-4ar\\cos\\theta,\\\\\n\\nonumber\nr&=&\\frac{D^2-a^2}{D+a\\cos\\theta}=\\frac{1}{D/(D^2-a^2)-a\\cos\\theta/(D^2-a^2)}.\n\\end{eqnarray}\n$$\n\nBy inspection, this is the same form as Eq. ([105](#eq:Ctrajectory)) with $D/(D^2-a^2)=m\\alpha/L^2$ and $a/(D^2-a^2)=A$.\n\n\nLet us remind ourselves about what an ellipse is before we proceed.\n\n\n```\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom math import pi\n\nu=1. #x-position of the center\nv=0.5 #y-position of the center\na=2. #radius on the x-axis\nb=1.5 #radius on the y-axis\n\nt = np.linspace(0, 2*pi, 100)\nplt.plot( u+a*np.cos(t) , v+b*np.sin(t) )\nplt.grid(color='lightgray',linestyle='--')\nplt.show()\n```\n\n## Effective or Centrifugal Potential\n\nThe total energy of a particle is\n\n$$\n\\begin{eqnarray}\nE&=&U(r)+\\frac{1}{2}mv_\\theta^2+\\frac{1}{2}m\\dot{r}^2\\\\\n\\nonumber\n&=&U(r)+\\frac{1}{2}mr^2\\dot{\\theta}^2+\\frac{1}{2}m\\dot{r}^2\\\\\n\\nonumber\n&=&U(r)+\\frac{L^2}{2mr^2}+\\frac{1}{2}m\\dot{r}^2.\n\\end{eqnarray}\n$$\n\nThe second term then contributes to the energy like an additional\nrepulsive potential. The term is sometimes referred to as the\n\"centrifugal\" potential, even though it is actually the kinetic energy\nof the angular motion. Combined with $U(r)$, it is sometimes referred\nto as the \"effective\" potential,\n\n$$\n\\begin{eqnarray}\nU_{\\rm eff}(r)&=&U(r)+\\frac{L^2}{2mr^2}.\n\\end{eqnarray}\n$$\n\nNote that if one treats the effective potential like a real potential, one would expect to be able to generate an effective force,\n\n$$\n\\begin{eqnarray}\nF_{\\rm eff}&=&-\\frac{d}{dr}U(r) -\\frac{d}{dr}\\frac{L^2}{2mr^2}\\\\\n\\nonumber\n&=&F(r)+\\frac{L^2}{mr^3}=F(r)+m\\frac{v_\\perp^2}{r},\n\\end{eqnarray}\n$$\n\nwhich is indeed matches the form for $m\\ddot{r}$ in Eq. ([100](#eq:radialeqofmotion2)), which included the **centrifugal** force.\n\nThe following code plots this effective potential for a simple choice of parameters, with a standard gravitational potential $-\\alpha/r$. Here we have chosen $L=m=\\alpha=1$.\n\n\n```\n# Common imports\nimport numpy as np\nfrom math import *\nimport matplotlib.pyplot as plt\n\nDeltax = 0.01\n#set up arrays\nxinitial = 0.3\nxfinal = 5.0\nalpha = 1.0 # spring constant\nm = 1.0 # mass, you can change these\nAngMom = 1.0 # The angular momentum\nn = ceil((xfinal-xinitial)/Deltax)\nx = np.zeros(n)\nfor i in range(n):\n x[i] = xinitial+i*Deltax\nV = np.zeros(n)\nV = -alpha/x+0.5*AngMom*AngMom/(m*x*x)\n# Plot potential\nfig, ax = plt.subplots()\nax.set_xlabel('r[m]')\nax.set_ylabel('V[J]')\nax.plot(x, V)\nfig.tight_layout()\nplt.show()\n```\n\n### Gravitational force example\n\nUsing the above parameters, we can now study the evolution of the system using for example the velocity Verlet method.\nThis is done in the code here for an initial radius equal to the minimum of the potential well. We seen then that the radius is always the same and corresponds to a circle (the radius is always constant).\n\n\n```\n# Common imports\nimport numpy as np\nimport pandas as pd\nfrom math import *\nimport matplotlib.pyplot as plt\nimport os\n\n# Where to save the figures and data files\nPROJECT_ROOT_DIR = \"Results\"\nFIGURE_ID = \"Results/FigureFiles\"\nDATA_ID = \"DataFiles/\"\n\nif not os.path.exists(PROJECT_ROOT_DIR):\n os.mkdir(PROJECT_ROOT_DIR)\n\nif not os.path.exists(FIGURE_ID):\n os.makedirs(FIGURE_ID)\n\nif not os.path.exists(DATA_ID):\n os.makedirs(DATA_ID)\n\ndef image_path(fig_id):\n return os.path.join(FIGURE_ID, fig_id)\n\ndef data_path(dat_id):\n return os.path.join(DATA_ID, dat_id)\n\ndef save_fig(fig_id):\n plt.savefig(image_path(fig_id) + \".png\", format='png')\n\n\n# Simple Gravitational Force -alpha/r\n \nDeltaT = 0.01\n#set up arrays \ntfinal = 100.0\nn = ceil(tfinal/DeltaT)\n# set up arrays for t, v and r\nt = np.zeros(n)\nv = np.zeros(n)\nr = np.zeros(n)\n# Constants of the model, setting all variables to one for simplicity\nalpha = 1.0\nAngMom = 1.0 # The angular momentum\nm = 1.0 # scale mass to one\nc1 = AngMom*AngMom/(m*m)\nc2 = AngMom*AngMom/m\nrmin = (AngMom*AngMom/m/alpha)\n# Initial conditions\nr0 = rmin\nv0 = 0.0\nr[0] = r0\nv[0] = v0\n# Start integrating using the Velocity-Verlet method\nfor i in range(n-1):\n # Set up acceleration\n a = -alpha/(r[i]**2)+c1/(r[i]**3)\n # update velocity, time and position using the Velocity-Verlet method\n r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a\n anew = -alpha/(r[i+1]**2)+c1/(r[i+1]**3)\n v[i+1] = v[i] + 0.5*DeltaT*(a+anew)\n t[i+1] = t[i] + DeltaT\n # Plot position as function of time\nfig, ax = plt.subplots(2,1)\nax[0].set_xlabel('time')\nax[0].set_ylabel('radius')\nax[0].plot(t,r)\nax[1].set_xlabel('time')\nax[1].set_ylabel('Velocity')\nax[1].plot(t,v)\nsave_fig(\"RadialGVV\")\nplt.show()\n```\n\nChanging the value of the initial position to a value where the energy is positive, leads to an increasing radius with time, a so-called unbound orbit. Choosing on the other hand an initial radius that corresponds to a negative energy and different from the minimum value leads to a radius that oscillates back and forth between two values. \n\n### Harmonic Oscillator in two dimensions\n\nConsider a particle of mass $m$ in a 2-dimensional harmonic oscillator with potential\n\n$$\nU=\\frac{1}{2}kr^2=\\frac{1}{2}k(x^2+y^2).\n$$\n\nIf the orbit has angular momentum $L$, we can find the radius and angular velocity of the circular orbit as well as the b) the angular frequency of small radial perturbations.\n\nWe consider the effective potential. The radius of a circular orbit is at the minimum of the potential (where the effective force is zero).\nThe potential is plotted here with the parameters $k=m=0.1$ and $L=1.0$.\n\n\n```\n# Common imports\nimport numpy as np\nfrom math import *\nimport matplotlib.pyplot as plt\n\nDeltax = 0.01\n#set up arrays\nxinitial = 1.0\nxfinal = 5.0\nk = 0.1 # spring constant\nm = 0.1 # mass, you can change these\nAngMom = 1.0 # The angular momentum\nn = ceil((xfinal-xinitial)/Deltax)\nx = np.zeros(n)\nfor i in range(n):\n x[i] = xinitial+i*Deltax\nV = np.zeros(n)\nV = 0.5*k*x*x+0.5*AngMom*AngMom/(m*x*x)\n# Plot potential\nfig, ax = plt.subplots()\nax.set_xlabel('r[m]')\nax.set_ylabel('V[J]')\nax.plot(x, V)\nfig.tight_layout()\nplt.show()\n```\n\n$$\n\\begin{eqnarray*}\nU_{\\rm eff}&=&\\frac{1}{2}kr^2+\\frac{L^2}{2mr^2}\n\\end{eqnarray*}\n$$\n\nThe effective potential looks like that of a harmonic oscillator for\nlarge $r$, but for small $r$, the centrifugal potential repels the\nparticle from the origin. The combination of the two potentials has a\nminimum for at some radius $r_{\\rm min}$.\n\n$$\n\\begin{eqnarray*}\n0&=&kr_{\\rm min}-\\frac{L^2}{mr_{\\rm min}^3},\\\\\nr_{\\rm min}&=&\\left(\\frac{L^2}{mk}\\right)^{1/4},\\\\\n\\dot{\\theta}&=&\\frac{L}{mr_{\\rm min}^2}=\\sqrt{k/m}.\n\\end{eqnarray*}\n$$\n\nFor particles at $r_{\\rm min}$ with $\\dot{r}=0$, the particle does not\naccelerate and $r$ stays constant, i.e. a circular orbit. The radius\nof the circular orbit can be adjusted by changing the angular momentum\n$L$.\n\nFor the above parameters this minimum is at $r_{\\rm min}=1$.\n\n Now consider small vibrations about $r_{\\rm min}$. The effective spring constant is the curvature of the effective potential.\n\n$$\n\\begin{eqnarray*}\nk_{\\rm eff}&=&\\left.\\frac{d^2}{dr^2}U_{\\rm eff}(r)\\right|_{r=r_{\\rm min}}=k+\\frac{3L^2}{mr_{\\rm min}^4}\\\\\n&=&4k,\\\\\n\\omega&=&\\sqrt{k_{\\rm eff}/m}=2\\sqrt{k/m}=2\\dot{\\theta}.\n\\end{eqnarray*}\n$$\n\nHere, the second step used the result of the last step from part\n(a). Because the radius oscillates with twice the angular frequency,\nthe orbit has two places where $r$ reaches a minimum in one\ncycle. This differs from the inverse-square force where there is one\nminimum in an orbit. One can show that the orbit for the harmonic\noscillator is also elliptical, but in this case the center of the\npotential is at the center of the ellipse, not at one of the foci.\n\nThe solution is also simple to write down exactly in Cartesian coordinates. The $x$ and $y$ equations of motion separate,\n\n$$\n\\begin{eqnarray*}\n\\ddot{x}&=&-kx,\\\\\n\\ddot{y}&=&-ky.\n\\end{eqnarray*}\n$$\n\nSo the general solution can be expressed as\n\n$$\n\\begin{eqnarray*}\nx&=&A\\cos\\omega_0 t+B\\sin\\omega_0 t,\\\\\ny&=&C\\cos\\omega_0 t+D\\sin\\omega_0 t.\n\\end{eqnarray*}\n$$\n\nThe code here finds the solution for $x$ and $y$ using the code we developed in homework 4.\n\n\n```\n\nDeltaT = 0.01\n#set up arrays \ntfinal = 10.0\nn = ceil(tfinal/DeltaT)\n# set up arrays\nt = np.zeros(n)\nv = np.zeros((n,2))\nr = np.zeros((n,2))\nradius = np.zeros(n)\n# Constants of the model\nk = 0.1 # spring constant\nm = 0.1 # mass, you can change these\nomega02 = sqrt(k/m) # Frequency\nAngMom = 1.0 # The angular momentum\nrmin = (AngMom*AngMom/k/m)**0.25\n# Initial conditions as compact 2-dimensional arrays\n#x0 =rmin*0.5; y0 = sqrt(rmin*rmin-x0*x0)\nx0 = 1.0; y0= 1.0\nr0 = np.array([x0,y0]) \nv0 = np.array([0.0,0.0])\nr[0] = r0\nv[0] = v0\n# Start integrating using the Velocity-Verlet method\nfor i in range(n-1):\n # Set up the acceleration\n a = -r[i]*omega02 \n # update velocity, time and position using the Velocity-Verlet method\n r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a\n anew = -r[i+1]*omega02 \n v[i+1] = v[i] + 0.5*DeltaT*(a+anew)\n t[i+1] = t[i] + DeltaT\n# Plot position as function of time\nradius = np.sqrt(r[:,0]**2+r[:,1]**2)\nfig, ax = plt.subplots(3,1)\nax[0].set_xlabel('time')\nax[0].set_ylabel('radius squared')\nax[0].plot(t,r[:,0]**2+r[:,1]**2)\nax[1].set_xlabel('time')\nax[1].set_ylabel('x position')\nax[1].plot(t,r[:,0])\nax[2].set_xlabel('time')\nax[2].set_ylabel('y position')\nax[2].plot(t,r[:,1])\n\nfig.tight_layout()\nsave_fig(\"2DimHOVV\")\nplt.show()\n```\n\nWith some work using double angle formulas, one can calculate\n\n$$\n\\begin{eqnarray*}\nr^2&=&x^2+y^2\\\\\n\\nonumber\n&=&(A^2+C^2)\\cos^2(\\omega_0t)+(B^2+D^2)\\sin^2\\omega_0t+(AB+CD)\\cos(\\omega_0t)\\sin(\\omega_0t)\\\\\n\\nonumber\n&=&\\alpha+\\beta\\cos 2\\omega_0 t+\\gamma\\sin 2\\omega_0 t,\\\\\n\\alpha&=&\\frac{A^2+B^2+C^2+D^2}{2},~~\\beta=\\frac{A^2-B^2+C^2-D^2}{2},~~\\gamma=AB+CD,\\\\\nr^2&=&\\alpha+(\\beta^2+\\gamma^2)^{1/2}\\cos(2\\omega_0 t-\\delta),~~~\\delta=\\arctan(\\gamma/\\beta),\n\\end{eqnarray*}\n$$\n\nand see that radius oscillates with frequency $2\\omega_0$. The\nfactor of two comes because the oscillation $x=A\\cos\\omega_0t$ has two\nmaxima for $x^2$, one at $t=0$ and one a half period later.\n\nThe following code shows first how we can solve this problem using the radial degrees of freedom only.\n\n\n```\nDeltaT = 0.01\n#set up arrays \ntfinal = 10.0\nn = ceil(tfinal/DeltaT)\n# set up arrays for t, v and r\nt = np.zeros(n)\nv = np.zeros(n)\nr = np.zeros(n)\nE = np.zeros(n)\n# Constants of the model\nAngMom = 1.0 # The angular momentum\nm = 0.1\nk = 0.1\nomega02 = k/m\nc1 = AngMom*AngMom/(m*m)\nc2 = AngMom*AngMom/m\nrmin = (AngMom*AngMom/k/m)**0.25\n# Initial conditions\nr0 = rmin\nv0 = 0.0\nr[0] = r0\nv[0] = v0\nE[0] = 0.5*m*v0*v0+0.5*k*r0*r0+0.5*c2/(r0*r0)\n# Start integrating using the Velocity-Verlet method\nfor i in range(n-1):\n # Set up acceleration\n a = -r[i]*omega02+c1/(r[i]**3) \n # update velocity, time and position using the Velocity-Verlet method\n r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a\n anew = -r[i+1]*omega02+c1/(r[i+1]**3)\n v[i+1] = v[i] + 0.5*DeltaT*(a+anew)\n t[i+1] = t[i] + DeltaT\n E[i+1] = 0.5*m*v[i+1]*v[i+1]+0.5*k*r[i+1]*r[i+1]+0.5*c2/(r[i+1]*r[i+1])\n # Plot position as function of time\nfig, ax = plt.subplots(2,1)\nax[0].set_xlabel('time')\nax[0].set_ylabel('radius')\nax[0].plot(t,r)\nax[1].set_xlabel('time')\nax[1].set_ylabel('Energy')\nax[1].plot(t,E)\nsave_fig(\"RadialHOVV\")\nplt.show()\n```\n\n## Stability of Orbits\n\nThe effective force can be extracted from the effective potential, $U_{\\rm eff}$. Beginning from the equations of motion, Eq. ([98](#eq:radialeqofmotion)), for $r$,\n\n$$\n\\begin{eqnarray}\nm\\ddot{r}&=&F+\\frac{L^2}{mr^3}\\\\\n\\nonumber\n&=&F_{\\rm eff}\\\\\n\\nonumber\n&=&-\\partial_rU_{\\rm eff},\\\\\n\\nonumber\nF_{\\rm eff}&=&-\\partial_r\\left[U(r)+(L^2/2mr^2)\\right].\n\\end{eqnarray}\n$$\n\nFor a circular orbit, the radius must be fixed as a function of time,\nso one must be at a maximum or a minimum of the effective\npotential. However, if one is at a maximum of the effective potential\nthe radius will be unstable. For the attractive Coulomb force the\neffective potential will be dominated by the $-\\alpha/r$ term for\nlarge $r$ because the centrifugal part falls off more quickly, $\\sim\n1/r^2$. At low $r$ the centrifugal piece wins and the effective\npotential is repulsive. Thus, the potential must have a minimum\nsomewhere with negative potential. The circular orbits are then stable\nto perturbation.\n\n\nThe effective potential is sketched for two cases, a $1/r$ attractive\npotential and a $1/r^3$ attractive potential. The $1/r$ case has a\nstable minimum, whereas the circular orbit in the $1/r^3$ case is\nunstable.\n\n\nIf one considers a potential that falls as $1/r^3$, the situation is\nreversed and the point where $\\partial_rU$ disappears will be a local\nmaximum rather than a local minimum. **Fig to come here with code**\n\nThe repulsive centrifugal piece dominates at large $r$ and the attractive\nCoulomb piece wins out at small $r$. The circular orbit is then at a\nmaximum of the effective potential and the orbits are unstable. It is\nthe clear that for potentials that fall as $r^n$, that one must have\n$n>-2$ for the orbits to be stable.\n\n\nConsider a potential $U(r)=\\beta r$. For a particle of mass $m$ with\nangular momentum $L$, find the angular frequency of a circular\norbit. Then find the angular frequency for small radial perturbations.\n\n\nFor the circular orbit you search for the position $r_{\\rm min}$ where the effective potential is minimized,\n\n$$\n\\begin{eqnarray*}\n\\partial_r\\left\\{\\beta r+\\frac{L^2}{2mr^2}\\right\\}&=&0,\\\\\n\\beta&=&\\frac{L^2}{mr_{\\rm min}^3},\\\\\nr_{\\rm min}&=&\\left(\\frac{L^2}{\\beta m}\\right)^{1/3},\\\\\n\\dot{\\theta}&=&\\frac{L}{mr_{\\rm min}^2}=\\frac{\\beta^{2/3}}{(mL)^{1/3}}\n\\end{eqnarray*}\n$$\n\nNow, we can find the angular frequency of small perturbations about the circular orbit. To do this we find the effective spring constant for the effective potential,\n\n$$\n\\begin{eqnarray*}\nk_{\\rm eff}&=&\\partial_r^2 \\left.U_{\\rm eff}\\right|_{r_{\\rm min}}\\\\\n&=&\\frac{3L^2}{mr_{\\rm min}^4},\\\\\n\\omega&=&\\sqrt{\\frac{k_{\\rm eff}}{m}}\\\\\n&=&\\frac{\\beta^{2/3}}{(mL)^{1/3}}\\sqrt{3}.\n\\end{eqnarray*}\n$$\n\nIf the two frequencies, $\\dot{\\theta}$ and $\\omega$, differ by an\ninteger factor, the orbit's trajectory will repeat itself each time\naround. This is the case for the inverse-square force,\n$\\omega=\\dot{\\theta}$, and for the harmonic oscillator,\n$\\omega=2\\dot{\\theta}$. In this case, $\\omega=\\sqrt{3}\\dot{\\theta}$,\nand the angles at which the maxima and minima occur change with each\norbit.\n\n\n### Code example with gravitional force\n\nThe code example here is meant to illustrate how we can make a plot of the final orbit. We solve the equations in polar coordinates (the example here uses the minimum of the potential as initial value) and then we transform back to cartesian coordinates and plot $x$ versus $y$. We see that we get a perfect circle when we place ourselves at the minimum of the potential energy, as expected.\n\n\n```\n\n# Simple Gravitational Force -alpha/r\n \nDeltaT = 0.01\n#set up arrays \ntfinal = 8.0\nn = ceil(tfinal/DeltaT)\n# set up arrays for t, v and r\nt = np.zeros(n)\nv = np.zeros(n)\nr = np.zeros(n)\nphi = np.zeros(n)\nx = np.zeros(n)\ny = np.zeros(n)\n# Constants of the model, setting all variables to one for simplicity\nalpha = 1.0\nAngMom = 1.0 # The angular momentum\nm = 1.0 # scale mass to one\nc1 = AngMom*AngMom/(m*m)\nc2 = AngMom*AngMom/m\nrmin = (AngMom*AngMom/m/alpha)\n# Initial conditions, place yourself at the potential min\nr0 = rmin\nv0 = 0.0 # starts at rest\nr[0] = r0\nv[0] = v0\nphi[0] = 0.0\n# Start integrating using the Velocity-Verlet method\nfor i in range(n-1):\n # Set up acceleration\n a = -alpha/(r[i]**2)+c1/(r[i]**3)\n # update velocity, time and position using the Velocity-Verlet method\n r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a\n anew = -alpha/(r[i+1]**2)+c1/(r[i+1]**3)\n v[i+1] = v[i] + 0.5*DeltaT*(a+anew)\n t[i+1] = t[i] + DeltaT\n phi[i+1] = t[i+1]*c2/(r0**2)\n# Find cartesian coordinates for easy plot \nx = r*np.cos(phi)\ny = r*np.sin(phi)\nfig, ax = plt.subplots(3,1)\nax[0].set_xlabel('time')\nax[0].set_ylabel('radius')\nax[0].plot(t,r)\nax[1].set_xlabel('time')\nax[1].set_ylabel('Angle $\\cos{\\phi}$')\nax[1].plot(t,np.cos(phi))\nax[2].set_ylabel('y')\nax[2].set_xlabel('x')\nax[2].plot(x,y)\n\nsave_fig(\"Phasespace\")\nplt.show()\n```\n\nTry to change the initial value for $r$ and see what kind of orbits you get.\nIn order to test different energies, it can be useful to look at the plot of the effective potential discussed above.\n\nHowever, for orbits different from a circle the above code would need modifications in order to allow us to display say an ellipse. For the latter, it is much easier to run our code in cartesian coordinates, as done here. In this code we test also energy conservation and see that it is conserved to numerical precision. The code here is a simple extension of the code we developed for homework 4.\n\n\n```\n# Common imports\nimport numpy as np\nimport pandas as pd\nfrom math import *\nimport matplotlib.pyplot as plt\n\nDeltaT = 0.01\n#set up arrays \ntfinal = 10.0\nn = ceil(tfinal/DeltaT)\n# set up arrays\nt = np.zeros(n)\nv = np.zeros((n,2))\nr = np.zeros((n,2))\nE = np.zeros(n)\n# Constants of the model\nm = 1.0 # mass, you can change these\nalpha = 1.0\n# Initial conditions as compact 2-dimensional arrays\nx0 = 0.5; y0= 0.\nr0 = np.array([x0,y0]) \nv0 = np.array([0.0,1.0])\nr[0] = r0\nv[0] = v0\nrabs = sqrt(sum(r[0]*r[0]))\nE[0] = 0.5*m*(v[0,0]**2+v[0,1]**2)-alpha/rabs\n# Start integrating using the Velocity-Verlet method\nfor i in range(n-1):\n # Set up the acceleration\n rabs = sqrt(sum(r[i]*r[i]))\n a = -alpha*r[i]/(rabs**3)\n # update velocity, time and position using the Velocity-Verlet method\n r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a\n rabs = sqrt(sum(r[i+1]*r[i+1]))\n anew = -alpha*r[i+1]/(rabs**3)\n v[i+1] = v[i] + 0.5*DeltaT*(a+anew)\n E[i+1] = 0.5*m*(v[i+1,0]**2+v[i+1,1]**2)-alpha/rabs\n t[i+1] = t[i] + DeltaT\n# Plot position as function of time\nfig, ax = plt.subplots(3,1)\nax[0].set_ylabel('y')\nax[0].set_xlabel('x')\nax[0].plot(r[:,0],r[:,1])\nax[1].set_xlabel('time')\nax[1].set_ylabel('y position')\nax[1].plot(t,r[:,0])\nax[2].set_xlabel('time')\nax[2].set_ylabel('y position')\nax[2].plot(t,r[:,1])\n\nfig.tight_layout()\nsave_fig(\"2DimGravity\")\nplt.show()\nprint(E)\n```\n\n## Scattering and Cross Sections\n\nScattering experiments don't measure entire trajectories. For elastic\ncollisions, they measure the distribution of final scattering angles\nat best. Most experiments use targets thin enough so that the number\nof scatterings is typically zero or one. The cross section, $\\sigma$,\ndescribes the cross-sectional area for particles to scatter with an\nindividual target atom or nucleus. Cross section measurements form the\nbasis for MANY fields of physics. BThe cross section, and the\ndifferential cross section, encapsulates everything measurable for a\ncollision where all that is measured is the final state, e.g. the\noutgoing particle had momentum $\\boldsymbol{p}_f$. y studying cross sections,\none can infer information about the potential interaction between the\ntwo particles. Inferring, or constraining, the potential from the\ncross section is a classic {\\it inverse} problem. Collisions are\neither elastic or inelastic. Elastic collisions are those for which\nthe two bodies are in the same internal state before and after the\ncollision. If the collision excites one of the participants into a\nhigher state, or transforms the particles into different species, or\ncreates additional particles, the collision is inelastic. Here, we\nconsider only elastic collisions.\n\nFor Coulomb forces, the cross section is infinite because the range of\nthe Coulomb force is infinite, but for interactions such as the strong\ninteraction in nuclear or particle physics, there is no long-range\nforce and cross-sections are finite. Even for Coulomb forces, the part\nof the cross section that corresponds to a specific scattering angle,\n$d\\sigma/d\\Omega$, which is a function of the scattering angle\n$\\theta_s$ is still finite.\n\nIf a particle travels through a thin target, the chance the particle\nscatters is $P_{\\rm scatt}=\\sigma dN/dA$, where $dN/dA$ is the number\nof scattering centers per area the particle encounters. If the density\nof the target is $\\rho$ particles per volume, and if the thickness of\nthe target is $t$, the areal density (number of target scatterers per\narea) is $dN/dA=\\rho t$. Because one wishes to quantify the collisions\nindependently of the target, experimentalists measure scattering\nprobabilities, then divide by the areal density to obtain\ncross-sections,\n\n$$\n\\begin{eqnarray}\n\\sigma=\\frac{P_{\\rm scatt}}{dN/dA}.\n\\end{eqnarray}\n$$\n\nInstead of merely stating that a particle collided, one can measure\nthe probability the particle scattered by a given angle. The\nscattering angle $\\theta_s$ is defined so that at zero the particle is\nunscattered and at $\\theta_s=\\pi$ the particle is scattered directly\nbackward. Scattering angles are often described in the center-of-mass\nframe, but that is a detail we will neglect for this first discussion,\nwhere we will consider the scattering of particles moving classically\nunder the influence of fixed potentials $U(\\boldsymbol{r})$. Because the\ndistribution of scattering angles can be measured, one expresses the\ndifferential cross section,\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{d^2\\sigma}{d\\cos\\theta_s~d\\phi}.\n\\label{_auto77} \\tag{106}\n\\end{equation}\n$$\n\nUsually, the literature expresses differential cross sections as\n\n\n
\n\n$$\n\\begin{equation}\nd\\sigma/d\\Omega=\\frac{d\\sigma}{d\\cos\\theta d\\phi}=\\frac{1}{2\\pi}\\frac{d\\sigma}{d\\cos\\theta},\n\\label{_auto78} \\tag{107}\n\\end{equation}\n$$\n\nwhere the last equivalency is true when the scattering does not depend\non the azimuthal angle $\\phi$, as is the case for spherically\nsymmetric potentials.\n\nThe differential solid angle $d\\Omega$ can be thought of as the area\nsubtended by a measurement, $dA_d$, divided by $r^2$, where $r$ is the\ndistance to the detector,\n\n$$\n\\begin{eqnarray}\ndA_d=r^2 d\\Omega.\n\\end{eqnarray}\n$$\n\nWith this definition $d\\sigma/d\\Omega$ is independent of the distance\nfrom which one places the detector, or the size of the detector (as\nlong as it is small).\n\nDifferential scattering cross sections are calculated by assuming a\nrandom distribution of impact parameters $b$. These represent the\ndistance in the $xy$ plane for particles moving in the $z$ direction\nrelative to the scattering center. An impact parameter $b=0$ refers to\nbeing aimed directly at the target's center. The impact parameter\ndescribes the transverse distance from the $z=0$ axis for the\ntrajectory when it is still far away from the scattering center and\nhas not yet passed it. The differential cross section can be expressed\nin terms of the impact parameter,\n\n\n
\n\n$$\n\\begin{equation}\nd\\sigma=2\\pi bdb,\n\\label{_auto79} \\tag{108}\n\\end{equation}\n$$\n\nwhich is the area of a thin ring of radius $b$ and thickness $db$. In\nclassical physics, one can calculate the trajectory given the incoming\nkinetic energy $E$ and the impact parameter if one knows the mass and\npotential. From the trajectory, one then finds the scattering angle\n$\\theta_s(b)$. The differential cross section is then\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{d\\sigma}{d\\Omega}=\\frac{1}{2\\pi}\\frac{d\\sigma}{d\\cos\\theta_s}=b\\frac{db}{d\\cos\\theta_s}=\\frac{b}{(d/db)\\cos\\theta_s(b)}.\n\\label{_auto80} \\tag{109}\n\\end{equation}\n$$\n\nTypically, one would calculate $\\cos\\theta_s$ and $(d/db)\\cos\\theta_s$\nas functions of $b$. This is sufficient to plot the differential cross\nsection as a function of $\\theta_s$.\n\nThe total cross section is\n\n\n
\n\n$$\n\\begin{equation}\n\\sigma_{\\rm tot}=\\int d\\Omega\\frac{d\\sigma}{d\\Omega}=2\\pi\\int d\\cos\\theta_s~\\frac{d\\sigma}{d\\Omega}. \n\\label{_auto81} \\tag{110}\n\\end{equation}\n$$\n\nEven if the total cross section is infinite, e.g. Coulomb forces, one\ncan still have a finite differential cross section as we will see\nlater on.\n\n\nAn asteroid of mass $m$ and kinetic energy $E$ approaches a planet of\nradius $R$ and mass $M$. What is the cross section for the asteroid to\nimpact the planet?\n\n### Solution\n\nCalculate the maximum impact parameter, $b_{\\rm max}$, for which the asteroid will hit the planet. The total cross section for impact is $\\sigma_{\\rm impact}=\\pi b_{\\rm max}^2$. The maximum cross-section can be found with the help of angular momentum conservation. The asteroid's incoming momentum is $p_0=\\sqrt{2mE}$ and the angular momentum is $L=p_0b$. If the asteroid just grazes the planet, it is moving with zero radial kinetic energy at impact. Combining energy and angular momentum conservation and having $p_f$ refer to the momentum of the asteroid at a distance $R$,\n\n$$\n\\begin{eqnarray*}\n\\frac{p_f^2}{2m}-\\frac{GMm}{R}&=&E,\\\\\np_fR&=&p_0b_{\\rm max},\n\\end{eqnarray*}\n$$\n\nallows one to solve for $b_{\\rm max}$,\n\n$$\n\\begin{eqnarray*}\nb_{\\rm max}&=&R\\frac{p_f}{p_0}\\\\\n&=&R\\frac{\\sqrt{2m(E+GMm/R)}}{\\sqrt{2mE}}\\\\\n\\sigma_{\\rm impact}&=&\\pi R^2\\frac{E+GMm/R}{E}.\n\\end{eqnarray*}\n$$\n\n## Rutherford Scattering\n\nThis refers to the calculation of $d\\sigma/d\\Omega$ due to an inverse\nsquare force, $F_{12}=\\pm\\alpha/r^2$ for repulsive/attractive\ninteraction. Rutherford compared the scattering of $\\alpha$ particles\n($^4$He nuclei) off of a nucleus and found the scattering angle at\nwhich the formula began to fail. This corresponded to the impact\nparameter for which the trajectories would strike the nucleus. This\nprovided the first measure of the size of the atomic nucleus. At the\ntime, the distribution of the positive charge (the protons) was\nconsidered to be just as spread out amongst the atomic volume as the\nelectrons. After Rutherford's experiment, it was clear that the radius\nof the nucleus tended to be roughly 4 orders of magnitude smaller than\nthat of the atom, which is less than the size of a football relative\nto Spartan Stadium.\n\n\n\nThe incoming and outgoing angles of the trajectory are at\n$\\pm\\theta'$. They are related to the scattering angle by\n$2\\theta'=\\pi+\\theta_s$.\n\nIn order to calculate differential cross section, we must find how the\nimpact parameter is related to the scattering angle. This requires\nanalysis of the trajectory. We consider our previous expression for\nthe trajectory where we derived the elliptic form for the trajectory,\nEq. ([105](#eq:Ctrajectory)). For that case we considered an attractive\nforce with the particle's energy being negative, i.e. it was\nbound. However, the same form will work for positive energy, and\nrepulsive forces can be considered by simple flipping the sign of\n$\\alpha$. For positive energies, the trajectories will be hyperbolas,\nrather than ellipses, with the asymptotes of the trajectories\nrepresenting the directions of the incoming and outgoing\ntracks. Rewriting Eq. ([105](#eq:Ctrajectory)),\n\n\n
\n\n$$\n\\begin{equation}\\label{eq:ruthtraj} \\tag{111}\nr=\\frac{1}{\\frac{m\\alpha}{L^2}+A\\cos\\theta}.\n\\end{equation}\n$$\n\nOnce $A$ is large enough, which will happen when the energy is\npositive, the denominator will become negative for a range of\n$\\theta$. This is because the scattered particle will never reach\ncertain angles. The asymptotic angles $\\theta'$ are those for which\nthe denominator goes to zero,\n\n\n
\n\n$$\n\\begin{equation}\n\\cos\\theta'=-\\frac{m\\alpha}{AL^2}.\n\\label{_auto82} \\tag{112}\n\\end{equation}\n$$\n\nThe trajectory's point of closest approach is at $\\theta=0$ and the\ntwo angles $\\theta'$, which have this value of $\\cos\\theta'$, are the\nangles of the incoming and outgoing particles. From\nFig (**to come**), one can see that the scattering angle\n$\\theta_s$ is given by,\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:sthetover2} \\tag{113}\n2\\theta'-\\pi&=&\\theta_s,~~~\\theta'=\\frac{\\pi}{2}+\\frac{\\theta_s}{2},\\\\\n\\nonumber\n\\sin(\\theta_s/2)&=&-\\cos\\theta'\\\\\n\\nonumber\n&=&\\frac{m\\alpha}{AL^2}.\n\\end{eqnarray}\n$$\n\nNow that we have $\\theta_s$ in terms of $m,\\alpha,L$ and $A$, we wish\nto re-express $L$ and $A$ in terms of the impact parameter $b$ and the\nenergy $E$. This will set us up to calculate the differential cross\nsection, which requires knowing $db/d\\theta_s$. It is easy to write\nthe angular momentum as\n\n\n
\n\n$$\n\\begin{equation}\nL^2=p_0^2b^2=2mEb^2.\n\\label{_auto83} \\tag{114}\n\\end{equation}\n$$\n\nFinding $A$ is more complicated. To accomplish this we realize that\nthe point of closest approach occurs at $\\theta=0$, so from\nEq. ([111](#eq:ruthtraj))\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:rminofA} \\tag{115}\n\\frac{1}{r_{\\rm min}}&=&\\frac{m\\alpha}{L^2}+A,\\\\\n\\nonumber\nA&=&\\frac{1}{r_{\\rm min}}-\\frac{m\\alpha}{L^2}.\n\\end{eqnarray}\n$$\n\nNext, $r_{\\rm min}$ can be found in terms of the energy because at the\npoint of closest approach the kinetic energy is due purely to the\nmotion perpendicular to $\\hat{r}$ and\n\n\n
\n\n$$\n\\begin{equation}\nE=-\\frac{\\alpha}{r_{\\rm min}}+\\frac{L^2}{2mr_{\\rm min}^2}.\n\\label{_auto84} \\tag{116}\n\\end{equation}\n$$\n\nOne can solve the quadratic equation for $1/r_{\\rm min}$,\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{1}{r_{\\rm min}}=\\frac{m\\alpha}{L^2}+\\sqrt{(m\\alpha/L^2)^2+2mE/L^2}.\n\\label{_auto85} \\tag{117}\n\\end{equation}\n$$\n\nWe can plug the expression for $r_{\\rm min}$ into the expression for $A$, Eq. ([115](#eq:rminofA)),\n\n\n
\n\n$$\n\\begin{equation}\nA=\\sqrt{(m\\alpha/L^2)^2+2mE/L^2}=\\sqrt{(\\alpha^2/(4E^2b^4)+1/b^2}\n\\label{_auto86} \\tag{118}\n\\end{equation}\n$$\n\nFinally, we insert the expression for $A$ into that for the scattering angle, Eq. ([113](#eq:sthetover2)),\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:scattangle} \\tag{119}\n\\sin(\\theta_s/2)&=&\\frac{m\\alpha}{AL^2}\\\\\n\\nonumber\n&=&\\frac{a}{\\sqrt{a^2+b^2}}, ~~a\\equiv \\frac{\\alpha}{2E}\n\\end{eqnarray}\n$$\n\nThe differential cross section can now be found by differentiating the\nexpression for $\\theta_s$ with $b$,\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:rutherford} \\tag{120}\n\\frac{1}{2}\\cos(\\theta_s/2)d\\theta_s&=&\\frac{ab~db}{(a^2+b^2)^{3/2}}=\\frac{bdb}{a^2}\\sin^3(\\theta_s/2),\\\\\n\\nonumber\nd\\sigma&=&2\\pi bdb=\\frac{\\pi a^2}{\\sin^3(\\theta_s/2)}\\cos(\\theta_s/2)d\\theta_s\\\\\n\\nonumber\n&=&\\frac{\\pi a^2}{2\\sin^4(\\theta_s/2)}\\sin\\theta_s d\\theta_s\\\\\n\\nonumber\n\\frac{d\\sigma}{d\\cos\\theta_s}&=&\\frac{\\pi a^2}{2\\sin^4(\\theta_s/2)},\\\\\n\\nonumber\n\\frac{d\\sigma}{d\\Omega}&=&\\frac{a^2}{4\\sin^4(\\theta_s/2)}.\n\\end{eqnarray}\n$$\n\nwhere $a= \\alpha/2E$. This the Rutherford formula for the differential\ncross section. It diverges as $\\theta_s\\rightarrow 0$ because\nscatterings with arbitrarily large impact parameters still scatter to\narbitrarily small scattering angles. The expression for\n$d\\sigma/d\\Omega$ is the same whether the interaction is positive or\nnegative.\n\n\nConsider a particle of mass $m$ and charge $z$ with kinetic energy $E$\n(Let it be the center-of-mass energy) incident on a heavy nucleus of\nmass $M$ and charge $Z$ and radius $R$. Find the angle at which the\nRutherford scattering formula breaks down.\n\n### Solution\n\nLet $\\alpha=Zze^2/(4\\pi\\epsilon_0)$. The scattering angle in Eq. ([119](#eq:scattangle)) is\n\n$$\n\\sin(\\theta_s/2)=\\frac{a}{\\sqrt{a^2+b^2}}, ~~a\\equiv \\frac{\\alpha}{2E}.\n$$\n\nThe impact parameter $b$ for which the point of closest approach\nequals $R$ can be found by using angular momentum conservation,\n\n$$\n\\begin{eqnarray*}\np_0b&=&b\\sqrt{2mE}=Rp_f=R\\sqrt{2m(E-\\alpha/R)},\\\\\nb&=&R\\frac{\\sqrt{2m(E-\\alpha/R)}}{\\sqrt{2mE}}\\\\\n&=&R\\sqrt{1-\\frac{\\alpha}{ER}}.\n\\end{eqnarray*}\n$$\n\nPutting these together\n\n$$\n\\theta_s=2\\sin^{-1}\\left\\{\n\\frac{a}{\\sqrt{a^2+R^2(1-\\alpha/(RE))}}\n\\right\\},~~~a=\\frac{\\alpha}{2E}.\n$$\n\nIt was from this departure of the experimentally measured\n$d\\sigma/d\\Omega$ from the Rutherford formula that allowed Rutherford\nto infer the radius of the gold nucleus, $R$.\n\n\n\nJust like electrodynamics, one can define \"fields\", which for a small\nadditional mass $m$ are the force per mass and the additional\npotential energy per mass. The {\\it gravitational field} related to\nthe force has dimensions of force per mass, or acceleration, and can\nbe labeled $\\boldsymbol{g}(\\boldsymbol{r})$. The potential energy per mass has\ndimensions of energy per mass. This is analogous to the\nelectromagnetic potential, which is the potential energy per charge,\nand the electric field which is the force per charge.\n\nBecause the field $\\boldsymbol{g}$ obeys the same inverse square law for a\npoint mass as the electric field does for a point charge, the\ngravitational field also satisfies a version of Gauss's law,\n\n\n
\n\n$$\n\\begin{equation}\n\\label{eq:GravGauss} \\tag{121}\n\\oint d\\boldsymbol{A}\\cdot\\boldsymbol{g}=-4\\pi GM_{\\rm inside}.\n\\end{equation}\n$$\n\nHere, $M_{\\rm inside}$ is the net mass inside a closed area.\n\nGauss's law can be understood by considering a nozzle that sprays\npaint in all directions uniformly from a point source. Let $B$ be the\nnumber of gallons per minute of paint leaving the nozzle. If the\nnozzle is at the center of a sphere of radius $r$, the paint per\nsquare meter per minute that is deposited on some part of the sphere\nis\n\n$$\n\\begin{eqnarray}\nF(r)&=&\\frac{B}{4\\pi r^2}.\n\\end{eqnarray}\n$$\n\nNow, let $F$ also be assigned a direction, so that it becomes a vector\npointing along the direction of the flying paint. For any surface that\nsurrounds the nozzle, not necessarily a sphere, one can state that\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:paint} \\tag{122}\n\\oint \\boldsymbol{dA}\\cdot\\boldsymbol{F}&=&B,\n\\end{eqnarray}\n$$\n\nregardless of the shape of the surface. This follows because the rate\nat which paint is deposited on the surface should equal the rate at\nwhich it leaves the nozzle. The dot product ensures that only the\ncomponent of $\\boldsymbol{F}$ into the surface contributes to the deposition\nof paint. Similarly, if $\\boldsymbol{F}$ is any radial inverse-square forces,\nthat falls as $B/(4\\pi r^2)$, then one can apply\nEq. ([122](#eq:paint)). For gravitational fields, $B/(4\\pi)$ is replaced\nby $GM$, and one quickly \"derives\" Gauss's law for gravity,\nEq. ([121](#eq:GravGauss)).\n\n\nConsider Earth to have its mass $M$ uniformly distributed in a sphere\nof radius $R$. Find the magnitude of the gravitational acceleration as\na function of the radius $r$ in terms of the acceleration of gravity\nat the surface $g(R)$. Assume $r\n
\n\n$$\n\\begin{equation}\nF=-\\frac{GM\\delta m}{D^2}+2\\frac{GM\\delta m}{D^3}\\Delta D+\\cdots\n\\label{_auto87} \\tag{123}\n\\end{equation}\n$$\n\nIf the $z$ direction points toward the large object, $\\Delta D$ can be\nreferred to as $z$. In the accelerating frame of an observer at the\ncenter of the planet,\n\n\n
\n\n$$\n\\begin{equation}\n\\delta m\\frac{d^2 z}{dt^2}=F-\\delta ma'+{\\rm other~forces~acting~on~} \\delta m,\n\\label{_auto88} \\tag{124}\n\\end{equation}\n$$\n\nwhere $a'$ is the acceleration of the observer. Because $\\delta ma'$\nequals the gravitational force on $\\delta m$ if it were located at the\nplanet's center, one can write\n\n\n
\n\n$$\n\\begin{equation}\nm\\frac{d^2z}{dt^2}=2\\frac{GM\\delta m}{D^3}z+{\\rm other~forces~acting~on~}\\delta m.\n\\label{_auto89} \\tag{125}\n\\end{equation}\n$$\n\nHere the other forces could represent the forces acting on $\\delta m$\nfrom the spherical planet such as the gravitational force or the\ncontact force with the surface. If $\\theta$ is the angle w.r.t. the\n$z$ axis, the effective force acting on $\\delta m$ is\n\n\n
\n\n$$\n\\begin{equation}\nF_{\\rm eff}\\approx 2\\frac{GM\\delta m}{D^3}r\\cos\\theta\\hat{z}+{\\rm other~forces~acting~on~}\\delta m.\n\\label{_auto90} \\tag{126}\n\\end{equation}\n$$\n\nThis first force is the \"tidal\" force. It pulls objects outward from the center of the object. If the object were covered with water, it would distort the objects shape so that the shape would be elliptical, stretched out along the axis pointing toward the large mass $M$. The force is always along (either parallel or antiparallel to) the $\\hat{z}$ direction.\n\n\nConsider the Earth to be a sphere of radius $R$ covered with water,\nwith the gravitational acceleration at the surface noted by $g$. Now\nassume that a distant body provides an additional constant\ngravitational acceleration $\\boldsymbol{a}$ pointed along the $z$ axis. Find\nthe distortion of the radius as a function of $\\theta$. Ignore\nplanetary rotation and assume $a<\n
\n\n$$\n\\begin{equation}\n\\nabla f\\cdot\\boldsymbol{\\epsilon}=0,\n\\label{_auto91} \\tag{127}\n\\end{equation}\n$$\n\nfor any infinitesimal vector $\\boldsymbol{\\epsilon}$ if $\\boldsymbol{\\epsilon}$\nsatisfies the condition\n\n\n
\n\n$$\n\\begin{equation}\n\\delta C=\\nabla C\\cdot\\boldsymbol{\\epsilon}=0.\n\\label{_auto92} \\tag{128}\n\\end{equation}\n$$\n\nThat is to say if I take a small step in a direction that doesn't\nchange the constraint, then $f$ must not change if it is an\nextrema. Not changing the constraint implies the step is orthogonal to\n$\\nabla C$. As there are $n$ dimensions of $x$, the vector $\\nabla C$\ndefines one direction, and $\\boldsymbol{\\epsilon}$ can be in any of the $n-1$\ndirections orthogonal to $\\nabla C$. If $\\nabla f\\cdot\\boldsymbol{\\epsilon}=0$\nfor ANY of the $n-1$ directions of $\\boldsymbol{\\epsilon}$ orthogonal to\n$\\nabla C$, then\n\n\n
\n\n$$\n\\begin{equation}\n\\nabla f ~||~ \\nabla C.\n\\label{_auto93} \\tag{129}\n\\end{equation}\n$$\n\nBecause the two vectors are parallel you can say there must exist some\nconstant $\\lambda$ such that\n\n\n
\n\n$$\n\\begin{equation}\n\\nabla(f-\\lambda C)=0.\n\\label{_auto94} \\tag{130}\n\\end{equation}\n$$\n\nHere, $\\lambda$ is known as a Lagrange multiplier. Satisfying\nthis equation is a necessary, but not a sufficient\ncondition. One could add a constant to the constraint and the gradient\nwould not change. One must find the correct value of $\\lambda$ that\nsatisfies the constraint $C=0$, rather than $C=$ some other\nconstant. The strategy is then to solve\nthw above equation then adjust $\\lambda$ until one\nfinds the $x_1\\cdots x_n$ that gives $C(x_1\\cdots x_n)=0$.\n\nThe method of Lagrange multipliers is counter-intuitive to one's\nintuition to use the constraint to reduce the dimensionality of the\nproblem. Normally, minimizing a function of $n$ variables, leads to\n$n$ equations and $n$ unknowns. A constraint could be used, by\nsubstitution, to replace the $n$ variables with $n-1$\nvariables. Instead, we add an unknown parameter, $\\lambda$, and change\nthe equation to $n+1$ equations with $n+1$ unknowns, with the extra\nunknown being the Lagrange multiplier $\\lambda$. Often, it is rather\neasy to solve for $x_1\\cdots x_n$. Then one is left with the usually\ndifficult problem of finding $\\lambda$, often requiring the solution\nof a transcendental equation.\n\nLet us try to formalize this. We consider a function of three independent variables $f(x,y,z)$ . For\nthe function $f$ to be an extreme we have\n\n$$\ndf=0.\n$$\n\nA necessary and sufficient condition is\n\n$$\n\\frac{\\partial f}{\\partial x} =\\frac{\\partial f}{\\partial y}=\\frac{\\partial f}{\\partial z}=0,\n$$\n\ndue to\n\n$$\ndf = \\frac{\\partial f}{\\partial x}dx+\\frac{\\partial f}{\\partial y}dy+\\frac{\\partial f}{\\partial z}dz.\n$$\n\nIn physical problems the variables $x,y,z$ are often subject to constraints (in our case $q$ and the orthogonality constraint)\nso that they are no longer all independent. It is possible at least in principle to use each constraint to eliminate one variable\nand to proceed with a new and smaller set of independent varables.\n\nThe use of so-called Lagrangian multipliers is an alternative technique when the elimination of\nof variables is incovenient or undesirable. Assume that we have an equation of constraint on the variables $x,y,z$\n\n$$\n\\phi(x,y,z) = 0,\n$$\n\nresulting in\n\n$$\nd\\phi = \\frac{\\partial \\phi}{\\partial x}dx+\\frac{\\partial \\phi}{\\partial y}dy+\\frac{\\partial \\phi}{\\partial z}dz =0.\n$$\n\nNow we cannot set anymore\n\n$$\n\\frac{\\partial f}{\\partial x} =\\frac{\\partial f}{\\partial y}=\\frac{\\partial f}{\\partial z}=0,\n$$\n\nif $df=0$ is wanted\nbecause there are now only two independent variables! Assume $x$ and $y$ are the independent variables.\nThen $dz$ is no longer arbitrary.\n\n\n\nHowever, we can add to\n\n$$\ndf = \\frac{\\partial f}{\\partial x}dx+\\frac{\\partial f}{\\partial y}dy+\\frac{\\partial f}{\\partial z}dz,\n$$\n\na multiplum of $d\\phi$, viz. $\\lambda d\\phi$, resulting in\n\n$$\ndf+\\lambda d\\phi = (\\frac{\\partial f}{\\partial z}+\\lambda\\frac{\\partial \\phi}{\\partial x})dx+(\\frac{\\partial f}{\\partial y}+\\lambda\\frac{\\partial \\phi}{\\partial y})dy+(\\frac{\\partial f}{\\partial z}+\\lambda\\frac{\\partial \\phi}{\\partial z})dz =0.\n$$\n\nOur multiplier is chosen so that\n\n$$\n\\frac{\\partial f}{\\partial z}+\\lambda\\frac{\\partial \\phi}{\\partial z} =0.\n$$\n\nHowever, we took $dx$ and $dy$ as to be arbitrary and thus we must have\n\n$$\n\\frac{\\partial f}{\\partial x}+\\lambda\\frac{\\partial \\phi}{\\partial x} =0,\n$$\n\nand\n\n$$\n\\frac{\\partial f}{\\partial y}+\\lambda\\frac{\\partial \\phi}{\\partial y} =0.\n$$\n\nWhen all these equations are satisfied, $df=0$. We have four\nunknowns, $x,y,z$ and $\\lambda$. Actually we want only $x,y,z$,\n$\\lambda$ need not to be determined, it is therefore often called\nLagrange's undetermined multiplier. If we have a set of constraints\n$\\phi_k$ we have the equations\n\n$$\n\\frac{\\partial f}{\\partial x_i}+\\sum_k\\lambda_k\\frac{\\partial \\phi_k}{\\partial x_i} =0.\n$$\n\n### Example: brachiostone\n\nConsider a particle constrained to move along a path (like a bead\nmoving without friction on a wire) and you need to design a path from\n$x=y=0$ to some final point $x_f,y_f$. Assume there is a constant\nforce in the $x$ direction, $F_x=mg$. Design the path so that the time\nthe bead travels is a minimum.\n\n\nThe net time is\n\n$$\nT=\\int \\frac{d\\ell}{v}=\\int_0^{x_f} dx~\\frac{\\sqrt{1+y'^2}}{\\sqrt{2gx}}={\\rm minimum}.\n$$\n\nHere we made use of the fact that $d\\ell=\\sqrt{dx^2+dy^2}$ and that\nthe velocity is determined by $KE=mv^2/2=mgx$. The Euler equations can\nbe applied if you first define the function as\n\n$$\n\\begin{eqnarray*}\nf(y,y';x)&=&\\frac{\\sqrt{1+y'^2}}{\\sqrt{x}}.\n\\end{eqnarray*}\n$$\n\nThe equations are then\n\n$$\n\\begin{eqnarray*}\n\\frac{d}{dx}\\frac{\\partial f}{\\partial y'}&=&0.\n\\end{eqnarray*}\n$$\n\nThe simplification ensued from $f$ not having any dependence on $y$. This yields the differential equation\n\n$$\n\\begin{eqnarray}\n\\frac{y'}{x^{1/2}(1+y'^2)^{1/2}}&=&(2a)^{-1/2},\n\\end{eqnarray}\n$$\n\nbecause $\\partial f/\\partial y'$ must be a constant, which with some\nforesight we label $(2a)^{-1/2}$. One can now solve for $y'$,\n\n$$\n\\begin{eqnarray*}\n(y')^2&=&2ax(1+y'^2)\\\\\n\\nonumber\ny'&=&\\sqrt{\\frac{x}{2a-x}},\\\\\n\\nonumber\ny(t)&=&\\int_0^x dx'~\\frac{\\sqrt{x'}dx'}{\\sqrt{2a-x'}}=\\int_0^x dx'~\\frac{x'dx'}{\\sqrt{2ax'-x'^2}}\\\\\n\\nonumber\n&=&\\frac{1}{2}\\int_0^x\\frac{(2x'-2a)dx'}{(2ax'-x'^2)^{1/2}}+a\\int_0^x\\frac{dx'}{\\sqrt{2ax'-x'^2}}\\\\\n\\nonumber\n&=&\\frac{-1}{2}\\int_0^{2ax-x^2}\\frac{du}{\\sqrt{u}}+a\\int_0^x\\frac{dx'}{\\sqrt{a^2-(x'-a)^2}}\\\\\n&=&-\\sqrt{2ax-x^2}+a\\cos^{-1}(1-x/a).\n\\end{eqnarray*}\n$$\n\nThis turns out to be the equation for a {\\it cycloid} or a {\\it\nbrachiostone}. If you rolled a wheel of radius $a$ down the $y$ axis\nand followed a point on the rim, it would trace out a cycloid. Here,\nthe constant $a$ must be chosen to match the boundary condition,\n$y_2=y(x_2)$. You can see the textbook for more details, plus you get\na chance to work with cycloids in the exercises at the end of this\nchapter.\n\n\n\n\n### Maximizing a Function\n\nAs an example of using Lagrange multipliers for a standard\noptimization formula we attempt to maximize the following function,\n\n$$\nF(x_1\\cdots x_n)=-\\sum_{i=1}^n x_i\\ln(x_i),\n$$\n\nwith respect to the $n$ variables $x_i$. With no constraints, each\n$x_i$ would maximize the function for\n\n$$\n\\begin{eqnarray*}\n\\frac{d}{dx_j}~\\left[-\\sum_i x_i\\ln(x_i)\\right]&=&0\\\\\n-\\ln(x_j)-1&=&0,~~~~x_j=e^{-1}.\n\\end{eqnarray*}\n$$\n\nNow, we repeat the problem but with two constraints,\n\n$$\n\\sum_ix_i=1~,~~~~\\sum_ix_i\\epsilon_i=E.\n$$\n\nHere, $\\epsilon_i$ and $E$ are fixed constants. We go forward by\nfinding the extrema for\n\n$$\n\\begin{eqnarray*}\nG(x_1\\cdots x_n)&=&F-\\alpha\\sum_i x_i-\\beta\\sum_i\\epsilon_ix_i\n=\\sum_i \\left\\{-x_i\\ln(x_i)-\\alpha x_i-\\beta\\epsilon_ix_i\\right\\}.\n\\end{eqnarray*}\n$$\n\nThere are two Lagrange multipliers, $\\alpha$ and $\\beta$,\ncorresponding to the two constraints. One then solves for the extrema\n\n$$\n\\begin{eqnarray*}\n\\frac{d}{dx_j}G&=&0\\\\\n&=&-\\ln(x_j)-1-\\alpha-\\beta\\epsilon_j,\\\\\nx_j&=&\\exp\\left\\{-1-\\alpha-\\beta\\epsilon_j\\right\\}.\n\\end{eqnarray*}\n$$\n\nFor any given $\\alpha$ and $\\beta$ this provides a solution for\nconstraining $\\sum_i x_i$ and $\\sum_i\\epsilon_ix_i$ to some values,\njust not the values of unity and $E$ that you wish. One would then\nhave to search for the correct values by adjusting $\\alpha$ and\n$\\beta$ until the constraint are actually matched by solving a\ntranscendental equation. Although this can be complicated, it is\ncertainly less expensive than searching over all $N$ values of\n$x_i$. This particular example corresponds to maximizing the entropy\nfor a system, $S=-\\sum_i x_i\\ln(x_i)$, where $x_i$ is the probability\nof the system being in a particular discrete level $i$ that has energy\n$\\epsilon_i$. One wishes to maximize the entropy subject to the\nconstraints that the probabilities sum to unity and the average energy\nhas some given value. The result that $x_i\\sim e^{-\\beta\\epsilon_i}$\ndemonstrates the origin of the Boltzmann factor, with the inverse\ntemperature $\\beta=1/T$.\n\n\nLagrange multipliers also assist with the Euler-Lagrange equation. If\none breaks an interval $x_1\n
\n\n$$\n\\begin{equation}\nf\\left\\{y(t),y'(t),x\\right\\}\\rightarrow f\\left\\{y(t),y'(t),x\\right\\}-\\lambda C\\left\\{y(t),y'(t),x\\right\\}\n\\label{_auto95} \\tag{131}\n\\end{equation}\n$$\n\n### Example\n\nConsider a chain of length $L$ and mass per unit length $\\kappa$ that\nhangs from point $x=0,y=0$ to point $x_f,y_f$. The shape must minimize\nthe potential energy. Find general expressions for the shape in terms\nof three constants which must be chosen to match $y(0)=0, y(x_f)=y_f$\nand the fixed length. Equivalently, one finds the function $y(t)$ that\nprovides an extrema for the integral,\n\nOne must minimize\n\n$$\n\\int d\\ell~\\kappa gy-\\lambda\\int d\\ell=\n\\int_0^{x_f} dx~\\sqrt{1+y'^2}\\kappa gy-\\lambda \\int_0^{x_f} dx\\sqrt{1+y'^2}.\n$$\n\nHere $\\lambda$ is the Lagrange multiplier associated with constraining\nthe length of the chain. The constrained length $L$ appears nowhere in\nthe expression. Instead, one solves for form of the answer, then\nadjusts $\\lambda$ to give the correct length. For the purposes of the\nEuler-Lagrange minimization one considers the function\n\n$$\n\\begin{eqnarray}\nf(y,y';x)&=&\\kappa gy\\sqrt{1+y'^2}-\\lambda\\sqrt{1+y'^2}.\n\\end{eqnarray}\n$$\n\nBecause $\\lambda$ is an unknown constant and because minimizing a\nfunction multiplied by a constant is the same as minimizing the\nfunction, we can equivlently minimize the integral using the function\n\n$$\n\\begin{eqnarray}\n\\tilde{f}(y,y';x)&=&y\\sqrt{1+y'^2}-\\tilde{\\lambda}\\sqrt{1+y'^2},\\\\\n\\nonumber\n\\tilde{\\lambda}&\\equiv&\\frac{\\lambda}{\\kappa g}.\n\\end{eqnarray}\n$$\n\nThe Euler-Lagrange equations then become\n\n$$\n\\begin{eqnarray*}\n\\frac{d}{dx}\\left\\{\n\\frac{y'}{\\sqrt{1+y'^2}}y-\\tilde{\\lambda}\\frac{y'}{\\sqrt{1+y'^2}}\n\\right\\}&=&\\sqrt{1+y'^2}.\n\\end{eqnarray*}\n$$\n\nHere, we will guess at the form of the solution,\n\n$$\n\\begin{eqnarray*}\ny'&=&\\sinh[(x-x_0)/a],~~y=a\\cosh[(x-x_0)/a]+y_0.\n\\end{eqnarray*}\n$$\n\nPlugging into the Euler-Lagange equations,\n\n$$\n\\begin{eqnarray*}\n\\frac{d}{dx}\\left\\{(a\\cosh[(x-x_0)/a]+y_0)\\frac{\\sinh[(x-x_0)/a]}{\\cosh[(x-x_0)/a]}-\\tilde{\\lambda}\\frac{\\sinh[(x-x_0)/a]}{\\cosh[(x-x_0)/a]}\\right\\}&=&\\cosh[(x-x_0)/a],\\\\\n\\nonumber\n\\frac{d}{dx}\\left\\{(y_0-\\tilde{\\lambda})\\tanh[(x-x_0)/a]\\right\\}=0.\n\\end{eqnarray*}\n$$\n\nThis solution works if $y_0=\\tilde{\\lambda}$. So the general form of\nthe solution is\n\n$$\ny=\\tilde{\\lambda}+a\\cosh[(x-x_0)/a].\n$$\n\nOne must find $\\tilde{\\lambda}$, $x_0$ and $a$ to satisfy three\nconditions, $y(x=0)=0$, $y(x=x_f)=y_f$ and that the length is $L$. For\na hanging chain $a$ is positive. A solution with negative $a$ would\nrepresent a maximum of the potential energy. A remarkable property of\nthe solution is that once you define the length and the end-point\npositions $y_1$ and $y_2$, the solution does not depend on $\\kappa$ or\n$g$. Thus, the shape of the chain would be the same if you took it to\nthe moon. These solutions are known as [catenaries](http://en.wikipedia.org/wiki/Catenary}{http://en.wikipedia.org/wiki/Catenary).\n\n\n\n## Lagrangians\n\nLagrangians represent a powerful method for solving problems that\nwould be nearly impossible by direct application of Newton's third\nlaw, $\\boldsymbol{F}=m\\boldsymbol{a}$. The method works well for problems where a\nsystem is well described by a few \\textit{generalized coordinates}. A\ngeneralized coordinate might be the angle describing the position of a\npendulum. This one angle takes the place of using $x$ and $y$ to\ndescribe the position of the pendulum, then applying a clumsy\nconstraint.\n\nThe Lagrangian equations of motion can be derived from a principle of\nleast action, where the action $S$ is defined as\n\n\n
\n\n$$\n\\begin{equation}\nS=\\int dt~ L(q,\\dot{q},t),\n\\label{_auto96} \\tag{132}\n\\end{equation}\n$$\n\nwhere $q$ is some coordinate that describes the orientation of a\nsystem and the Lagrangian $L$ is defined as\n\n\n
\n\n$$\n\\begin{equation}\nL=T-U,\n\\label{_auto97} \\tag{133}\n\\end{equation}\n$$\n\nthe difference of the kinetic and potential energies. Minimizing the\naction through the Euler-Lagrange equations gives the Lagrangian\nequations of motion,\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{d}{dt}\\frac{\\partial L}{\\partial \\dot{q}}=\\frac{\\partial L}{\\partial q}.\n\\label{_auto98} \\tag{134}\n\\end{equation}\n$$\n\nWe begin with two simple examples, neither of which gains from the Lagrangian approach.\n\n\nConsider a particle of mass $m$ connected to a spring with stiffness $k$. Derive the Lagrangian equations of motion.\n\n$$\n\\begin{eqnarray*}\nL&=&\\frac{1}{2}m\\dot{x}^2-\\frac{1}{2}kx^2,\\\\\n\\frac{d}{dt}\\frac{\\partial L}{\\partial \\dot{x}}&=&\\frac{\\partial L}{\\partial x},\\\\\nm\\ddot{x}&=&-kx.\n\\end{eqnarray*}\n$$\n\nDerive the Lagrangian equations of motion for a pendulum of mass $m$\nand length $\\ell$.\n\n$$\n\\begin{eqnarray*}\nL&=&\\frac{m}{2}\\ell^2\\dot{\\theta}^2-mg\\ell(1-\\cos\\theta),\\\\\n\\frac{d}{dt}\\frac{\\partial L}{\\partial \\dot{\\theta}}&=&\\frac{\\partial L}{\\partial \\theta},\\\\\nm\\ell^2\\ddot{\\theta}&=&-mg\\ell\\sin\\theta,\\\\\n\\ddot{\\theta}&=&-\\frac{g}{\\ell}\\sin\\theta,\\\\\n\\ddot{\\theta}&\\approx&-\\frac{g}{\\ell}\\theta.\n\\end{eqnarray*}\n$$\n\n### Proving Lagrange's Equations of Motion from Newton's Laws\n\nLagrange's equations of motion can only be applied for the following conditions:\n\n\n\n* The potential energy is a function of the generalized coordinates $q_i$, but not of $\\dot{q}_i$.\n\n* The relation between the original coordinates $x,y,z\\cdots$ and the generalized coordinates does not depend on $\\dot{q}_i$, e.g. $x(q,t)$ not $x(q,\\dot{q},t)$.\n\n* Any constraints used to reduce the number of degrees of freedom are functions of $\\boldsymbol{q}$, but not of $\\dot{\\boldsymbol{q}}$.\n\n* The motion is not dissipative (no damping or friction).\n\nGoing forward with the proof, consider $x_i(q_1,q_2\\cdots,t)$ and look\nat the l.h.s. of Lagrange's equations of motion.\n\n$$\n\\begin{eqnarray}\n\\frac{\\partial T}{\\partial\\dot{q}_j}&=&\\sum_i\\frac{\\partial T}{\\partial\\dot{x}_i}\\frac{\\partial\\dot{x}_i}{\\partial\\dot{q_j}}\n+\\sum_i\\frac{\\partial T}{\\partial x_i}\\frac{\\partial x_i}{\\partial\\dot{q_j}}\\\\\n\\nonumber\n&=&\\sum_i m\\dot{x}_i\\frac{\\partial \\dot{x}_i}{\\partial\\dot{q_j}}\\\\\n\\nonumber\n&=&\\sum_i m\\dot{x}_i\\frac{(\\delta x_i/\\delta t)|_{{\\rm fixed~}q_{j'\\ne j}}}{\\delta q_j/\\delta t}\\\\\n\\nonumber\n&=&\\sum_im\\dot{x}_i\\frac{\\delta{x}_i|_{{\\rm fixed~}q_{j'\\ne j}}}{\\delta q_j}\\\\\n\\nonumber\n&=&\\sum_i m\\dot{x}_i\\frac{\\partial x_i}{\\partial q_j}.\n\\end{eqnarray}\n$$\n\nIn the first line we used the fact that $T$ does not depend on\n$x$. Continuing with taking the derivative of $U$,\n\n$$\n\\begin{eqnarray}\n-\\frac{\\partial U}{\\partial\\dot{q}_j}&=&-\\sum_i\\frac{\\partial U}{\\partial x_i}\\frac{\\partial x_i}{\\partial\\dot{q}_j}=0.\n\\end{eqnarray}\n$$\n\nIn the first line above we used the fact that $U$ does not depend on $\\dot{x}$ then we used the second condition that $x$ does not depend on $\\dot{q}$. Adding the two pieces together, then taking the derivative w.r.t. time,\n\n$$\n\\begin{eqnarray}\n\\nonumber\n\\frac{d}{dt}\\frac{\\partial}{\\partial\\dot{q}}(T-U)&=&\\sum_im\\ddot{x}_i\\frac{\\partial x_i}{\\partial q_j}\n+\\sum_i m\\dot{x}_i\\frac{\\partial\\dot{x}_i}{\\partial q_j}.\n\\end{eqnarray}\n$$\n\nNow, we consider the r.h.s. of Lagrange's equations. Because the\nkinetic energy depends only on $\\dot{x}$ and not $x$, and because the\npotential depends on $x$ but not $\\dot{x}$,\n\n$$\n\\begin{eqnarray}\n\\frac{\\partial}{\\partial q_j}(T-U)&=&\\sum_i\\frac{\\partial T}{\\partial\\dot{x}_i}\\frac{\\partial\\dot{x_i}}{\\partial q_j}\n-\\sum_i\\frac{\\partial U}{\\partial x_i}\\frac{\\partial x_i}{\\partial q_j}\\\\\n\\nonumber\n&=&\\sum_i m\\dot{x}_i\\frac{\\partial\\dot{x_i}}{\\partial q_j}\n-\\sum_i\\frac{\\partial U}{\\partial x_i}\\frac{\\partial x_i}{\\partial q_j}\n\\end{eqnarray}\n$$\n\nUsing the fact that $m\\ddot{x}_i=-(\\partial/\\partial x_i)U$, one can\nsee that the bottom expressions above are identical,\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{d}{dt}\\frac{\\partial}{\\partial\\dot{q}_i}(T-U)=\\frac{\\partial}{\\partial q_i}(T-U).\n\\label{_auto99} \\tag{135}\n\\end{equation}\n$$\n\n### Lagrangian Examples\n\nTwo examples are presented here. In the first, there are two\ngeneralized coordinates, but the two equations of motion can be\nreduced to one through conservation laws (angular momentum in this\ncase). In the second, there is a time-dependent constraint.\n\n\nConsider a cone of half angle $\\alpha$ standing on its tip at the\norigin. The surface of the cone is defined as\n\n$$\nr=\\sqrt{x^2+y^2}=z\\tan \\alpha.\n$$\n\nFind the equations of motion for a particle of mass $m$ moving along the surface under the influence of a constant gravitational force, $-mg\\hat{z}$. For generalized coordinates use the azimuthal angle $\\phi$ and $r$.\n\n\nThe kinetic energy is\n\n$$\n\\begin{eqnarray*}\nT&=&\\frac{1}{2}mr^2\\dot{\\theta}^2+\\frac{1}{2}m(\\dot{r}^2+\\dot{z}^2)\\\\\n&=&\\frac{1}{2}mr^2\\dot{\\theta}^2+\\frac{1}{2}m\\dot{r}^2\\left(1+\\cot^2\\alpha\\right)\\\\\n&=&\\frac{1}{2}mr^2\\dot{\\theta}^2+\\frac{1}{2}m\\dot{r}^2\\csc^2\\alpha.\n\\end{eqnarray*}\n$$\n\nThe potential energy is\n\n$$\nU=mgr\\cot\\alpha,\n$$\n\nso Lagrange's equations give\n\n$$\n\\begin{eqnarray*}\n\\frac{d}{dt}\\left(mr^2\\dot{\\theta}\\right)&=&0,\\\\\n\\frac{d}{dt}\\left(m\\csc^2\\alpha \\dot{r}\\right)&=&mr\\dot{\\theta}^2-mg\\cot\\alpha,\\\\\n\\ddot{r}&=&r\\dot{\\theta}^2\\sin^2\\alpha-g\\cos\\alpha\\sin\\alpha\n\\end{eqnarray*}\n$$\n\nThe first equation is a statement of the conservation of angular\nmomentum with $L=mr^2\\dot{\\theta}$, so the second equation can also be\nexpressed as\n\n$$\n\\ddot{r}=\\frac{L^2\\sin^2\\alpha}{m^2r^3}-g\\sin\\alpha\\cos\\alpha.\n$$\n\nA bead slides along a wire bent in the shape of a parabola,\n\n$$\nz=\\frac{1}{2}kr^2,~~r^2=x^2+y^2.\n$$\n\nAlso, the parabolic wire is rotating about the $z$ axis with angular\nvelocity $\\omega$. Derive the equations of motion. Are there any\nstable configurations?\n\n\nUsing the fact that\n\n$$\n\\dot{z}=\\dot{r}\\frac{\\partial z}{\\partial r}=kr\\dot{r},\n$$\n\nthe kinetic and potential energies are\n\n$$\n\\begin{eqnarray*}\nT&=&\\frac{1}{2}m\\left(\\dot{r}^2+\\dot{z}^2+r^2\\omega^2\\right)\\\\\n&=&\\frac{1}{2}m\\left(\\dot{r}^2+(kr\\dot{r})^2+r^2\\omega^2\\right),\\\\\nU&=&mgkr^2/2.\n\\end{eqnarray*}\n$$\n\nThe equations of motion are then\n\n$$\n\\begin{eqnarray*}\n\\frac{d}{dt}\\left\\{m\\dot{r}(1+k^2r^2)\\right\\}&=&-mgkr+mk^2\\dot{r}^2r+m\\omega^2r,\\\\\n\\ddot{r}&=&\\frac{-gkr+\\omega^2r-k^2\\dot{r}^2r}{1+k^2r^2}\n\\end{eqnarray*}\n$$\n\nFor a stable configuration, there needs to be a solution with\n$\\dot{r}=0$ and $\\ddot{r}=0$. This can only happen at $r=0$, and then\nfor the acceleration to be inward for small deviations of $r$ one\nneeds to have $gk>\\omega^2$. If $\\omega^2>gk$ the bead will move\noutward indefinitely.\n\n\n\n## Small Vibrations and Normal Modes\n\nTwo examples are provided for solving for normal modes. These are\nsolutions with multiple generalized coordinates, where the motion is\nthat of simple harmonic motion. However, the motion is only simple for\na particular set of coordinates $q_1$ and $q_2$,\n\n$$\n\\begin{eqnarray}\nq_1&=&A\\cos(\\omega_1 t),\\\\\n\\nonumber\nq_2&=&B\\cos(\\omega_2 t),\n\\end{eqnarray}\n$$\n\nwhile it is not necessarily simple in other coordinates. For example\nif $x=q_1+q_2$, and $y=q_1-q_2$, the $x$ and $y$ motions will contain\nmixtures of multiple frequencies. For many problems, or in the limit\nof small vibrations about a minimum, there is some coordinate system\nwhere the motion is simple. These are normal modes. Characterizing the\nnormal modes involves finding the frequencies, $\\omega_i$, and the\ncoordinate system where the motion is simple for each coordinate. This\ninvolves finding the direction, or the linear combination of $x_i$\nthat form the coordinates $q_i$ in which the motion is that of a\nsingle oscillator in each coordinate.\n\nFor a first example, we consider a system of springs, where we write\nthe Lagrangian, then find the normal modes. For the second example, a\ndouble pendulum is considered. In this case, one must first make a\nsmall angle expansion before finding the modes. In principle, problems\ncould have the same number of normal modes a degrees of freedom. For\nexample, a system of 7 particles moving in three dimensions has 21\ndegrees of freedom. However, some of the degrees of freedom do not\nhave oscillatory behavior. For example, for a rigid body in free\nspace, the angles describing the orientation evolve, but do not\noscillate. Also, the center-of-mass coordinates of a system of\nparticles isolated from outside particles moves at constant\nvelocity. One can also describe these as normal modes, but acknowledge\nthat their characteristic frequency is zero, as there are no restoring\nforces.\n\n\nConsider two springs, whose relaxed lengths are $\\ell$, connected to three masses as depicted in the figure here. Describe the two normal modes of the motion. We can write the Lagrangian as\n\n$$\n\\begin{eqnarray*}\n\\mathcal{L}&=&\\frac{m}{2}\\dot{x}_1^2+m\\dot{x}_2^2+\\frac{m}{2}\\dot{x}_3^2\n-\\frac{k}{2}(x_2-x_1-\\ell)^2-\\frac{k}{2}(x_3-x_2-\\ell)^2.\n\\end{eqnarray*}\n$$\n\nThere are three coordinates, thus there are three equations of motion,\n\n$$\n\\begin{eqnarray*}\nm\\ddot{x}_1&=&-k(x_1-x_2+\\ell)\\\\\n2m\\ddot{x}_2&=&-k(x_2-x_1-\\ell)-k(x_2-x_3+\\ell)\\\\\n&=&-k(2x_2-x_1-x_3)\\\\\nm\\ddot{x}_3&=&-k(x_3-x_2+\\ell).\n\\end{eqnarray*}\n$$\n\nThis is a bit complicated because the center-of-mass motion does not easily separate from the three equations. Instead, choose the following coordinates,\n\n$$\n\\begin{eqnarray*}\nX&=&\\frac{x_1+2x_2+x_3}{4},\\\\\nq_1&=&x_1-x_2+\\ell,\\\\\nq_3&=&x_3-x_2-\\ell.\n\\end{eqnarray*}\n$$\n\nIn these coordinates the potential energy only involves two coordinates,\n\n$$\n\\begin{eqnarray*}\nU&=&\\frac{k}{2}(q_1^2+q_3^2).\n\\end{eqnarray*}\n$$\n\nTo express the kinetic energy express $x_1, x_2$ and $x_3$ in terms of\n$X$, $q_1$ and $q_3$,\n\n$$\n\\begin{eqnarray*}\nx_1&=&(3q_1-q_3-4\\ell+4X)/4,\\\\\nx_2&=&(4X-q_1-q_3)/4,\\\\\nx_3&=&(3q_3-q_1+4\\ell+4X)/4.\n\\end{eqnarray*}\n$$\n\nThe kinetic energy and Lagrangian are them\n\n$$\n\\begin{eqnarray*}\nT&=&\\frac{m}{2}\\frac{1}{16}(3\\dot{q}_1-\\dot{q}_3+4\\dot{X})^2\n+m\\frac{1}{16}(4\\dot{X}-\\dot{q}_1-\\dot{q}_3)^2\n+\\frac{m}{2}\\frac{1}{16}(3\\dot{q}_3-\\dot{q}_1+4\\dot{X})^2\\\\\n&=&\\frac{3m}{8}(\\dot{q}_1^2+\\dot{q}_3^2)-\\frac{m}{4}\\dot{q}_1\\dot{q}_3\n+2m\\dot{X}^2,\\\\\n\\mathcal{L}&=&\\frac{3m}{8}(\\dot{q}_1^2+\\dot{q}_3^2)-\\frac{m}{4}\\dot{q}_1\\dot{q}_3\n+2m\\dot{X}^2-\\frac{k}{2}q_1^2-\\frac{k}{2}q_3^2.\n\\end{eqnarray*}\n$$\n\nThe three equations of motion are then,\n\n$$\n\\begin{eqnarray*}\n\\frac{3}{4}m\\ddot{q}_1-\\frac{1}{4}m\\ddot{q}_3&=&-kq_1,\\\\\n\\frac{3}{4}m\\ddot{q}_3-\\frac{1}{4}m\\ddot{q}_1&=&-kq_3,\\\\\n4M\\ddot{X}&=&0.\n\\end{eqnarray*}\n$$\n\nThe last equation simply states that the center-of-mass velocity is\nfixed. One could obtain the same result by summing the equations of\nmotion for $x_1$, $2x_2$ and $x_3$ above. The second two equations are\nmore complicated. To solve them, we assume a form\n\n$$\n\\begin{eqnarray*}\nq_1&=&Ae^{i\\omega t},\\\\\nq_3&=&Be^{i\\omega t},\n\\end{eqnarray*}\n$$\n\nBecause this is a linear equation, we can multiply the solution by a\nconstant and it will still be a solution. Thus, we can set $B=1$, then\nsolve for $A$, effectively solving for $A/B$. Putting this guess into\nthe equations of motion,\n\n$$\n\\begin{eqnarray*}\n-\\frac{3}{4}\\frac{A}{B}\\omega^2+\\frac{1}{4}\\omega^2&=&-\\omega_0^2\\frac{A}{B},\\\\\n-\\frac{3}{4}\\omega^2+\\frac{1}{4}\\frac{A}{B}\\omega^2&=&-\\omega_0^2.\n\\end{eqnarray*}\n$$\n\nThis is two equations and two unknowns, $\\omega^2$ and\n$A/B$. Substituting for $A/B$ gives a quadratic equation,\n\n$$\n\\begin{eqnarray*}\n\\omega^4-3\\omega_0^2\\omega^2+2\\omega_0^4&=&0,\\\\\n\\omega_0^2&\\equiv&k/m.\n\\end{eqnarray*}\n$$\n\nThe two solutions are\n\n$$\n\\begin{eqnarray*}\n(1)~~\\omega&=&\\omega_0,~~~A=-B,\\\\\n(2)~~\\omega&=&\\omega_0\\sqrt{2},~~~A=B.\n\\end{eqnarray*}\n$$\n\nThe first solution corresponds to the two outer masses moving in\nopposite directions, in sync, with the middle mass fixed. The second\nsolution has both outer masses moving in the same direction, but with\nthe center mass moving opposite. These two solutions are referred to\nas normal modes, and are characterized by their frequency and by the\nlinear combinations of coordinates that oscillate together. In\ngeneral, the solution is a linear combination of normal modes, which\nusually results in a chaotic looking motion. However, once the\nsolution is expressed in terms of the normal modes, each of which\noscillates independently in a simple manner, one can better understand\nthe motion. Further, the frequencies of these modes represent the\nnatural resonant frequencies of the system. This is important in the\nconstruction of many structures, such as bridges or vehicles.\n\n\nConsider a double pendulum confined to the $x-y$ plane, where $y$ is\nvertical. A mass $m$ is connected to the ceiling with a massless\nstring of length $\\ell$. A second mass $m$ hangs from the first mass\nwith an identical massless string of the same length. Using $\\theta_1$\nand $\\theta_2$ to describe the orientations of the strings relative to\nthe vertical axis, find the Lagrangian and derive the equations of\nmotion, both for arbitrary angles and in the small-angle\napproximation. Finally, express the equations of motion in the limit\nof small oscillations.\n\n\nThe kinetic and potential energies are:\n\n$$\n\\begin{eqnarray*}\nT&=&\\frac{1}{2}m\\ell^2\\dot{\\theta}_1^2\n+\\frac{1}{2}m\\left\\{(\\ell\\dot{\\theta}_1\\cos\\theta_1+\\ell\\dot{\\theta}_2\\cos\\theta_2)^2\n+(\\ell\\dot{\\theta}_1\\sin\\theta_1+\\ell\\dot{\\theta}_2\\sin\\theta_2)^2\\right\\}\\\\\n&=&\\frac{1}{2}m\\ell^2\\left\\{2\\dot{\\theta}_1^2+\\dot{\\theta}_2^2+2\\dot{\\theta}_1\\dot{\\theta}_2\\cos(\\theta_1-\\theta_2)\n\\right\\},\\\\\nU&=&mg\\ell(1-\\cos\\theta_1)+mg\\left[\\ell(1-\\cos\\theta_1)+\\ell(1-\\cos\\theta_2)\\right]\\\\\n&=&mg\\ell(3-2\\cos\\theta_1-\\cos\\theta_2)\n\\end{eqnarray*}\n$$\n\nLagrange's equations for $\\theta_1$ lead to\n\n$$\n\\begin{eqnarray*}\nm\\ell^2\\frac{d}{dt}\\left\\{2\\dot{\\theta}_1+\\dot{\\theta}_2\\cos(\\theta_1-\\theta_2)\\right\\}&=&\n-m\\ell^2\\dot{\\theta}_1\\dot{\\theta}_2\\sin(\\theta_1-\\theta_2)\n-2mg\\ell\\sin\\theta_1,\\\\\n2\\ddot{\\theta}_1+\\ddot{\\theta}_2\\cos(\\theta_1-\\theta_2)+\\dot{\\theta}_2^2\\sin(\\theta_1-\\theta_2)\n&=&-2\\omega_0^2\\sin\\theta_1,\\\\\n\\omega_0^2&\\equiv& g/\\ell,\n\\end{eqnarray*}\n$$\n\nand the equations for $\\theta_2$ are\n\n$$\n\\begin{eqnarray*}\nm\\ell^2\\frac{d}{dt}\\left\\{\\dot{\\theta}_2+\\dot{\\theta}_1\\cos(\\theta_1-\\theta_2)\\right\\}&=&\nm\\ell^2\\dot{\\theta}_1\\dot{\\theta}_2\\sin(\\theta_1-\\theta_2)-mg\\ell\\sin\\theta_2,\\\\\n\\ddot{\\theta}_2+\\ddot{\\theta_1}\\cos(\\theta_1-\\theta_2)&=&\n-\\omega_0^2\\sin\\theta_2.\n\\end{eqnarray*}\n$$\n\nFor small oscillations, one can only consider terms linear in $\\theta_1$ and $\\theta_2$ or their derivatives,\n\n$$\n\\begin{eqnarray}\n2\\ddot{\\theta}_1+\\ddot{\\theta}_2&=&-2\\omega_0^2\\theta_1,\\\\\n\\nonumber\n\\ddot{\\theta}_1+\\ddot{\\theta}_2&=&-\\omega_0^2\\theta_2.\n\\end{eqnarray}\n$$\n\nTo find the solutions, assume they are of the form\n$\\theta_1=Ae^{i\\omega t}, \\theta_2=Be^{i\\omega t}$. Solve for $\\omega$\nand $A/B$, noting that $B$ is arbitrary.\n\nPlug in the desired form and find\n\n$$\n\\begin{eqnarray*}\ne^{i\\omega t}(-2\\omega^2A-\\omega^2B)&=&e^{i\\omega t}(-2\\omega_0^2A),\\\\\ne^{i\\omega t}(-\\omega^2A-\\omega^2B)&=&e^{i\\omega t}(-\\omega_0^2B).\n\\end{eqnarray*}\n$$\n\nWe can treat $B$ as arbitrary and set it to unity. When we find $A$,\nit is the same as $A/B$ for arbitrary $B$. This gives the equations\n\n$$\n\\begin{eqnarray*}\n2\\omega^2A+\\omega^2&=&2\\omega_0^2A,\\\\\n\\omega^2A+\\omega^2&=&\\omega_0^2.\n\\end{eqnarray*}\n$$\n\nThis is two equations and two unknowns. Solving them leads to a\nquadratic equation with solutions\n\n$$\n\\begin{eqnarray*}\nA/B&=&\\pm\\frac{1}{\\sqrt{2}},\\\\\n\\omega^2&=&\\frac{\\omega_0^2}{1\\pm 1/\\sqrt{2}}.\n\\end{eqnarray*}\n$$\n\nAgain, these two solutions are the normal modes, and the general\nsolution is a sum of the two solutions, with two arbitrary\nconstants. For the angles $\\theta_1$ and $\\theta_2$ are:\n\n$$\n\\begin{eqnarray*}\n\\theta_1&=&\\frac{A_+}{\\sqrt{2}}e^{i\\omega_+t}, ~\\theta_2=A_+e^{i\\omega_+t},\\\\\n\\theta_1&=&\\frac{-A_-}{\\sqrt{2}}e^{i\\omega_-t}, ~\\theta_2=A_-e^{i\\omega_-t},\\\\\n\\omega_{\\pm}&=&\\omega_0\\sqrt{\\frac{1}{1\\pm 1/\\sqrt{2}}}.\n\\end{eqnarray*}\n$$\n\nOne can also express the solution in vector notation, with the vectors\nhaving arbitrary amplitudes $A_+$ and $A_-$,\n\n$$\n\\begin{eqnarray*}\n\\theta_+&=&\\left(\\begin{array}{c}\n\\frac{1}{\\sqrt{2}}\\\\ 1\\end{array}\\right)A_+e^{i\\omega_+t},\\\\\n\\theta_-&=&\\left(\\begin{array}{c}\n\\frac{-1}{\\sqrt{2}}\\\\ 1\\end{array}\\right)A_-e^{i\\omega_-t}.\n\\end{eqnarray*}\n$$\n\nHere, the upper/lower components of the vector describe\n$\\theta_1/\\theta_2$ respectively.\n\n\n\n\nThese problems can be treated as linear algebra exercises. Linear\nalgebra is not used in this course, but nonetheless we describe how\nthis works for the curious student. In the limit of small vibrations,\nthe equations of motion can be expressed in the form,\n\n$$\n\\begin{eqnarray*}\nM\\ddot{q}&=&-Kq,\n\\end{eqnarray*}\n$$\n\na form that looks like the spring equation. However, $q$ is an\n$n-$dimensional vector and $M$ and $k$ are $n\\times n$ matrices. In\nthe double pendulum example, the dimensionality is 2 and the $q$\nrefers to the $\\theta_1$ and $\\theta_2$, and the matrices for $M$ and\n$K$ can be read off (add ref).\n\n$$\n\\begin{eqnarray*}\nM&=&\\left(\\begin{array}{cc}\n2&1\\\\\n1&1\\end{array}\\right)~,\\hspace*{40pt} K=\\left(\\begin{array}{cc}\n2\\omega_0^2&0\\\\\n0&\\omega_0^2\\end{array}\\right).\n\\end{eqnarray*}\n$$\n\nMultiplying both sides of the equation by the inverse matrix $M^{-1}$,\n\n$$\n\\begin{eqnarray*}\n\\ddot{q}&=&-\\left(M^{-1}K\\right)q.\n\\end{eqnarray*}\n$$\n\nHere,\n\n$$\n\\begin{eqnarray*}\nM^{-1}&=&\\left(\\begin{array}{cc}\n1&-1\\\\\n-1&2\\end{array}\\right),\\\\\nM^{-1}K&=&\\left(\\begin{array}{cc}\n2&-1\\\\\n-2&2\\end{array}\\right)\\omega_0^2.\n\\end{eqnarray*}\n$$\n\nOne can find a transformation, basically a rotation, that transforms\nto a frame where $M^{-1}K$ is diagonal. In this coordinate system the\ndiagonal components of $M^{-1}K$ represent the squared frequencies of\nthe normal modes,\n\n$$\nM^{-1}K\\rightarrow -\\left(\\begin{array}{cc}\n\\omega_+^2&0\\\\\n0&\\omega_-^2\\end{array}\\right)~,\n$$\n\nand are known as \"eigen\" frequencies. The corresponding unit vectors,\n\n$$\n\\left(\\begin{array}{c}\n1\\\\0\\end{array}\\right)~{\\rm and}~\\left(\\begin{array}{c}\n0\\\\1\\end{array}\\right)~{\\rm in~the~new~coordinate~system},\n$$\n\ncan be rotated back into the original frame, and become the solutions\nfor the normal modes. These are then called \"eigenvectors\", which\nare the same as the normal modes. Finding the eigenfrequencies is\nperformed by realizing that the determinant of a matrix is unchanged\nby the rotation between coordinate systems. Writing the equations of\nmotion as an eigenvalue problem,\n\n$$\n\\begin{eqnarray}\n\\left[A-\\lambda_i\\mathbb{1}\\right]u_i&=&0,~~~A\\equiv M^{-1}K,~\\lambda_i\\equiv \\omega^2_i.\n\\end{eqnarray}\n$$\n\nIn the coordinate system where $M^{-1}K$ is diagonal, and the forms\nfor $u_i$ are simple this requires that in that system, the diagonal\nelements of $M^{-1}K$ are the eigenvalues, $\\omega_i^2$. For each\n$\\omega^2_i$, the determinant $|A-\\lambda_i\\mathbb{1}|$ must\nvanish. This is then true in any coordinate system,\n\n$$\n\\begin{eqnarray}\n{\\rm det}\\left[A-\\lambda\\mathbb{1}\\right]&=&0,\n\\end{eqnarray}\n$$\n\nwhich for a $2\\times 2$ matrix becomes\n\n$$\n\\begin{eqnarray}\n\\left|\n\\begin{array}{cc}\nA_{11}-\\lambda&A_{12}\\\\\nA_{21}&A_{22}-\\lambda\n\\end{array}\n\\right|&=&0,\\\\\nA_{11}A_{22}-\\lambda A_{11}-\\lambda A_{22}+\\lambda^2-A_{21}A_{12}&=&0.\n\\end{eqnarray}\n$$\n\nOne can solve a quadratic equation for $\\lambda$, which gives two\neigenvalues corresponding to $\\omega_+^2$ and $\\omega_-^2$ found\nabove. Choosing one of the eigenvalues, one can insert one of the\neigenvalues $\\lambda_i$ into the eigenvalue problem and solve for $u_i$,\nthen choose the other eigenvalue and solve for the other corresponding\nvector.\n\nIf this were a 3-dimensional set of equations, the determinant would\ninclude terms like $\\lambda^3$ and would become a cubic equation with\nthree eigenvalues. One would then solve for three eigenvectors. If one\nhas a system with dimensionality $n>2$, one usually resorts to solving\nthe problem numerically due to the messiness of the algebra. The main\nprogramming languages all have packages which readily diagonalize\nmatrices and find eigenvectors and eigenvalues.\n\n\n\n## Conservation Laws\n\nEnergy is conserved only when the Lagrangian has no explicit\ndependence on time, i.e. $L(q,\\dot{q})$, not $L(q,\\dot{q},t)$. To show\nthis, we first define the Hamiltonian,\n\n$$\n\\begin{eqnarray}\nH&=&\\sum_i\\left(\\dot{q}_i\\frac{\\partial L}{\\partial\\dot{q}_i}\\right)-L.\n\\end{eqnarray}\n$$\n\nAfter showing that $H$ is conserved, i.e. $(d/dt)H=0$, we then show\nthat $H$ can be identified with the total energy, $H=T+V$.\n\nOne can see that $H$ is conserved by applying first using the chain\nrule for $(d/dt)H$, then applying Lagrange's\nequations,\n\n$$\n\\begin{eqnarray}\n\\frac{d}{dt}H&=&\\sum_i\\left\\{\\ddot{q}_i\\frac{\\partial L}{\\partial\\dot{q}_i}+\\dot{q}_i\\frac{d}{dt}\\left(\\frac{\\partial L}{\\partial\\dot{q}_i}\\right)-\\frac{\\partial L}{\\partial\\dot{q}_i}\\ddot{q}_i-\\frac{\\partial L}{\\partial q_i}\\dot{q}_i\\right\\}\\\\\n\\nonumber\n&=&\\sum_i\\left\\{\\ddot{q}_i\\frac{\\partial L}{\\partial\\dot{q}_i}+\\dot{q}_i\\frac{\\partial L}{\\partial q_i}-\\frac{\\partial L}{\\partial\\dot{q}_i}\\ddot{q}_i-\\frac{\\partial L}{\\partial q_i}\\dot{q}_i\\right\\}\\\\\n\\nonumber\n&=&0.\n\\end{eqnarray}\n$$\n\nThese steps assumed that $L$ had no explicit time dependence, i.e. $L$\nis a function of $q$ and $\\dot{q}$, but not of $t$.\n\nNext, we show that $L$ can be identified with the energy. Because $V$ does not depend on $\\dot{q}$,\n\n\n
\n\n$$\n\\begin{equation}\nH=\\sum_i\\frac{\\partial T}{\\partial\\dot{q}_i}\\dot{q}_i-T+V.\n\\label{_auto100} \\tag{136}\n\\end{equation}\n$$\n\nIf the kinetic energy has a purely quadratic form in terms of $\\dot{q}$,\n\n\n
\n\n$$\n\\begin{equation}\nT=\\sum_{ij}A_{ij}(q)\\dot{q}_i\\dot{q}_j,\n\\label{_auto101} \\tag{137}\n\\end{equation}\n$$\n\nthe Hamiltonian becomes\n\n$$\n\\begin{eqnarray}\nH&=&\\sum_{ij}2A_{ij}(q)\\dot{q}_i\\dot{q}_j-\\sum_{ij}A_{ij}(q)\\dot{q}_i\\dot{q}_j+V\\\\\n\\nonumber\n&=&T+V.\n\\end{eqnarray}\n$$\n\nThe proof that $H$ equals the energy hinged on the fact that the\nkinetic energy was quadratic in $\\dot{q}$. This can be attributed to\ntime-reversal symmetry. Because the Cartesian coordinates $x_i$ do not\ndepend on $\\dot{q}_i$ or on time, $\\dot{x}_i=(\\partial x_i/\\partial\nq_j)\\dot{q}_j$. Thus, the kinetic energy, $T=m\\dot{x}_i^2/2$, should\nbe proportional to two powers of $\\dot{q}$, which validates the\nassumption above.\n\nHere, energy conservation is predicated on the Lagrangian not having\nan explicit time dependence. Without an explicit time dependence the\nequations of motion are unchanged if one translates a fixed amount in\ntime because the physics does not depend on when the clock starts. In\ncontrast, the absolute time becomes relevant if there is an explicit\ntime dependence. In fact, conservation laws can usually be associated\nwith symmetries. In this case the translation symmetry in time leads\nto energy conservation.\n\nFor another example of how symmetry leads to conservation laws,\nconsider a Lagrangian for a particle of mass $m$ moving in a\ntwo-dimensional plane where the generalized coordinates are the radius\n$r$ and the angle $\\theta$. The kinetic energy would be\n\n\n
\n\n$$\n\\begin{equation}\nT=\\frac{1}{2}m\\left\\{\\dot{r}^2+r^2\\dot{\\theta}^2\\right\\},\n\\label{_auto102} \\tag{138}\n\\end{equation}\n$$\n\nand if the potential energy $V(r)$ depends only on the radius $r$ and\nnot on the angle, Lagrange's equations become\n\n$$\n\\begin{eqnarray}\n\\frac{d}{dt}(m\\dot{r})&=&-\\frac{\\partial V}{\\partial r}+m\\dot{\\theta}^2r,\\\\\n\\nonumber\n\\frac{d}{dt}(mr^2\\dot{\\theta})&=&0.\n\\end{eqnarray}\n$$\n\nThe second equation implies that $mr^2\\dot{\\theta}$ is a\nconstant. Indeed, it is the angular momentum which is conserved for a\nradial force. Here, the conservation of angular momentum is associated\nwith the independence of the physics to changes in $\\theta$, or in\nother words, rotational invariance. Once one knows the fact that\n$L=mr^2\\dot{\\theta}$ is conserved, it can be inserted into the\nequations of motion for $\\dot{r}$,\n\n\n
\n\n$$\n\\begin{equation}\nm\\ddot{r}=-\\frac{\\partial V}{\\partial r}+\\frac{L^2}{mr^3}.\n\\label{_auto103} \\tag{139}\n\\end{equation}\n$$\n\nThis is related to [Emmy Noether's theorem](http://en.wikipedia.org/wiki/Noether's_theorem)\n\nSimply stated, if the Lagrangian $L$ is independent of $q_i$, one can\nsee that the quantity $\\partial L/\\partial\\dot{q}_i$ is conserved,\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{d}{dt}\\frac{\\partial L}{\\partial\\dot{q}_i}=0.\n\\label{_auto104} \\tag{140}\n\\end{equation}\n$$\n\nAnother easy example is in Cartesian coordinates where the potential\ndepends only on $x$ and $y$ but not on $z$. In that case, there is a\ntranslational symmetry. From the last equation, this translates\ninto conservation of the momentum in the $z$ direction.\n\n\nConsider a pair of particles of mass $m_1$ and $m_2$ where the potential is of the form\n\n$$\nU(\\boldsymbol{r}_1,\\boldsymbol{r}_2)=V_a(|m_1\\boldsymbol{r}_1+m_2\\boldsymbol{r}_2|/(m_1+m_2))+V_b(|\\boldsymbol{r}_1-\\boldsymbol{r}_2|).\n$$\n\nUsing symmetry arguments alone, are there any conserved components of\nthe momentum? or the angular momentum??\n\nThere is no translational invariance, hence there are no conserved\ncomponents of the momentum. However, there is rotational invariance\nabout any axis that goes through the origin. Hence, there is angular\nmomentum conservation in all three directions. Symmetry arguments are\ngreat ways to recognize the existence of conserved quantities, but\nactually expressing them in terms of coordinates can be tricky. For\ninstance, you may need to write the Lagrangian in terms of angles.\n\n\n\n\n\n\n", "meta": {"hexsha": "dcf65e12823577544bf8853c1ddc43c9313a8d6f", "size": 424437, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "doc/pub/LectureNotes/ipynb/LectureNotes.ipynb", "max_stars_repo_name": "Shield94/Physics321", "max_stars_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2020-01-09T17:41:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T00:48:58.000Z", "max_issues_repo_path": "doc/pub/LectureNotes/ipynb/LectureNotes.ipynb", "max_issues_repo_name": "Shield94/Physics321", "max_issues_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-01-08T03:47:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-15T15:02:57.000Z", "max_forks_repo_path": "doc/pub/LectureNotes/ipynb/LectureNotes.ipynb", "max_forks_repo_name": "Shield94/Physics321", "max_forks_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 33, "max_forks_repo_forks_event_min_datetime": "2020-01-10T20:40:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T20:28:41.000Z", "avg_line_length": 29.917318672, "max_line_length": 589, "alphanum_fraction": 0.5464061804, "converted": true, "num_tokens": 83041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.5, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.23439531331312188}} {"text": "\n\n# Lambda School Data Science Module 143\n\n## Introduction to Bayesian Inference\n\n!['Detector! What would the Bayesian statistician say if I asked him whether the--' [roll] 'I AM A NEUTRINO DETECTOR, NOT A LABYRINTH GUARD. SERIOUSLY, DID YOUR BRAIN FALL OUT?' [roll] '... yes.'](https://imgs.xkcd.com/comics/frequentists_vs_bayesians.png)\n\n*[XKCD 1132](https://www.xkcd.com/1132/)*\n\n\n## Prepare - Bayes' Theorem and the Bayesian mindset\n\nBayes' theorem possesses a near-mythical quality - a bit of math that somehow magically evaluates a situation. But this mythicalness has more to do with its reputation and advanced applications than the actual core of it - deriving it is actually remarkably straightforward.\n\n### The Law of Total Probability\n\nBy definition, the total probability of all outcomes (events) if some variable (event space) $A$ is 1. That is:\n\n$$P(A) = \\sum_n P(A_n) = 1$$\n\nThe law of total probability takes this further, considering two variables ($A$ and $B$) and relating their marginal probabilities (their likelihoods considered independently, without reference to one another) and their conditional probabilities (their likelihoods considered jointly). A marginal probability is simply notated as e.g. $P(A)$, while a conditional probability is notated $P(A|B)$, which reads \"probability of $A$ *given* $B$\".\n\nThe law of total probability states:\n\n$$P(A) = \\sum_n P(A | B_n) P(B_n)$$\n\nIn words - the total probability of $A$ is equal to the sum of the conditional probability of $A$ on any given event $B_n$ times the probability of that event $B_n$, and summed over all possible events in $B$.\n\n### The Law of Conditional Probability\n\nWhat's the probability of something conditioned on something else? To determine this we have to go back to set theory and think about the intersection of sets:\n\nThe formula for actual calculation:\n\n$$P(A|B) = \\frac{P(A \\cap B)}{P(B)}$$\n\n\n\nThink of the overall rectangle as the whole probability space, $A$ as the left circle, $B$ as the right circle, and their intersection as the red area. Try to visualize the ratio being described in the above formula, and how it is different from just the $P(A)$ (not conditioned on $B$).\n\nWe can see how this relates back to the law of total probability - multiply both sides by $P(B)$ and you get $P(A|B)P(B) = P(A \\cap B)$ - replaced back into the law of total probability we get $P(A) = \\sum_n P(A \\cap B_n)$.\n\nThis may not seem like an improvement at first, but try to relate it back to the above picture - if you think of sets as physical objects, we're saying that the total probability of $A$ given $B$ is all the little pieces of it intersected with $B$, added together. The conditional probability is then just that again, but divided by the probability of $B$ itself happening in the first place.\n\n### Bayes Theorem\n\n\n\nHere is is, the seemingly magic tool:\n\n$$P(A|B) = \\frac{P(B|A)P(A)}{P(B)}$$\n\nIn words - the probability of $A$ conditioned on $B$ is the probability of $B$ conditioned on $A$, times the probability of $A$ and divided by the probability of $B$. These unconditioned probabilities are referred to as \"prior beliefs\", and the conditioned probabilities as \"updated.\"\n\nWhy is this important? Scroll back up to the XKCD example - the Bayesian statistician draws a less absurd conclusion because their prior belief in the likelihood that the sun will go nova is extremely low. So, even when updated based on evidence from a detector that is $35/36 = 0.972$ accurate, the prior belief doesn't shift enough to change their overall opinion.\n\nThere's many examples of Bayes' theorem - one less absurd example is to apply to [breathalyzer tests](https://www.bayestheorem.net/breathalyzer-example/). You may think that a breathalyzer test that is 100% accurate for true positives (detecting somebody who is drunk) is pretty good, but what if it also has 8% false positives (indicating somebody is drunk when they're not)? And furthermore, the rate of drunk driving (and thus our prior belief) is 1/1000.\n\nWhat is the likelihood somebody really is drunk if they test positive? Some may guess it's 92% - the difference between the true positives and the false positives. But we have a prior belief of the background/true rate of drunk driving. Sounds like a job for Bayes' theorem!\n\n$$\n\\begin{aligned}\nP(Drunk | Positive) &= \\frac{P(Positive | Drunk)P(Drunk)}{P(Positive)} \\\\\n&= \\frac{1 \\times 0.001}{0.08} \\\\\n&= 0.0125\n\\end{aligned}\n$$\n\nIn other words, the likelihood that somebody is drunk given they tested positive with a breathalyzer in this situation is only 1.25% - probably much lower than you'd guess. This is why, in practice, it's important to have a repeated test to confirm (the probability of two false positives in a row is $0.08 * 0.08 = 0.0064$, much lower), and Bayes' theorem has been relevant in court cases where proper consideration of evidence was important.\n\n## Derive Baye's Rule\n\n\\begin{align}\nP(A|B) &= \\frac{P(A \\cap B)}{P(B)}\\\\\n\\Rightarrow P(A|B)P(B) &= P(A \\cap B)\\\\\nP(B|A) &= \\frac{P(B \\cap A)}{P(A)}\\\\\n\\Rightarrow P(B|A)P(A) &= P(B \\cap A)\\\\\n\\Rightarrow P(A|B)P(B) &= P(B|A)P(A) \\\\\nP(A \\cap B) &= P(B \\cap A)\\\\\nP(A|B) &= \\frac{P(B|A) \\times P(A)}{P(B)}\n\\end{align}\n\n## Live Lecture - Deriving Bayes' Theorem, Calculating Bayesian Confidence\n\nNotice that $P(A|B)$ appears in the above laws - in Bayesian terms, this is the belief in $A$ updated for the evidence $B$. So all we need to do is solve for this term to derive Bayes' theorem. Let's do it together!\n\n\n```\n# Activity 2 - Use SciPy to calculate Bayesian confidence intervals\n# https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.bayes_mvs.html#scipy.stats.bayes_mvs\n\nfrom scipy import stats\nimport numpy as np\n\nnp.random.seed(seed=42)\n\ncoinflips = np.random.binomial(n=1, p=.5, size=100)\nprint(coinflips)\n```\n\n [0 1 1 1 0 0 0 1 1 1 0 1 1 0 0 0 0 1 0 0 1 0 0 0 0 1 0 1 1 0 1 0 0 1 1 1 0\n 0 1 0 0 0 0 1 0 1 0 1 1 0 1 1 1 1 1 1 0 0 0 0 0 0 1 0 0 1 0 1 0 1 1 0 0 1\n 1 1 1 0 0 0 1 1 0 0 0 0 1 1 1 0 0 1 1 1 1 0 1 0 0 0]\n\n\n\n```\ndef confidence_interval(data, confidence=.95):\n n = len(data)\n mean = sum(data)/n\n data = np.array(data)\n stderr = stats.sem(data)\n interval = stderr * stats.t.ppf((1 + confidence) / 2.0, n-1)\n return (mean , mean-interval, mean+interval)\n```\n\n\n```\nconfidence_interval(coinflips)\n```\n\n\n\n\n (0.47, 0.3704689875017368, 0.5695310124982632)\n\n\n\n\n```\nhelp(stats.bayes_mvs)\n```\n\n Help on function bayes_mvs in module scipy.stats.morestats:\n \n bayes_mvs(data, alpha=0.9)\n Bayesian confidence intervals for the mean, var, and std.\n \n Parameters\n ----------\n data : array_like\n Input data, if multi-dimensional it is flattened to 1-D by `bayes_mvs`.\n Requires 2 or more data points.\n alpha : float, optional\n Probability that the returned confidence interval contains\n the true parameter.\n \n Returns\n -------\n mean_cntr, var_cntr, std_cntr : tuple\n The three results are for the mean, variance and standard deviation,\n respectively. Each result is a tuple of the form::\n \n (center, (lower, upper))\n \n with `center` the mean of the conditional pdf of the value given the\n data, and `(lower, upper)` a confidence interval, centered on the\n median, containing the estimate to a probability ``alpha``.\n \n See Also\n --------\n mvsdist\n \n Notes\n -----\n Each tuple of mean, variance, and standard deviation estimates represent\n the (center, (lower, upper)) with center the mean of the conditional pdf\n of the value given the data and (lower, upper) is a confidence interval\n centered on the median, containing the estimate to a probability\n ``alpha``.\n \n Converts data to 1-D and assumes all data has the same mean and variance.\n Uses Jeffrey's prior for variance and std.\n \n Equivalent to ``tuple((x.mean(), x.interval(alpha)) for x in mvsdist(dat))``\n \n References\n ----------\n T.E. Oliphant, \"A Bayesian perspective on estimating mean, variance, and\n standard-deviation from data\", http://scholarsarchive.byu.edu/facpub/278,\n 2006.\n \n Examples\n --------\n First a basic example to demonstrate the outputs:\n \n >>> from scipy import stats\n >>> data = [6, 9, 12, 7, 8, 8, 13]\n >>> mean, var, std = stats.bayes_mvs(data)\n >>> mean\n Mean(statistic=9.0, minmax=(7.103650222612533, 10.896349777387467))\n >>> var\n Variance(statistic=10.0, minmax=(3.176724206..., 24.45910382...))\n >>> std\n Std_dev(statistic=2.9724954732045084, minmax=(1.7823367265645143, 4.945614605014631))\n \n Now we generate some normally distributed random data, and get estimates of\n mean and standard deviation with 95% confidence intervals for those\n estimates:\n \n >>> n_samples = 100000\n >>> data = stats.norm.rvs(size=n_samples)\n >>> res_mean, res_var, res_std = stats.bayes_mvs(data, alpha=0.95)\n \n >>> import matplotlib.pyplot as plt\n >>> fig = plt.figure()\n >>> ax = fig.add_subplot(111)\n >>> ax.hist(data, bins=100, density=True, label='Histogram of data')\n >>> ax.vlines(res_mean.statistic, 0, 0.5, colors='r', label='Estimated mean')\n >>> ax.axvspan(res_mean.minmax[0],res_mean.minmax[1], facecolor='r',\n ... alpha=0.2, label=r'Estimated mean (95% limits)')\n >>> ax.vlines(res_std.statistic, 0, 0.5, colors='g', label='Estimated scale')\n >>> ax.axvspan(res_std.minmax[0],res_std.minmax[1], facecolor='g', alpha=0.2,\n ... label=r'Estimated scale (95% limits)')\n \n >>> ax.legend(fontsize=10)\n >>> ax.set_xlim([-4, 4])\n >>> ax.set_ylim([0, 0.5])\n >>> plt.show()\n \n\n\n\n```\n#0.37046898750173674\n#0.3704689875017368\n\nstats.bayes_mvs(coinflips, alpha=.95)\n```\n\n\n\n\n (Mean(statistic=0.47, minmax=(0.37046898750173674, 0.5695310124982632)),\n Variance(statistic=0.25680412371134015, minmax=(0.1939698977025208, 0.3395533426586547)),\n Std_dev(statistic=0.5054540733507159, minmax=(0.44042013771229943, 0.5827120581030176)))\n\n\n\n\n```\ncoinflips_mean_dist, _, _ = stats.mvsdist(coinflips)\ncoinflips_mean_dist\n```\n\n\n\n\n \n\n\n\n\n```\nhelp(coinflips_mean_dist)\n```\n\n Help on rv_frozen in module scipy.stats._distn_infrastructure object:\n \n class rv_frozen(builtins.object)\n | # Frozen RV class\n | \n | Methods defined here:\n | \n | __init__(self, dist, *args, **kwds)\n | Initialize self. See help(type(self)) for accurate signature.\n | \n | cdf(self, x)\n | \n | entropy(self)\n | \n | expect(self, func=None, lb=None, ub=None, conditional=False, **kwds)\n | \n | interval(self, alpha)\n | \n | isf(self, q)\n | \n | logcdf(self, x)\n | \n | logpdf(self, x)\n | \n | logpmf(self, k)\n | \n | logsf(self, x)\n | \n | mean(self)\n | \n | median(self)\n | \n | moment(self, n)\n | \n | pdf(self, x)\n | \n | pmf(self, k)\n | \n | ppf(self, q)\n | \n | rvs(self, size=None, random_state=None)\n | \n | sf(self, x)\n | \n | stats(self, moments='mv')\n | \n | std(self)\n | \n | var(self)\n | \n | ----------------------------------------------------------------------\n | Data descriptors defined here:\n | \n | __dict__\n | dictionary for instance variables (if defined)\n | \n | __weakref__\n | list of weak references to the object (if defined)\n | \n | random_state\n \n\n\n\n```\ncoinflips_mean_dist.rvs(100)\n```\n\n\n\n\n array([0.47447628, 0.51541425, 0.54722018, 0.4589882 , 0.51501386,\n 0.53819192, 0.43382292, 0.53546659, 0.47026173, 0.44967562,\n 0.4621107 , 0.42691904, 0.37324325, 0.47531437, 0.46052277,\n 0.48711257, 0.52456771, 0.43332181, 0.49545882, 0.44671454,\n 0.47520117, 0.47047251, 0.41828918, 0.50159477, 0.42965501,\n 0.45273383, 0.48045849, 0.45342529, 0.48238344, 0.53966291,\n 0.48230241, 0.48073422, 0.48553525, 0.47962228, 0.41274185,\n 0.42892633, 0.5170948 , 0.42678096, 0.42249309, 0.51499109,\n 0.47059199, 0.39903942, 0.41790336, 0.46406817, 0.42232382,\n 0.42163269, 0.47848227, 0.48232842, 0.4731858 , 0.51077244,\n 0.3957508 , 0.48504646, 0.49014295, 0.53252732, 0.45495376,\n 0.47883978, 0.60393033, 0.4492549 , 0.44797902, 0.54782121,\n 0.43380002, 0.5760073 , 0.36941266, 0.44467418, 0.4939245 ,\n 0.45278835, 0.55635162, 0.48695459, 0.39080983, 0.45948606,\n 0.2941779 , 0.35950718, 0.44805696, 0.4725126 , 0.42218381,\n 0.45985418, 0.47545393, 0.44317753, 0.46267013, 0.4458753 ,\n 0.44204707, 0.51334913, 0.50914181, 0.49923748, 0.46895674,\n 0.43892798, 0.45984946, 0.44984632, 0.53560791, 0.45865723,\n 0.48646824, 0.55937503, 0.41464303, 0.50701457, 0.46934196,\n 0.37681534, 0.42748113, 0.49812825, 0.48278895, 0.4964763 ])\n\n\n\n\n```\nimport pandas as pd\npd.DataFrame(coinflips).describe()\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
0
count100.000000
mean0.470000
std0.501614
min0.000000
25%0.000000
50%0.000000
75%1.000000
max1.000000
\n
\n\n\n\n## Assignment - Code it up!\n\nMost of the above was pure math - now write Python code to reproduce the results! This is purposefully open ended - you'll have to think about how you should represent probabilities and events. You can and should look things up, and as a stretch goal - refactor your code into helpful reusable functions!\n\nSpecific goals/targets:\n\n1. Write a function `def prob_drunk_given_positive(prob_drunk_prior, prob_positive, prob_positive_drunk)` that reproduces the example from lecture, and use it to calculate and visualize a range of situations\n2. Explore `scipy.stats.bayes_mvs` - read its documentation, and experiment with it on data you've tested in other ways earlier this week\n3. Create a visualization comparing the results of a Bayesian approach to a traditional/frequentist approach\n4. In your own words, summarize the difference between Bayesian and Frequentist statistics\n\nIf you're unsure where to start, check out [this blog post of Bayes theorem with Python](https://dataconomy.com/2015/02/introduction-to-bayes-theorem-with-python/) - you could and should create something similar!\n\nStretch goals:\n\n- Apply a Bayesian technique to a problem you previously worked (in an assignment or project work) on from a frequentist (standard) perspective\n- Check out [PyMC3](https://docs.pymc.io/) (note this goes beyond hypothesis tests into modeling) - read the guides and work through some examples\n- Take PyMC3 further - see if you can build something with it!\n\n\n```\n# Write a function def prob_drunk_given_positive(prob_drunk_prior, prob_positive, prob_positive_drunk) that reproduces the example from lecture, and use it to calculate and visualize a range of situations\n\ndef prob_drunk_given_positive(prob_drunk_prior - .001, prob_positive, prob_positive_drunk)\n\n```\n\n\n```\n\n```\n\n## Assignment - Code it up!\n\nMost of the above was pure math - now write Python code to reproduce the results! This is purposefully open ended - you'll have to think about how you should represent probabilities and events. You can and should look things up, and as a stretch goal - refactor your code into helpful reusable functions!\n\nSpecific goals/targets:\n\n1. Write a function `def prob_drunk_given_positive(prob_drunk_prior, prob_positive, prob_positive_drunk)` that reproduces the example from lecture, and use it to calculate and visualize a range of situations\n2. Explore `scipy.stats.bayes_mvs` - read its documentation, and experiment with it on data you've tested in other ways earlier this week\n3. Create a visualization comparing the results of a Bayesian approach to a traditional/frequentist approach\n4. In your own words, summarize the difference between Bayesian and Frequentist statistics\n\nIf you're unsure where to start, check out [this blog post of Bayes theorem with Python](https://dataconomy.com/2015/02/introduction-to-bayes-theorem-with-python/) - you could and should create something similar!\n\nStretch goals:\n\n- Apply a Bayesian technique to a problem you previously worked (in an assignment or project work) on from a frequentist (standard) perspective\n- Check out [PyMC3](https://docs.pymc.io/) (note this goes beyond hypothesis tests into modeling) - read the guides and work through some examples\n- Take PyMC3 further - see if you can build something with it!\n\n## Assignment - Code it up!\n\nMost of the above was pure math - now write Python code to reproduce the results! This is purposefully open ended - you'll have to think about how you should represent probabilities and events. You can and should look things up, and as a stretch goal - refactor your code into helpful reusable functions!\n\nSpecific goals/targets:\n\n1. Write a function `def prob_drunk_given_positive(prob_drunk_prior, prob_positive, prob_positive_drunk)` that reproduces the example from lecture, and use it to calculate and visualize a range of situations\n2. Explore `scipy.stats.bayes_mvs` - read its documentation, and experiment with it on data you've tested in other ways earlier this week\n3. Create a visualization comparing the results of a Bayesian approach to a traditional/frequentist approach\n4. In your own words, summarize the difference between Bayesian and Frequentist statistics\n\nIf you're unsure where to start, check out [this blog post of Bayes theorem with Python](https://dataconomy.com/2015/02/introduction-to-bayes-theorem-with-python/) - you could and should create something similar!\n\nStretch goals:\n\n- Apply a Bayesian technique to a problem you previously worked (in an assignment or project work) on from a frequentist (standard) perspective\n- Check out [PyMC3](https://docs.pymc.io/) (note this goes beyond hypothesis tests into modeling) - read the guides and work through some examples\n- Take PyMC3 further - see if you can build something with it!\n\n## Resources\n\n- [Worked example of Bayes rule calculation](https://en.wikipedia.org/wiki/Bayes'_theorem#Examples) (helpful as it fully breaks out the denominator)\n- [Source code for mvsdist in scipy](https://github.com/scipy/scipy/blob/90534919e139d2a81c24bf08341734ff41a3db12/scipy/stats/morestats.py#L139)\n", "meta": {"hexsha": "62f760939073a2e4dd01e5b37b82e88bcc040cd6", "size": 33261, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "module3-introduction-to-bayesian-inference/LS_DS_143_Introduction_to_Bayesian_Inference.ipynb", "max_stars_repo_name": "standroidbeta/DS-Unit-1-Sprint-4-Statistical-Tests-and-Experiments", "max_stars_repo_head_hexsha": "f0c67697cfacecffc945df82125f956c8d5bbf38", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "module3-introduction-to-bayesian-inference/LS_DS_143_Introduction_to_Bayesian_Inference.ipynb", "max_issues_repo_name": "standroidbeta/DS-Unit-1-Sprint-4-Statistical-Tests-and-Experiments", "max_issues_repo_head_hexsha": "f0c67697cfacecffc945df82125f956c8d5bbf38", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "module3-introduction-to-bayesian-inference/LS_DS_143_Introduction_to_Bayesian_Inference.ipynb", "max_forks_repo_name": "standroidbeta/DS-Unit-1-Sprint-4-Statistical-Tests-and-Experiments", "max_forks_repo_head_hexsha": "f0c67697cfacecffc945df82125f956c8d5bbf38", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.424744898, "max_line_length": 472, "alphanum_fraction": 0.5074411473, "converted": true, "num_tokens": 5652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. YES", "lm_q1_score": 0.44167299096624174, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.23290146606697357}} {"text": "Chapter 1\n======\n***\n\nThe Philosophy of Bayesian Inference\n------\n \n> You are a skilled programmer, but bugs still slip into your code. After a particularly difficult implementation of an algorithm, you decide to test your code on a trivial example. It passes. You test the code on a harder problem. It passes once again. And it passes the next, *even more difficult*, test too! You are starting to believe that there may be no bugs in this code...\n\nIf you think this way, then congratulations, you already are a Bayesian practitioner! Bayesian inference is simply updating your beliefs after considering new evidence. A Bayesian can rarely be certain about a result, but he or she can be very confident. Just like in the example above, we can never be 100% sure that our code is bug-free unless we test it on every possible problem; something rarely possible in practice. Instead, we can test it on a large number of problems, and if it succeeds we can feel more *confident* about our code. Bayesian inference works identically: we update our beliefs about an outcome; rarely can we be absolutely sure unless we rule out all other alternatives. \n\n\n\n###The Bayesian state of mind\n\n\nBayesian inference differs from more traditional statistical inference by preserving *uncertainty* about our beliefs. At first, this sounds like a bad statistical technique. Isn't statistics all about deriving *certainty* from randomness? To reconcile this, we need to start thinking like Bayesians. \n\nThe Bayesian world-view interprets probability as measure of *believability in an event*, that is, how confident we are in an event occurring. In fact, we will see in a moment that this is the natural interpretation of probability. \n\nFor this to be clearer, we consider an alternative interpretation of probability: *Frequentist* methods assume that probability is the long-run frequency of events (hence the bestowed title). For example, the *probability of plane accidents* under a frequentist philosophy is interpreted as the *long-term frequency of plane accidents*. This makes logical sense for many probabilities of events, but becomes more difficult to understand when events have no long-term frequency of occurrences. Consider: we often assign probabilities to outcomes of presidential elections, but the election itself only happens once! Frequentists get around this by invoking alternative realities and saying across all these universes, the frequency of occurrences defines the probability. \n\nBayesians, on the other hand, have a more intuitive approach. Bayesians interpret a probability as measure of *belief*, or confidence, of an event occurring. An individual who assigns a belief of 0 to an event has no confidence that the event will occur; conversely, assigning a belief of 1 implies that the individual is absolutely certain of an event occurring. Beliefs between 0 and 1 allow for weightings of other outcomes. This definition agrees with the probability of a plane accident example, for having observed the frequency of plane accidents, an individual's belief should be equal to that frequency, excluding any outside information. Similarly, under this definition of probability being equal to beliefs, it is clear how we can speak about probabilities (beliefs) of presidential election outcomes: how confident are you candidate A will win?\n\nNotice in the paragraph above, I assigned the belief (probability) measure to an *individual*, not to Nature. This is very interesting, as this definition leaves room for conflicting beliefs between individuals. Again, this is appropriate for what naturally occurs: different individuals have different beliefs of events occurring, because they possess different *information* about the world. Consider the following examples demonstrating the relationship between individual beliefs and probabilities:\n\n- I flip a coin, and we both guess the result. We would both agree, assuming the coin is fair, that the probability of heads is 1/2. Assume, then, that I peek at the coin. Now I know for certain what the result is: I assign probability 1.0 to either heads or tails. Now what is *your* belief that the coin is heads? My knowledge of the outcome has not changed the coin's results. Thus we assign different probabilities to the result. \n\n- Your code either has a bug in it or not, but we do not know for certain which is true. Though we have a belief about the presence or absence of a bug. \n\n- A medical patient is exhibiting symptoms $x$, $y$ and $z$. There are a number of diseases that could be causing all of them, but only a single disease is present. A doctor has beliefs about which disease.\n\n\nThis philosophy of treating beliefs as probability is natural to humans. We employ it constantly as we interact with the world and only see partial evidence. Alternatively, you have to be *trained* to think like a frequentist. \n\nTo align ourselves with traditional probability notation, we denote our belief about event $A$ as $P(A)$. We call this quantity the *prior probability*.\n\nJohn Maynard Keynes, a great economist and thinker, said \"When the facts change, I change my mind. What do you do, sir?\" This quote reflects the way a Bayesian updates his or her beliefs after seeing evidence. Even --especially-- if the evidence is counter to what was initially believed, the evidence cannot be ignored. We denote our updated belief as $P(A |X )$, interpreted as the probability of $A$ given the evidence $X$. We call the updated belief the *posterior probability* so as to contrast it with the prior probability. For example, consider the posterior probabilities (read: posterior beliefs) of the above examples, after observing some evidence $X$.:\n\n1\\. $P(A): \\;\\;$ the coin has a 50 percent chance of being heads. $P(A | X):\\;\\;$ You look at the coin, observe a heads has landed, denote this information $X$, and trivially assign probability 1.0 to heads and 0.0 to tails.\n\n2\\. $P(A): \\;\\;$ This big, complex code likely has a bug in it. $P(A | X): \\;\\;$ The code passed all $X$ tests; there still might be a bug, but its presence is less likely now.\n\n3\\. $P(A):\\;\\;$ The patient could have any number of diseases. $P(A | X):\\;\\;$ Performing a blood test generated evidence $X$, ruling out some of the possible diseases from consideration.\n\n\nIt's clear that in each example we did not completely discard the prior belief after seeing new evidence $X$, but we *re-weighted the prior* to incorporate the new evidence (i.e. we put more weight, or confidence, on some beliefs versus others). \n\nBy introducing prior uncertainty about events, we are already admitting that any guess we make is potentially very wrong. After observing data, evidence, or other information, we update our beliefs, and our guess becomes *less wrong*. This is the alternative side of the prediction coin, where typically we try to be *more right*.\n\n\n\n###Bayesian Inference in Practice\n\n If frequentist and Bayesian inference were programming functions, with inputs being statistical problems, then the two would be different in what they return to the user. The frequentist inference function would return a number, whereas the Bayesian function would return *probabilities*.\n\nFor example, in our debugging problem above, calling the frequentist function with the argument \"My code passed all $X$ tests; is my code bug-free?\" would return a *YES*. On the other hand, asking our Bayesian function \"Often my code has bugs. My code passed all $X$ tests; is my code bug-free?\" would return something very different: a probabilities of *YES* and *NO*. The function might return:\n\n\n> *YES*, with probability 0.8; *NO*, with probability 0.2\n\n\n\nThis is very different from the answer the frequentist function returned. Notice that the Bayesian function accepted an additional argument: *\"Often my code has bugs\"*. This parameter is the *prior*. By including the prior parameter, we are telling the Bayesian function to include our belief about the situation. Technically this parameter in the Bayesian function is optional, but we will see excluding it has its own consequences. \n\n\n####Incorporating evidence\n\nAs we acquire more and more instances of evidence, our prior belief is *washed out* by the new evidence. This is to be expected. For example, if your prior belief is something ridiculous, like \"I expect the sun to explode today\", and each day you are proved wrong, you would hope that any inference would correct you, or at least align your beliefs better. Bayesian inference will correct this belief.\n\n\nDenote $N$ as the number of instances of evidence we possess. As we gather an *infinite* amount of evidence, say as $N \\rightarrow \\infty$, our Bayesian results align with frequentist results. Hence for large $N$, statistical inference is more or less objective. On the other hand, for small $N$, inference is much more *unstable*: frequentist estimates have more variance and larger confidence intervals. This is where Bayesian analysis excels. By introducing a prior, and returning probabilities (instead of a scalar estimate), we *preserve the uncertainty* that reflects the instability of stastical inference of a small $N$ dataset. \n\nOne may think that for large $N$, one can be indifferent between the two techniques since they offer similar inference, and might lean towards the computational-simpler, frequentist methods. An individual in this position should consider the following quote by Andrew Gelman (2005)[1], before making such a decision:\n\n> Sample sizes are never large. If $N$ is too small to get a sufficiently-precise estimate, you need to get more data (or make more assumptions). But once $N$ is \"large enough,\" you can start subdividing the data to learn more (for example, in a public opinion poll, once you have a good estimate for the entire country, you can estimate among men and women, northerners and southerners, different age groups, etc.). $N$ is never enough because if it were \"enough\" you'd already be on to the next problem for which you need more data.\n\n### Are frequentist methods incorrect then? \n\n**No.**\n\nFrequentist methods are still useful or state-of-the-art in many areas. Tools like Least Squares linear regression, LASSO regression, EM algorithm etc. are all very powerful and incredibly fast. Bayesian methods are a compliment to solve the problems these solutions cannot or to gain further insight into the underlying system by offering more flexibility in modeling.\n\n\n#### A note on *Big Data*\nParadoxically, big data's predictive analytic problems are actually solved by relatively simple algorithms [2][4]. Thus we can argue that big data's prediction difficulty does not lie in the algorithm used, but instead on the computational difficulties of storage and execution on big data. (One should also consider Gelman's quote from above and ask \"Do I really have big data?\" )\n\nThe much more difficult analytic problems involve *medium data* and, especially troublesome, *really small data*. Using a similar argument as Gelman's above, if big data problems are *big enough* to be readily solved, then we should be more interested in the *not-quite-big enough* datasets. \n\n\n### Our Bayesian framework\n\nWe are interested in beliefs, which can be interpreted as probabilities by thinking Bayesian. We have a *prior* belief in event $A$, beliefs formed by previous information, e.g., our prior belief about bugs being in our code before performing tests.\n\nSecondly, we observe our evidence. To continue our buggy-code example: if our code passes $X$ tests, we want to update our belief to incorporate this. We call this new belief the *posterior* probability. Updating our belief is done via the following equation, known as Bayes' Theorem, after it's discoverer Thomas Bayes:\n\n\\begin{align}\n P( A | X ) = & \\frac{ P(X | A) P(A) } {P(X) } \\\\\\\\[5pt]\n& \\propto P(X | A) P(A)\\;\\; (\\propto \\text{is proportional to } )\n\\end{align}\n\nThe above formula is not unique to Bayesian inference: it is a mathematical fact with uses outside Bayesian inference. Bayesian inference merely uses it to connect prior probabilities $P(A)$ with an updated posterior probabilities $P(A | X )$.\n\n##### Example: Mandatory coin-flip example\n\nSince every statistics text must contain a coin-flipping example, I'll use it here to get it out of the way. Suppose, naively, that you are unsure what the ratio of heads is in a coin flip (spoiler alert: it's 50%). You believe there is some true underlying ratio, call it $p$, but have no guess apriori. We begin to flip a coin, and record the observations: this is our data. How does our inference change as we observe more and more data? More specifically, what do our posterior probabilities look like?\n\nBelow we plot a sequence of updating posteriors as we observe data (coin flips).\n\n\n```\n\"\"\"\nThe book uses a custom matplotlibrc file, which provides the unique styles for matplotlib plots.\nIf executing this book, and you wish to use the book's styling, provided are two options:\n 1. Overwrite your own matplotlibrc file with the rc-file provided in the book's styles/ dir.\n See http://matplotlib.org/users/customizing.html\n 2. Also in the styles is bmh_matplotlibrc.json file. This can be used to update the styles\n in only this notebook. Try running the following code:\n\n import json\n s = json.load( open(\"../styles/bmh_matplotlibrc.json\") )\n matplotlib.rcParams.update(s)\n\n\"\"\"\n\n#the code below can be passed over, as it is currently not important.\n%pylab inline\nfigsize( 11, 9)\n\nimport scipy.stats as stats\ndist = stats.beta\n#n_trials = [0,1, 2 ,4, 8, 16, 32, 64, 128, 500]\nn_trials = [0,1,2,3,4,5,8,15, 50, 500]\ndata = stats.bernoulli.rvs(0.5, size = n_trials[-1] )\n\nx = np.linspace(0,1,100)\n#y_prior = np.nan*np.ones( 100 )\n\nfor k, N in enumerate(n_trials):\n sx = subplot( len(n_trials)/2, 2, k+1)\n \n plt.setp(sx.get_yticklabels(), visible=False)\n heads = data[:N].sum()\n y = dist.pdf(x, 1 + heads, 1 + N - heads )\n plt.plot( x, y, label= \"observe %d tosses,\\n %d heads\"%(N,heads) )\n plt.fill_between( x, 0, y, color=\"#348ABD\", alpha = 0.4 )\n plt.vlines( 0.5, 0, 4, color = \"k\", linestyles = \"--\", lw=1 )\n \n leg = plt.legend()\n leg.get_frame().set_alpha(0.4)\n plt.autoscale(tight = True)\n\n\nplt.suptitle( \"Bayesian updating of posterior probabilities\", \n y = 1.02,\n fontsize = 14);\n\nplt.tight_layout()\n```\n\nAs the plot above shows, as we start to observe data, our posterior probabilities, represented as the above curves, start to shift and move around. Eventually, as we observe more and more data, our probabilities will lump closer and closer around the true value of $p=0.5$ (marked by a dashed line). \n\nNotice that the graph is not always *peaked* at 0.5. Apriori, there is no reason it should be. Remember we do not know what $p$ is, we only have seen the data. In fact, if we observe quite extreme data, say 8 flips and only 1 observed heads, our distribution would look very biased *away* from lumping around 0.5.\n\nThat being said, it does assign a positive probability to $p$ really being 0.5. As more data accumulates, we would see more and more probabilitiy being assigned at $p=0.5$.\n\nThe next example is a simple demonstration of the mathematics of Bayesian updating. \n\n#####Example: Bug, or just sweet, unintended feature?\n\n\nLet $A$ denote the event that our code has **no bugs** in it. Let $X$ denote the event that the code passes all debugging tests. For now, we will leave the prior probability of no bugs as a variable, i.e. $P(A) = p$. \n\nWe are interested in $P(A|X)$, i.e. the probability of no bugs, given our debugging tests $X$. To use the formula above, we need to compute some quantities.\n\nWhat is $P(X | A)$, i.e., the probability that the code passes $X$ tests *given* there are no bugs? Well, it is equal to 1, for a code with no bugs will pass all tests. \n\n$P(X)$ is a little bit trickier: The event $X$ can be divided into two possibilities, event $X$ occurring even though our code *indeed has* bugs (denoted $\\sim A\\;$, spoken *not $A$*), or event $X$ without bugs ($A$). $P(X)$ can be represented as:\n\n\\begin{align}\nP(X ) & = P(X \\text{ and } A) + P(X \\text{ and } \\sim A) \\\\\\\\[5pt]\n & = P(X|A)P(A) + P(X | \\sim A)P(\\sim A)\\\\\\\\[5pt]\n& = P(X|A)p + P(X | \\sim A)(1-p)\n\\end{align}\n\nWe have already computed $P(X|A)$ above. On the other hand, $P(X | \\sim A)$ is subjective: our code can pass tests but still have a bug in it, though the probability there is a bug present is reduced. Note this is dependent on the number of tests performed, the degree of complication in the tests, etc. Let's be conservative and assign $P(X|\\sim A) = 0.5$. Then\n\n\\begin{align}\nP(A | X) & = \\frac{1\\cdot p}{ 1\\cdot p +0.5 (1-p) } \\\\\\\\\n& = \\frac{ 2 p}{1+p}\n\\end{align}\nThis is the posterior probability. What does it look like as a function of our prior, $p \\in [0,1]$? \n\n\n```\nfigsize(12.5,4)\np = np.linspace( 0,1, 50)\nplt.plot( p, 2*p/(1+p), color = \"#348ABD\", lw = 3 )\nplt.fill_between( p, 2*p/(1+p), alpha = .2, facecolor = [\"#348ABD\"])\nplt.scatter( 0.2, 2*(0.2)/1.2, s = 140, c =\"#348ABD\" )\nplt.xlim( 0, 1)\nplt.ylim( 0, 1)\nplt.xlabel( \"Prior, $P(A) = p$\")\nplt.ylabel(\"Posterior, $P(A|X)$, with $P(A) = p$\")\nplt.title( \"Are there bugs in my code?\");\n```\n\nWe can see the biggest gains if we observe the $X$ tests passed when the prior probability, $p$, is low. Let's settle on a specific value for the prior. I'm a strong programmer (I think), so I'm going to give myself a realistic prior of 0.20, that is, there is a 20% chance that I write code bug-free. To be more realistic, this prior should be a function of how complicated and large the code is, but let's pin it at 0.20. Then my updated belief that my code is bug-free is 0.33. \n\nRecall that the prior is a probability: $p$ is the prior probability that there *are no bugs*, so $1-p$ is the prior probability that there *are bugs*.\n\nSimilarly, our posterior is also a probability, with $P(A | X)$ the probability there is no bug *given we saw all tests pass*, hence $1-P(A|X)$ is the probability there is a bug *given all tests passed*. What does our posterior probability look like? Below is a graph of both the prior and the posterior probabilities. \n\n\n\n```\nfigsize( 10, 4 )\ncolours = [\"#348ABD\", \"#A60628\"]\n\nprior = [0.20, 0.80]\nposterior = [1./3, 2./3]\nplt.bar( [0,.7], prior ,alpha = 0.60, width = 0.25, \\\n color = colours[0], label = \"prior distribution\",\n lw = \"3\", edgecolor = colours[0])\n\n\nplt.bar( [0+0.25,.7+0.25], posterior ,alpha = 0.5, \\\n width = 0.25, color = colours[1], \n label = \"posterior distribution\",\n lw = \"3\", edgecolor = colours[1])\n\nplt.xticks( [0.20,.95], [\"Bugs Absent\", \"Bugs Present\"] )\nplt.title(\"Prior and Posterior probability of bugs present, prior = 0.2\")\nplt.ylabel(\"Probability\")\nplt.legend(loc=\"upper left\");\n```\n\nNotice that after we observed $X$ occur, the probability of bugs being absent increased. By increasing the number of tests, we can approach confidence (probability 1) that there are no bugs present.\n\nThis was a very simple example of Bayesian inference and Bayes rule. Unfortunately, the mathematics necessary to perform more complicated Bayesian inference only becomes more difficult, except for artificially constructed cases. We will later see that this type of mathematical analysis is actually unnecessary. First we must broaden our modeling tools. The next section deals with *probability distributions*. If you are already familiar, feel free to skip (or at least skim), but for the less familiar the next section is essential.\n\n_______\n\n##Probability Distributions\n\n\n**Let's quickly recall what a probability distribution is:** Let $Z$ be some random variable. Then associated with $Z$ is a *probability distribution function* that assigns probabilities to the different outcomes $Z$ can take. There are three cases:\n\n- **$Z$ is discrete**: Discrete random variables may only assume values on a specified list. Things like populations, movie ratings, and number of votes are all discrete random variables. Discrete random variables become more clear when we contrast them with...\n\n- **$Z$ is continuous**: Continuous random variable can take on arbitrarily exact values. For example, temperature, speed, time, color are all modeled as continuous variables because you can constantly make the values more and more precise.\n\n- **$Z$ is mixed**: Mixed random variables assign probabilities to both discrete and continuous random variables, i.e. is is a combination of the above two categories. \n\n###Discrete Case\nIf $Z$ is discrete, then its distribution is called a *probability mass function*, which measures the probability $Z$ takes on the value $k$, denoted $P(Z=k)$. Note that the probability mass function completely describes the random variable $Z$, that is, if we know the mass function, we know how $Z$ should behave. There are popular probability mass functions that consistently appear: we will introduce them as needed, but let's introduce the first very useful probability mass function. We say $Z$ is *Poisson*-distributed if:\n\n$$P(Z = k) =\\frac{ \\lambda^k e^{-\\lambda} }{k!}, \\; \\; k=0,1,2, \\dots $$\n\nWhat is $\\lambda$? It is called the parameter, and it describes the shape of the distribution. For the Poisson random variable, $\\lambda$ can be any positive number. By increasing $\\lambda$, we add more probability to larger values, and conversely by decreasing $\\lambda$ we add more probability to smaller values. Unlike $\\lambda$, which can be any positive number, $k$ must be a non-negative integer, i.e., $k$ must take on values 0,1,2, and so on. This is very important, because if you wanted to model a population you could not make sense of populations with 4.25 or 5.612 members. \n\nIf a random variable $Z$ has a Poisson mass distribution, we denote this by writing\n\n$$Z \\sim \\text{Poi}(\\lambda) $$\n\nOne very useful property of the Poisson random variable, given we know $\\lambda$, is that its expected value is equal to the parameter, ie.:\n\n$$E\\large[ \\;Z\\; | \\; \\lambda \\;\\large] = \\lambda $$\n\nWe will use this property often, so it's something useful to remember. Below we plot the probability mass distribution for different $\\lambda$ values. The first thing to notice is that by increasing $\\lambda$ we add more probability to larger values occurring. Secondly, notice that although the graph ends at 15, the distributions do not. They assign positive probability to every non-negative integer.\n\n\n```\nfigsize( 12.5, 4)\n\nimport scipy.stats as stats\na = np.arange( 16 )\npoi = stats.poisson\nlambda_ = [1.5, 4.25 ]\n\nplt.bar( a, poi.pmf( a, lambda_[0]), color=colours[0],\n label = \"$\\lambda = %.1f$\"%lambda_[0], alpha = 0.60,\n edgecolor = colours[0], lw = \"3\")\n\nplt.bar( a, poi.pmf( a, lambda_[1]), color=colours[1],\n label = \"$\\lambda = %.1f$\"%lambda_[1], alpha = 0.60,\n edgecolor = colours[1], lw = \"3\")\n\nplt.xticks( a + 0.4, a )\nplt.legend()\nplt.ylabel(\"probability of $k$\")\nplt.xlabel(\"$k$\")\nplt.title(\"Probability mass function of a Poisson random variable; differing \\\n$\\lambda$ values\");\n```\n\n###Continuous Case\nInstead of a probability mass function, a continuous random variable has a *probability density function*. This might seem like unnecessary nomenclature, but the density function and the mass function are very different creatures. An example of continuous random variable is a random variable with a *exponential density*. The density function for an exponential random variable looks like:\n\n$$f_Z(z | \\lambda) = \\lambda e^{-\\lambda z }, \\;\\; z\\ge 0$$\n\nLike the Poisson random variable, an exponential random variable can only take on non-negative values. But unlike a Poisson random variable, the exponential can take on *any* non-negative values, like 4.25 or 5.612401. This makes it a poor choice for count data, which must be integers, but a great choice for time data, or temperature data (measured in Kelvins, of course), or any other precise *and positive* variable. Below are two probability density functions with different $\\lambda$ value. \n\nWhen a random variable $Z$ has an exponential distribution with parameter $\\lambda$, we say *$Z$ is exponential* and write\n\n$$Z \\sim \\text{Exp}(\\lambda)$$\n\nGiven a specific $\\lambda$, the expected value of an exponential random variable is equal to the inverse of $\\lambda$, that is:\n\n$$E[\\; Z \\;|\\; \\lambda \\;] = \\frac{1}{\\lambda}$$\n\n\n```\na = np.linspace(0,4, 100)\nexpo = stats.expon\nlambda_ = [0.5, 1]\n\nfor l,c in zip(lambda_,colours):\n plt.plot( a, expo.pdf( a, scale=1./l), lw=3, \n color=c, label = \"$\\lambda = %.1f$\"%l)\n plt.fill_between( a, expo.pdf( a, scale=1./l), color=c, alpha = .33)\n \nplt.legend()\nplt.ylabel(\"PDF at $z$\")\nplt.xlabel(\"$z$\")\nplt.title(\"Probability density function of an Exponential random variable;\\\n differing $\\lambda$\");\n```\n\n\n###But what is $\\lambda \\;$?\n\n\n**This question is what motivates statistics**. In the real world, $\\lambda$ is hidden from us. We only see $Z$, and must go backwards to try and determine $\\lambda$. The problem is so difficult because there is not a one-to-one mapping from $Z$ to $\\lambda$. Many different methods have been created to solve the problem of estimating $\\lambda$, but since $\\lambda$ is never actually observed, no one can say for certain which method is better! \n\nBayesian inference is concerned with *beliefs* about what $\\lambda$ is. Rather than try to guess $\\lambda$ exactly, we can only talk about what $\\lambda$ is likely to be by assigning a probability distribution to $\\lambda$.\n\nThis might seem odd at first: after all, $\\lambda$ is fixed, it is not (necessarily) random! How can we assign probabilities to a non-random event. Ah, we have fallen for the frequentist interpretation. Recall, under our Bayesian philosophy, we *can* assign probabilities if we interpret them as beliefs. And it is entirely acceptable to have *beliefs* about the parameter $\\lambda$. \n\n\n\n##### Example: Inferring behaviour from text-message data\n\nLet's try to model a more interesting example, concerning text-message rates:\n\n> You are given a series of text-message counts from a user of your system. The data, plotted over time, appears in the graph below. You are curious if the user's text-messaging habits changed over time, either gradually or suddenly. How can you model this? (This is in fact my own text-message data. Judge my popularity as you wish.)\n\n\n\n```\nfigsize( 12, 3.5 )\ncount_data = np.loadtxt(\"data/txtdata.csv\")\nn_count_data = len(count_data)\nplt.bar( np.arange( n_count_data ), count_data, color =\"#348ABD\" )\nplt.xlabel( \"Time (days)\")\nplt.ylabel(\"count of text-msgs received\")\nplt.title(\"Did the user's texting habits change over time?\")\nplt.xlim( 0, n_count_data );\n```\n\nBefore we begin, with respect to the plot above, would you say there was a change in behaviour\nduring the time period? \n\nHow can we start to model this? Well, as I conveniently already introduced, a Poisson random variable would be a very appropriate model for this *count* data. Denoting day $i$'s text-message count by $C_i$, \n\n$$ C_i \\sim \\text{Poisson}(\\lambda) $$\n\nWe are not sure about what the $\\lambda$ parameter is though. Looking at the chart above, it appears that the rate might become higher at some later date, which is equivalently saying the parameter $\\lambda$ increases at some later date (recall a higher $\\lambda$ means more probability on larger outcomes, that is, higher probability of many texts.).\n\nHow can we mathematically represent this? We can think, that at some later date (call it $\\tau$), the parameter $\\lambda$ suddenly jumps to a higher value. So we create two $\\lambda$ parameters, one for behaviour before the $\\tau$, and one for behaviour after. In literature, a sudden transition like this would be called a *switchpoint*:\n\n$$\n\\lambda = \n\\begin{cases}\n\\lambda_1 & \\text{if } t \\lt \\tau \\cr\n\\lambda_2 & \\text{if } t \\ge \\tau\n\\end{cases}\n$$\n\n\n If, in reality, no sudden change occurred and indeed $\\lambda_1 = \\lambda_2$, the $\\lambda$'s posterior distributions should look about equal.\n\nWe are interested in inferring the unknown $\\lambda$s. To use Bayesian inference, we need to assign prior probabilities to the different possible values of $\\lambda$. What would be good prior probability distributions for $\\lambda_1$ and $\\lambda_2$? Recall that $\\lambda_i, \\; i=1,2,$ can be any positive number. The *exponential* random variable has a density function for any positive number. This would be a good choice to model $\\lambda_i$. But, we need a parameter for this exponential distribution: call it $\\alpha$.\n\n\\begin{align}\n&\\lambda_1 \\sim \\text{Exp}( \\alpha ) \\\\\\\n&\\lambda_2 \\sim \\text{Exp}( \\alpha )\n\\end{align}\n\n$\\alpha$ is called a *hyper-parameter*, or a *parent-variable*, literally a parameter that influences other parameters. The influence is not too strong, so we can choose $\\alpha$ liberally. A good rule of thumb is to set the exponential parameter equal to the inverse of the average of the count data, since we're modeling $\\\\lambda$ using an Exponential distribution we can use the expected value identity shown earlier to get:\n\n$$\\frac{1}{N}\\sum_{i=0}^N \\;C_i \\approx E[\\; \\lambda \\; |\\; \\alpha ] = \\frac{1}{\\alpha}$$ \n\nAlternatively, and something I encourage the reader to try, is to have two priors: one for each $\\lambda_i$; creating two exponential distributions with different $\\alpha$ values reflects a prior belief that the rate changed after some period.\n\nWhat about $\\tau$? Well, due to the randomness, it is too difficult to pick out when $\\tau$ might have occurred. Instead, we can assign an *uniform prior belief* to every possible day. This is equivalent to saying\n\n\\begin{align}\n& \\tau \\sim \\text{DiscreteUniform(1,70) }\\\\\\\\\n& \\Rightarrow P( \\tau = k ) = \\frac{1}{70}\n\\end{align}\n\nSo after all this, what does our overall prior for the unknown variables look like? Frankly, *it doesn't matter*. What we should understand is that it would be an ugly, complicated, mess involving symbols only a mathematician would love. And things would only get uglier the more complicated our models become. Regardless, all we really care about is the posterior distribution. We next turn to PyMC, a Python library for performing Bayesian analysis, that is agnostic to the mathematical monster we have created. \n\n\nIntroducing our first hammer: PyMC\n-----\n\nPyMC is a Python library for programming Bayesian analysis [3]. It is a fast, well-maintained library. The only unfortunate part is that documentation can be lacking in areas, especially the bridge between beginner to hacker. One of this book's main goals is to solve that problem, and also to demonstrate why PyMC is so cool.\n\nWe will model the above problem using the PyMC library. This type of programming is called *probabilistic programming*, an unfortunate misnomer that invokes ideas of randomly-generated code and has likely confused and frightened users away from this field. The code is not random. The title is given because we create probability models using programming variables as the model's components, that is, model components are first-class primitives in this framework. \n\nB. Cronin [5] has a very motivating description of probabilistic programming:\n\n> Another way of thinking about this: unlike a traditional program, which only runs in the forward directions, a probabilistic program is run in both the forward and backward direction. It runs forward to compute the consequences of the assumptions it contains about the world (i.e., the model space it represents), but it also runs backward from the data to constrain the possible explanations. In practice, many probabilistic programming systems will cleverly interleave these forward and backward operations to efficiently home in on the best explanations.\n\nDue to its poorly understood title, I'll refrain from using the name *probabilistic programming*. Instead, I'll simply use *programming*, as that is what it really is. \n\nThe PyMC code is easy to follow along: the only novel thing should be the syntax, and I will interrupt the code to explain sections. Simply remember we are representing the model's components ($\\tau, \\lambda_1, \\lambda_2$ ) as variables:\n\n\n```\nimport pymc as mc\n\nn = count_data.shape[0]\n\nalpha = 1.0/count_data.mean() #recall count_data is \n #the variable that holds our txt counts\n\nlambda_1 = mc.Exponential( \"lambda_1\", alpha )\nlambda_2 = mc.Exponential( \"lambda_2\", alpha )\n\ntau = mc.DiscreteUniform( \"tau\", lower = 0, upper = n )\n```\n\nIn the above code, we create the PyMC variables corresponding to $\\lambda_1, \\; \\lambda_2$. We assign them to PyMC's *stochastic variables*, called stochastic variables because they are treated by the backend as random number generators. We can test this by calling their built-in `random()` method.\n\n\n```\nprint \"Random output:\", tau.random(),tau.random(), tau.random()\n```\n\n Random output: 55 42 41\n\n\n\n```\n@mc.deterministic\ndef lambda_( tau = tau, lambda_1 = lambda_1, lambda_2 = lambda_2 ):\n out = np.zeros( n ) \n out[:tau] = lambda_1 #lambda before tau is lambda1\n out[tau:] = lambda_2 #lambda after tau is lambda2\n return out\n```\n\nThis code is creating a new function `lambda_`, but really we think of it as a random variable: the random variable $\\lambda$ from above. Note that because `lambda_1`, `lambda_2` and `tau` are random, `lambda_` will be random. We are **not** fixing any variables yet. The `@mc.deterministic` is a decorator to tell PyMC that this is a deterministic function, i.e., if the arguments were deterministic (which they are not), the output would be deterministic as well. \n\n\n```\nobservation = mc.Poisson( \"obs\", lambda_, value = count_data, observed = True)\n\nmodel = mc.Model( [observation, lambda_1, lambda_2, tau] )\n```\n\nThe variable `observation` combines our data, `count_data`, with our proposed data-generation scheme, given by the variable `lambda_`, through the `value` keyword. We also set `observed = True` to tell PyMC that this should stay fixed in our analysis. Finally, PyMC wants us to collect all the variables of interest and create a `Model` instance out of them. This makes our life easier when we try to retrieve the results.\n\nThe below code will be explained in the Chapter 3, but this is where our results come from. One can think of it as a *learning* step. The machinery being employed is called *Monte Carlo Markov Chains* (which I delay explaining until Chapter 3). It returns thousands of random variables from the posterior distributions of $\\lambda_1, \\lambda_2$ and $\\tau$. We can plot a histogram of the random variables to see what the posterior distribution looks like. Below, we collect the samples (called *traces* in MCMC literature) in histograms.\n\n\n```\n### Myserious code to be explained later.\nmcmc = mc.MCMC(model)\nmcmc.sample( 20000, 5000, 1 )\n```\n\n [****************100%******************] 20000 of 20000 complete\n\n\n\n```\nlambda_1_samples = mcmc.trace( 'lambda_1' )[:]\nlambda_2_samples = mcmc.trace( 'lambda_2' )[:]\ntau_samples = mcmc.trace( 'tau' )[:]\n```\n\n\n```\nfigsize(12.5, 10)\n#histogram of the samples:\n\nax = plt.subplot(311)\nax.set_autoscaley_on(False)\n\nplt.hist( lambda_1_samples, histtype='stepfilled', bins = 30, alpha = 0.85, \n label = \"posterior of $\\lambda_1$\", color = \"#A60628\",normed = True )\nplt.legend(loc = \"upper left\")\nplt.title(r\"Posterior distributions of the variables $\\lambda_1,\\;\\lambda_2,\\;\\tau$\")\nplt.xlim([15,30])\nplt.xlabel(\"$\\lambda_2$ value\")\nplt.ylabel(\"probability\")\n\nax = plt.subplot(312)\nax.set_autoscaley_on(False)\n\nplt.hist( lambda_2_samples,histtype='stepfilled', bins = 30, alpha = 0.85, \n label = \"posterior of $\\lambda_2$\",color=\"#7A68A6\", normed = True )\nplt.legend(loc = \"upper left\")\nplt.xlim([15,30])\nplt.xlabel(\"$\\lambda_2$ value\")\nplt.ylabel(\"probability\")\n\nplt.subplot(313)\n\n\nw = 1.0/ tau_samples.shape[0] * np.ones_like( tau_samples )\nplt.hist( tau_samples, bins = n_count_data, alpha = 1, \n label = r\"posterior of $\\tau$\",\n color=\"#467821\", weights=w, rwidth =1. )\n\nplt.legend(loc = \"upper left\");\nplt.ylim([0,.75])\nplt.xlim([35, len(count_data)-20])\nplt.xlabel(\"days\")\nplt.ylabel(\"probability\");\n```\n\n### Interpretation\n\nRecall that the Bayesian methodology returns a *distribution*, hence we now have distributions to describe the unknown $\\lambda$'s and $\\tau$. What have we gained? Immediately we can see the uncertainty in our estimates: the more variance in the distribution, the less certain our posterior belief should be. We can also say what a plausible value for the parameters might be: $\\lambda_1$ is around 18 and $\\lambda_2$ is around 23. What other observations can you make? Look at the data again, do these seem reasonable? The distributions of the two $\\\\lambda$s are positioned very differently, indicating that it's likely there was a change in the user's text-message behaviour.\n\nAlso notice that the posterior distributions for the $\\lambda$'s do not look like any exponential distributions, though we originally started modelling with exponential random variables. They are really not anything we recognize. But this is OK. This is one of the benefits of taking a computational point-of-view. If we had instead done this mathematically, we would have been stuck with a very analytically intractable (and messy) distribution. Via computations, we are agnostic to the tractability.\n\nOur analysis also returned a distribution for what $\\tau$ might be. Its posterior distribution looks a little different from the other two because it is a discrete random variable, hence it doesn't assign probabilities to intervals. We can see that near day 45, there was a 50% chance the users behaviour changed. Had no change occurred, or the change been gradual over time, the posterior distribution of $\\tau$ would have been more spread out, reflecting that many values are likely candidates for $\\tau$. On the contrary, it is very peaked. \n\n###Why would I want samples from the posterior, anyways?\n\n\nWe will deal with this question for the remainder of the book, and it is an understatement to say we can perform amazingly useful things. For now, let's end this chapter with one more example. We'll use the posterior samples to answer the following question: what is the expected number of texts at day $t, \\; 0 \\le t \\le70$? Recall that the expected value of a Poisson is equal to its parameter $\\lambda$, then the question is equivalent to *what is the expected value of $\\lambda$ at time $t$*?\n\nIn the code below, we are calculating the following: Let $i$ index samples from the posterior distributions. Given a day $t$, we average over all possible $\\lambda_i$ for that day $t$, using $\\lambda_i = \\lambda_{1,i}$ if $t \\lt \\tau_i$ (that is, if the behaviour change hadn't occurred yet), else we use $\\lambda_i = \\lambda_{2,i}$. \n\n\n\n\n\n___________________\n\n\n```\nfigsize( 12.5, 4)\n# tau_samples, lambda_1_samples, lambda_2_samples contain\n# N samples from the corresponding posterior distribution\nN = tau_samples.shape[0]\nexpected_texts_per_day = np.zeros(n_count_data)\nfor day in range(0, n_count_data):\n # ix is a bool index of all tau samples corresponding to\n # the switchpoint occurring prior to value of 'day'\n ix = day < tau_samples\n # Each posterior sample corresponds to a value for tau.\n # for each day, that value of tau indicates whether we're \"before\" (in the lambda1 \"regime\")\n # or \"after\" (in the lambda2 \"regime\") the switchpoint.\n # by taking the posterior sample of lambda1/2 accordingly, we can average\n # over all samples to get an expected value for lambda on that day.\n # As explained, the \"message count\" random variable is Poisson distributed, \n # and therefore lambda (the poisson parameter) is the expected value of \"message count\"\n expected_texts_per_day[day] = (lambda_1_samples[ix].sum() \n + lambda_2_samples[~ix].sum() ) /N\n\n \nplt.plot( range( n_count_data), expected_texts_per_day, lw =4, color = \"#E24A33\" )\nplt.xlim( 0, n_count_data )\nplt.xlabel( \"Day\" )\nplt.ylabel( \"Expected # text-messages\" )\nplt.title( \"Expected number of text-messages received\")\n#plt.ylim( 0, 35 )\nplt.bar( np.arange( len(count_data) ), count_data, color =\"#348ABD\", alpha = 0.5,\n label=\"observed texts per day\")\n\nplt.legend(loc=\"upper left\");\n```\n\nOur analysis shows strong support for believing the user's behavior did change ($\\lambda_1$ would have been close in value to $\\lambda_2$ had this not been true), and the change was sudden rather then gradual (demonstrated by $\\tau$'s strongly peaked posterior distribution). We can speculate what might have caused this: a cheaper text-message rate, a recent weather-2-text subscription, or a new relationship. (The 45th day corresponds to Christmas, and I moved away to Toronto the next month leaving a girlfriend behind.)\n\n\n##### Exercises\n\n1\\. Using `lambda_1_samples` and `lambda_2_samples`, what is the mean of the posterior distributions of $\\lambda_1$ and $\\lambda_2$?\n\n\n```\n#type your code here.\n```\n\n2\\. What is the expected percentage increase in text-message rates? `hint:` compute the mean of `lambda_1_samples/lambda_2_samples`. Note that quantity is very different from `lambda_1_samples.mean()/lambda_2_samples.mean()`.\n\n\n```\n#type your code here.\n```\n\n3\\. Looking at the posterior distribution graph of $\\tau$, why do you think there is a small number of posterior $\\tau$ samples near 0? `hint:` Look at the data again.\n\n4\\. What is the mean of $\\lambda_1$ **given** we know $\\tau$ is less than 45. That is, suppose we have new information as we know for certain that the change in behaviour occurred before day 45. What is the expected value of $\\lambda_1$ now? (You do not need to redo the PyMC part, just consider all instances where `tau_trace<45`. )\n\n\n```\n#type your code here.\n```\n\n### References\n\n\n- [1] Gelman, Andrew. N.p.. Web. 22 Jan 2013. .\n- [2] Norvig, Peter. 2009. [*The Unreasonable Effectiveness of Data*](http://www.csee.wvu.edu/~gidoretto/courses/2011-fall-cp/reading/TheUnreasonable EffectivenessofData_IEEE_IS2009.pdf).\n- [3] Patil, A., D. Huard and C.J. Fonnesbeck. 2010. \nPyMC: Bayesian Stochastic Modelling in Python. Journal of Statistical \nSoftware, 35(4), pp. 1-81. \n- [4] Jimmy Lin and Alek Kolcz. Large-Scale Machine Learning at Twitter. Proceedings of the 2012 ACM SIGMOD International Conference on Management of Data (SIGMOD 2012), pages 793-804, May 2012, Scottsdale, Arizona.\n- [5] Cronin, Beau. \"Why Probabilistic Programming Matters.\" 24 Mar 2013. Google, Online Posting to Google . Web. 24 Mar. 2013. .\n\n\n```\nfrom IPython.core.display import HTML\ndef css_styling():\n styles = open(\"../styles/custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()\n```\n\n\n\n\n\n\n\n\n\n\n```\n\n```\n", "meta": {"hexsha": "06b3f005a51226a9b5bbd7ca83daa6ab4ad09650", "size": 406359, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter1_Introduction/Chapter1_Introduction.ipynb", "max_stars_repo_name": "mathisonian/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_stars_repo_head_hexsha": "74e869bac9764f8919a4db7369b5910ebdf21a7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-09-21T20:26:20.000Z", "max_stars_repo_stars_event_max_datetime": "2016-09-21T20:26:20.000Z", "max_issues_repo_path": "Chapter1_Introduction/Chapter1_Introduction.ipynb", "max_issues_repo_name": "mathisonian/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_issues_repo_head_hexsha": "74e869bac9764f8919a4db7369b5910ebdf21a7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter1_Introduction/Chapter1_Introduction.ipynb", "max_forks_repo_name": "mathisonian/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_forks_repo_head_hexsha": "74e869bac9764f8919a4db7369b5910ebdf21a7a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 393.3775411423, "max_line_length": 113544, "alphanum_fraction": 0.9039273155, "converted": true, "num_tokens": 10771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. YES", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.23230919981291934}} {"text": "# Tutorial 17 - LSTM with Keras and TensorFlow\n\n## Setup GPU & TensorFlow\n\n\n```python\n# Choose to the GPU number you want to use,\n# otherwise you will get a Python error\n# e.g. USE_GPU = 4\nUSE_GPU = X # YOUR_CHOICE\n```\n\n\n```python\n# Import TensorFlow \nimport tensorflow as tf\n\n# Print the installed TensorFlow version\nprint(f'TensorFlow version: {tf.__version__}\\n')\n\n# Get all GPU devices on this server\ngpu_devices = tf.config.list_physical_devices('GPU')\n\n# Print the name and the type of all GPU devices\nprint('Available GPU Devices:')\nfor gpu in gpu_devices:\n print(' ', gpu.name, gpu.device_type)\n \n# Set only the GPU specified as USE_GPU to be visible\ntf.config.set_visible_devices(gpu_devices[USE_GPU], 'GPU')\n\n# Get all visible GPU devices on this server\nvisible_devices = tf.config.get_visible_devices('GPU')\n\n# Print the name and the type of all visible GPU devices\nprint('\\nVisible GPU Devices:')\nfor gpu in visible_devices:\n print(' ', gpu.name, gpu.device_type)\n \n# Set the visible device(s) to not allocate all available memory at once,\n# but rather let the memory grow whenever needed\nfor gpu in visible_devices:\n tf.config.experimental.set_memory_growth(gpu, True)\n```\n\n## LSTM with Keras and TensorFlow\n\nSo far, the neural networks that we have examined have always had _forward connections_, meaning that each hidden layer always connects to the next hidden layer, and the final hidden layer always connects to the output layer. This manner to connect layers is the reason that these networks are called “feedforward”. \n\n### LEARNING OBJECTIVES\n\n* understand the anatomy of LSTM networks\n* learn the available recurrent layer types in TensorFlow\n* learn how to use recurrent layers sequence prediction\n\n__Recurrent neural networks__ are more flexible, as backward connections are also allowed. A recurrent connection links a neuron in a layer to either a previous layer or the neuron itself. Most recurrent neural network architectures maintain state in the recurrent connections. Feedforward neural networks don’t maintain any state. A recurrent neural network’s state acts as a sort of short-term memory for the neural network. Consequently, a recurrent neural network will not always produce the same output for a given input.\n\nRecurrent neural networks do not force the connections to flow only from one layer to the next, from input layer to output layer.\n\nA recurrent connection occurs when a connection is formed between a neuron and one of the following other types of neurons:\n\n* The neuron itself\n* A neuron on the same level\n* A neuron on a previous level\n\nRecurrent connections can never target the input neurons or the bias neurons. \nThe processing of recurrent connections can be challenging. Because the recurrent links create endless loops, the neural network must have some way to know when to stop. A neural network that entered an endless loop would not be useful. To prevent endless loops, we can calculate the recurrent connections with the following three approaches:\n\n* Context neurons\n* Calculating output over a fixed number of iterations\n* Calculating output until neuron output stabilizes\n\nThe __context neuron__ is a special neuron type that remembers its input and provides that input as its output the next time that we calculate the network. For example, if we gave a context neuron 0.5 as input, it would output 0. Context neurons always output 0 on their first call. However, if we gave the context neuron a 0.6 as input, the output would be 0.5. We never weight the input connections to a context neuron, but we can weight the output from a context neuron just like any other connection in a network. \n\nContext neurons allow us to calculate a neural network in a single feedforward pass. Context neurons usually occur in layers. A layer of context neurons will always have the same number of context neurons as neurons in its source layer, as demonstrated by Figure 1.CTX.\n \n \n \n \n\n**Figure 1.CTX: Context Layers**\n\n\nAs you can see from the above layer, two hidden neurons that are labeled hidden 1 and hidden 2 directly connect to the two context neurons. The dashed lines on these connections indicate that these are not weighted connections. These weightless connections are never dense. If these connections were dense, hidden 1 would be connected to both hidden 1 and hidden 2. However, the direct connection simply joins each hidden neuron to its corresponding context neuron. The two context neurons form dense, weighted connections to the two hidden neurons. Finally, the two hidden neurons also form dense connections to the neurons in the next layer. The two context neurons would form two connections to a single neuron in the next layer, four connections to two neurons, six connections to three neurons, and so on.\n\nYou can combine context neurons with the input, hidden, and output layers of a neural network in many different ways. \n\n### Understanding LSTM\n\nLong Short Term Neural Network (LSTM) are a type of recurrent unit that is often used with deep neural networks.[[Cite:hochreiter1997long]](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.676.4320) For TensorFlow, LSTM can be thought of as a layer type that can be combined with other layer types, such as dense. LSTM makes use two activation function types internally. \n\nThe first type of activation function is the sigmoid. This activation function type is used form gates inside of the unit. The sigmoid function is given by the following equation:\n\n$ \\mbox{S}(t) = \\frac{1}{1 + e^{-t}} $\n\nThe second type of transfer function is the hyperbolic tangent (tanh) function. This function is used to scale the output of the LSTM, similarly to how other activation functions have been used in this course. \n\nBoth of these two functions compress their output to a specific range. For the sigmoid function, this range is 0 to 1. For the hyperbolic tangent function, this range is -1 to 1.\n\n\n__LSTM maintains an internal state and produces an output.__\n\nThe following diagram shows an LSTM unit over three time slices: the current time slice (t), as well as the previous (t-1) and next (t+1) slice, as demonstrated by Figure 2.LSTM.\n\n**Figure 2.LSTM: LSTM Layers**\n\n\n\nThe values $\\hat{y}$ are the output from the unit, the values ($x$) are the input to the unit and the values $c$ are the context values. Both the output and context values are always fed to the next time slice. The context values allow the network to maintain state between calls. Figure 10.ILSTM shows the internals of a LSTM layer.\n\n**Figure 3.ILSTM: Inside a LSTM Layer**\n\n\n\nLSTM is made up of three gates:\n\n* Forget Gate ($f_t$) - Controls if/when the context is forgotten. (MC)\n* Input Gate ($i_t$) - Controls if/when a value should be remembered by the context. (M+/MS)\n* Output Gate ($o_t$) - Controls if/when the remembered value is allowed to pass from the unit. (RM)\nMathematically, the above diagram can be thought of as the following:\n**These are vector values.**\nFirst, calculate the forget gate value. This gate determines if the short term memory is forgotten. The value $b$ is a bias, just like the bias neurons we saw before. Except LSTM has a bias for every gate: $b_t$, $b_i$, and $b_o$.\n\n$ f_t = S(W_f \\cdot [\\hat{y}_{t-1}, x_t] + b_f) $\n\n$ i_t = S(W_i \\cdot [\\hat{y}_{t-1},x_t] + b_i) $\n\n$ \\tilde{C}_t = \\tanh(W_C \\cdot [\\hat{y}_{t-1},x_t]+b_C) $\n\n$ C_t = f_t \\cdot C_{t-1}+i_t \\cdot \\tilde{C}_t $\n\n$ o_t = S(W_o \\cdot [\\hat{y}_{t-1},x_t] + b_o ) $\n\n$ \\hat{y}_t = o_t \\cdot \\tanh(C_t) $\n\n\n### Recurrent layers available in TensorFlow \n\nBuilt-in RNN layers: a simple example\nThere are three built-in RNN layers in Keras:\n\n[keras.layers.SimpleRNN](https://www.tensorflow.org/api_docs/python/tf/keras/layers/SimpleRNN), a fully-connected RNN where the output from previous timestep is to be fed to next timestep.\n\n[keras.layers.GRU](https://www.tensorflow.org/api_docs/python/tf/keras/layers/GRU), first proposed in Cho et al., 2014.\n\n[keras.layers.LSTM](https://www.tensorflow.org/api_docs/python/tf/keras/layers/LSTM), first proposed in Hochreiter & Schmidhuber, 1997.\n\n\n#### Stateful vs. Stateless LSTM\n\n\n1. **Stateless**: LSTM updates parameters on **batch 1** and then initiates cell states (meaning - memory, usually with zeros) for **batch 2** \n2. **Stateful**: it uses batch 1 last output cell sates as initial states for batch 2.\n\n#### When to use which?\n----------------\n\n- When sequences in batches are related to each other (e.g. prices of one commodity), we should better use **stateful** mode\n- Else, when one sequence represents a complete sentence, we should go with **stateless** mode\n\n### Simple LSTM Example in TensorFlow\n\nThe following code creates the LSTM network. This is an example of RNN classification. The following code trains on a data set (x) with a max sequence size of 6 (columns) and 6 training elements (rows)\n\n\n```python\nfrom tensorflow.keras.preprocessing import sequence\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Embedding\nfrom tensorflow.keras.layers import LSTM\nimport numpy as np\n```\n\n\n```python\nmax_features = 4 # 0,1,2,3 (total of 4)\nx = [\n [[0],[1],[1],[0],[0],[0]],\n [[0],[0],[0],[2],[2],[0]],\n [[0],[0],[0],[0],[3],[3]],\n [[0],[2],[2],[0],[0],[0]],\n [[0],[0],[3],[3],[0],[0]],\n [[0],[0],[0],[0],[1],[1]]\n]\nx = np.array(x,dtype=np.float32)\n\n\nprint (f\"Input size is: {x.shape[0]} example sequences and {x.shape[1]} sequence length\")\ny = np.array([1,2,3,2,3,1],dtype=np.int32)\n\n# Convert y2 to dummy variables\ny2 = np.zeros((y.shape[0], max_features),dtype=np.float32)\ny2[np.arange(y.shape[0]), y] = 1.0\nprint('One-hot encoded representation for the outputs:', y2)\n```\n\n\n```python\nprint('Build model...')\nmodel = Sequential()\nmodel.add(LSTM(units =128, dropout=0.2, recurrent_dropout=0.2,stateful=False,name ='first_lstm', input_shape=(None,1))) # inputs: A 3D tensor with shape [batch, timesteps, feature].\nmodel.add(Dense(4, activation='sigmoid'))\nmodel.summary()\n```\n\n\n```python\n# try using different optimizers and different optimizer configs\nmodel.compile(loss='binary_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n\nprint('Train...')\nmodel.fit(x,y2,epochs=20)\npred = model.predict(x)\npredict_classes = np.argmax(pred,axis=1)\nprint(\"Predicted classes: {}\",predict_classes)\nprint(\"Expected classes: {}\",predict_classes)\n```\n\n\n```python\nfirst_layer = model.get_layer('first_lstm' )\nfirst_layer.states\n```\n\n\n```python\ndef runit(model, inp):\n inp = np.array(inp,dtype=np.float32)\n pred = model.predict(inp)\n return np.argmax(pred[0])\n\nprint( runit( model, [[[0],[0],[0],[0],[0],[1]]] ))\n\n```\n\nHow to cumpute the number of parameters for a LSTM layer?\n--------------------------------\n\n1. To decide how to handle the memory each LSTM Cell has 3 Gates: \n - input (what to let in), \n - forget (what to forget) and \n - output (what to write to the output)\n2. LSTM **Cell State** is its **memory**\n3. LSTM Hidden State is equivalent to the Cell output:\n - lstm_hidden_state_size (number of neurons = memory cells) = lstm_outputs_size\n4. Parameters:\n - weights for the inputs (lstm_inputs_size)\n - weights for the outputs (lstm_outputs_size)\n - bias variable\n5. Result from previous point - for all 3 Gates and for Cell State ( = 4) \n \n \\begin{equation}\n \\textbf{PARAMETERS} = \\textbf4 \\times \\textbf{ LSTM outputs size} \\times (\\textbf{weights LSTM inputs size} + \\textbf{weights LSTM outputs size} + 1 \\textbf{ bias variable})\n \\end{equation}\n\n## Further reading on LSTM/recurrent neural networks.\n\n* [Understanding LSTM Networks](http://colah.github.io/posts/2015-08-Understanding-LSTMs/)\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "b3bd82bcc7535757c439a0ab3b7cdadc9f0dc3ab", "size": 16005, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Week 17/17 - LSTM with Keras and TensorFlow.ipynb", "max_stars_repo_name": "qiaw99/Deep-Learning-for-Geographical-Data", "max_stars_repo_head_hexsha": "029399e8110fc2fd54786add25ebd72c09880e59", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-02-16T04:35:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T13:26:51.000Z", "max_issues_repo_path": "Week 17/17 - LSTM with Keras and TensorFlow.ipynb", "max_issues_repo_name": "qiaw99/Deep-Learning-for-Geographical-Data", "max_issues_repo_head_hexsha": "029399e8110fc2fd54786add25ebd72c09880e59", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Week 17/17 - LSTM with Keras and TensorFlow.ipynb", "max_forks_repo_name": "qiaw99/Deep-Learning-for-Geographical-Data", "max_forks_repo_head_hexsha": "029399e8110fc2fd54786add25ebd72c09880e59", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.2567567568, "max_line_length": 825, "alphanum_fraction": 0.6228053733, "converted": true, "num_tokens": 2913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.43014734858584297, "lm_q1q2_score": 0.23184219694033364}} {"text": "**Report Submission Information (must be completed before submitting report!)**\n\n* Student 1 Full Name and Number : \n* Student 2 Full Name and Number : \n* Workshop day : e.g., Wednesday\n* Workshop time : e.g., 12pm \n\n# Workshop 1 – Optimisation [2 weeks] \n\n## Objectives:\n\n* Learn how to formulate optimisation problems in practice.\n* Familiarise yourself with practical software tools used for optimisation.\n* Solve optimisation problems using Python Scipy and Matlab.\n* Connect theoretical knowledge and practical usage by doing it yourself.\n\n> __Common objectives of all workshops:__\n> Gain hands-on experience and learn by doing! Understand how theoretical knowledge discussed in lectures relates to practice. Develop motivation for gaining further theoretical and practical knowledge beyond the subject material.\n\n## Overview:\nAnother name for the field of “Optimisation” is “Mathematical Optimisation.” As the name indicates optimisation is an area of applied mathematics. It is possible to study optimisation entirely from a mathematical perspective. However, engineers are interested in solving real-world problems in a principled way. Many engineering problems can be and are formulated as optimisation problems. In those cases, mathematical optimisation provides a solid theoretical foundation for solving them in a principled way.\n\nIn this workshop, you will learn how to formulate and solve optimisation problems in practice. This will give you a chance to connect theoretical knowledge and practical usage by doing it yourself. You will familiarise yourself with practical optimisation tools for Python. These are chosen completely for educational reasons (simplicity, accessibility, cost). While the underlying mathematics is timeless, optimisation software evolves with time, and can be diverse. Fortunately, once you learn one or two, it should be rather easy to learn others now and in the future, because software designers often try to make it user friendly and take into account what people already know. \n\n> In the future, you should consider and learn serious optimisation software for scalability and reliability. They can be complex and/or expensive but they get the job done for serious engineering. Teaching such software takes too much time and is beyond the scope of this subject.\n\n## Workshop Preparation: [before you arrive to the lab]\n\nYou can come to the workshops as you are or you can prepare beforehand to learn much more! \nWe will give you a lot of time to finish the tasks but those are the bare minimums. Just like in the lectures, the topics we cover in the workshops are quite deep and we can only do so much in two hours. There is much more to learn and coming prepared to the workshop is one of the best ways to gain more knowledge! For example, there are a few questions in each workshop which you can answer beforehand.\n\n> __Self-learning__ is one of the most important skills that you should acquire as a student. Today, self-learning is much easier than it used to be thanks to a plethora of online resources.\nFor this workshop, start by exploring the resource mentioned in the preparation steps below.\n\n### Workshop Preparation Steps:\n\n1. Common step for all workshops: read the Workshop Manual (Jupyter Notebook) beforehand!\n2. Review relevant lecture slides on optimisation.\n3. Read/check relevant reading material and links from LMS/Resources-Reading\n4. Check the embedded links below hints and background.\n5. _\\[optional\\]_ _You can start with workshop tasks and questions_\n\n\n## Tasks and Questions:\n\nFollow the procedures described below, perform the given tasks and answer the workshop questions __on the Python notebook itself!__ The marks associated with each question are clearly stated. Keep your answers to the point and complete to get full marks! Ensure that your code is clean and appropriately commented. \n\n__The resulting notebook will be your Workshop Report!__\n\n> __The goal is to learn__, NOT blindly follow the procedures in the fastest possible way! __Do not simply copy-paste answers (from Internet, friends, etc.). You can and should use all available resources but only to develop your own understanding. If you copy-paste, you will pay the price in the final exam!__\n\n# Section 1: Convex Functions\n\nRemember the definition of convex and concave functions from lecture slides. Functions are mathematical objects but they are used in engineering in very practical ways, for example, to represent the relationship between two quantities. Let's draw a function!\n\n\n```python\n%matplotlib notebook\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# define function f(x)\ndef f(x):\n return 3*(x-1)**2\n\n# define x and y\nx = np.linspace(-20, 20, 100) # 100 equally spaced points on interval [-20,20]\ny = f(x) # call function f(x) and set y to the function's return value\n\n# Plot the function y=f(x)\nplt.plot(x,y)\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title('$y=3(x-1)^2$')\nplt.show()\n```\n\n\n \n\n\n\n\n\n\n### Question 1.1. (1 pt)\nPlot one concave and one nonconvex functions of your choosing (preferably in 3D). Provide their formulas below.\n\n\n```python\n''' Answer as code here '''\nfrom mpl_toolkits.mplot3d.axes3d import Axes3D\nfrom matplotlib import cm\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfig = plt.figure()\n# Plot convex figure\nax = fig.add_subplot(1, 2, 1, projection='3d')\nX=np.arange(-10,10,1)\nY=np.arange(-10,10,1)\nX, Y = np.meshgrid(X, Y)\nZ = (2*X)**2 +(2*Y)**2\nsurf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1,\ncmap=cm.jet,linewidth=0.01, antialiased=False)\nax.set_zlim3d(0,1000)\n\n# Plot non-convex figure\nax = fig.add_subplot(1, 2, 2, projection='3d')\nX=np.arange(-10,10,1)\nY=np.arange(-10,10,1)\nX, Y = np.meshgrid(X, Y)\nZ = -(2*X)**2 +(2*Y)**2\nsurf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1,\ncmap=cm.jet,linewidth=0.01, antialiased=False)\nax.set_zlim3d(-1000,0)\nfig.colorbar(surf, shrink=0.5, aspect=5)\nplt.show()\n\n```\n\n**Answer as text here**\n\nConvex Formula:\n\n$$ z = 2x^2 + 2y^2$$\n\nNon-convex Formula:\n\n$$ z = -2x^2 + 2y^2$$\n\n### Question 1.2. (1 pts)\nHow would you determine whether a single or multi-variate continuously differentiable function is convex or not? \n> Note that the question becomes very tricky if you have a **parametric** multivariate polynomials of degree four or higher! \n\n> *[Optional]* An interesting paper (for those who wish to go deeper) http://web.mit.edu/~a_a_a/Public/Publications/convexity_nphard.pdf \n\n**Answer as text here**\n\nSingle continously differential function is convex if and only if:\n\\begin{equation}\n\\frac{\\partial^2 f}{\\partial^2 f} \\geq 0 \\\\\n\\frac{\\partial^2 f}{\\partial^2 f} > 0 \\Rightarrow strictly \\ convex (slope \\ increasing)\n\\end{equation}\n\nMulti-variate continously differential function is convex if and only if eigin values of Hessian matrix is positive:\n$$\\triangledown^2 f(x) = H = Hessian \\ matrix $$\n\n\n### Question 1.3. (2 pts)\nWhy are convex optimisation problems considered to be easy to solve? Consider optimality conditions of unconstrained functions in your answer. Plot first and second order derivative functions of the concave and non-convex functions you have chosen above (as part of Question 1.1) to further support your argument.\n\n**Answer as text here**\n\nConvex optimisation problem are easier to solve because of existance of global maximum or minimum.\n\n\n```python\n''' Answer as code here '''\nfrom mpl_toolkits.mplot3d.axes3d import Axes3D\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nx = Symbol('x')\ny = Symbol('y')\nz = (2*x )**2 +(2*y)**2\ndzdx = z.diff(x)\ndzdy = z.diff(y)\ndiv_z = [dzdx, dzdy]\ndzdxx = dzdx.diff(x)\ndzdxy = dzdx.diff(y)\ndzdyx = dzdy.diff(x)\ndzdyy = dzdy.diff(y)\ndiv2_z = [[dzdxx, dzdxy],[dzdyx, dzdyy]]\n\nfig_2 = plt.figure()\nax_1 = fig_2.add_subplot(1,2,1, projection='3d')\nX=np.arange(-10,10,1)\nY=np.arange(-10,10,1)\nX,Y = np.meshgrid(X,Y)\n# Z = div_z[0]+div_z[1]\nZ = (2*X)**2 +(2*Y)**2\nsurf = ax_1.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet,linewidth=0.01, antialiased=False)\nZ = 8*X\nsurf = ax_1.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.Purples,linewidth=0.01, antialiased=False)\nZ = 8*Y\nsurf = ax_1.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.Oranges,linewidth=0.01, antialiased=False)\nZ = 8+0*X*Y\nsurf = ax_1.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.Oranges,linewidth=0.01, antialiased=False)\n\nax_1.set_zlim3d(0,1000)\nplt.show()\n\nax_2 = fig_2.add_subplot(122, aspect='auto')\nX=np.arange(-10,10,1)\nY=np.arange(-10,10,1)\nX, Y = np.meshgrid(X, Y)\nZ = -(2*X)**2 -div_z[1]\n#surf = ax_2.plot_surface(X, Y, Z, rstride=1, cstride=1,cmap=cm.jet,linewidth=0.01, antialiased=False)\nax.set_zlim3d(-1000,0)\nfig.colorbar(surf, shrink=0.5, aspect=5)\n\n```\n\n# Section 2: Unconstrained Optimisation\n\n## 2.1 _Example_. Aloha communication protocol\n\n\n\n**Aloha** is a well-known random access or _MAC_ (Media/multiple Access Control) communication protocol. It enables multiple nodes sharing a broadcast channel without any additional signaling in a distributed manner. Unlike _FDMA_ or _TDMA_ (frequency or time-division multiple access), the channel is not divided into segments beforehand and collisions of packets due to simultaneous transmissions by nodes are allowed. In slotted Aloha, the nodes can only transmit at the beginning of time slots, which are kept by a global/shared clock. See [Aloha](https://en.wikipedia.org/wiki/ALOHAnet#Slotted_ALOHA) for further background information.\n\n### Slotted Aloha Efficiency\n\nFor an $N$-node slotted Aloha system, where each node transmits with a probability $p$, the throughput of the system is given by\n$$ S(p) = N p (1-p)^{N-1}$$\n\n### Question 2.1. (2 pts)\nFormally define the optimisation problem to find the optimal probability $p$ that maximises the throughput. Clearly identify the objective and decision variable(s). Is the objective convex or concave? Show through derivation. \n\nNote that, there is the constraint $0 \\leq p \\leq 1$ on probability $p$ but we will ignore it for now.\n\n**Answer as text here** \n\nOptimization problem:\n$$ \\max_p S(p) = Np(1-P)^{N-1}$$ where $S(p)$ is objective and $p$ is decision variable.\n\nConcave or Convex:\n\\begin{equation}\n\\begin{split}\nS^{'}(p) &= \\frac{\\partial}{\\partial p}Np(1 - p)^{N - 1} \\\\\n&= N(1-p)^{N-1} + Np(N-1)(1-p)^{N-2}(-1) \\\\\n&= N(1-p)^{N-2}(1-p - p(N-1)) \\\\\n&= N(1-p)^{N-2}(1-p - pN + p)) \\\\\n&= N(1-p)^{N-2}(1-pN)\n\\end{split}\n\\end{equation}\n\n\\begin{equation}\n\\begin{split}\nS^{''}(p) &= \\frac{\\partial}{\\partial p}S^{'}(p) \\\\\n&= N(N-2)(1-p)^{N-3}(-1)(1-pN)+ N(1-p)^{N-2}(-N) \\\\\n&= -N(1-p)^{N-3}((N-2)(1-pN) + N(1-p)) \\\\\n&= -N(1-p)^{N-3}(N-pN^2-2+2pN+N-pN) \\\\\n&= -N(1-p)^{N-3}(2N-pN^2-2+pN) \\\\\n&= N(1-p)^{N-3}(p(N^2-N)+2-2N) \\\\\n&\\Rightarrow \\ convex \\ or \\ concave \\ depends \\ on \\ vlaue \\ of \\ p \\ and \\ N\n\\end{split}\n\\end{equation}\n\n\n### Question 2.2. (2 pts)\nPlot the performance function and its derivative for $N=10$ nodes. Is the objective function convex or concave? Determine using mathematical methods. Investigate the property of the derivative function of the objective. What do you call such functions?\n\n**Answer as text here**\n\nConcave or Convex with $N=10$:\n\\begin{equation}\n\\begin{split}\nS^{''}(p) &= N(1-p)^{N-3}(p(N^2-N)+2-2N) \\\\\n&= 10(1-p)^{7}(90p-18)\n\\end{split}\n\\end{equation}\n$\\Rightarrow$ the function is quasi-convex since it depends on $p$ for above value to be positive or negative.\n\n\n\n```python\n''' Answer as code here '''\n```\n\n\n\n\n ' Answer as code here '\n\n\n\n### Question 2.3. (2 pts)\nFind the optimal probability $p$ for $N=10$ nodes. Use an appropriate package from [Scipy](https://docs.scipy.org/doc/scipy/reference/optimize.html). Cross-check your answer with a mathematical formula that you should derive by hand. \n\n\n\n```python\nfrom scipy import optimize\n''' Answer as code here '''\n```\n\n\n\n\n ' Answer as code here '\n\n\n\n**Answer as text here**\n\n## 2.2 Gradient Descent Algorithms\n\n### Question 2.4. (10 pts)\nWrite your own gradient algorithm (with constant step size) to solve the problem\n$$ \\min_x x^T Q x + r^T x,$$\nwhere $x,\\, r \\in \\mathbb{R}^2$ and $Q$ is a $2\\times 2$ positive definite matrix of your choice. Cross-check your answers using one of the standard optimisation packages, e.g. scipy or cvxpy.\n\n1. If Q is positive definite, then what type of optimisation problem is this? Give your answer using mathematical tools learned in classroom. Would anything change if $Q$ were not positive definite? Plot both cases and comment. \n2. Focusing on positive definite $Q$, what happens if you choose your fixed step size too large or too small? Observe and comment.\n3. Choose $Q$ in such a way that is has a low [condition number] (https://www.encyclopediaofmath.org/index.php/Condition_number), [see also.](https://calculus.subwiki.org/wiki/Gradient_descent_with_constant_learning_rate_for_a_quadratic_function_of_multiple_variables) Next, choose a $Q$ with a high condition number. Compare the performance of your algorithm in both cases, and comment. \n4. Now, solve both versions of the problem using (b) diminishing step size (c) Armijo rule/wolf test (line search). Discuss stopping criteria for all variants. \n5. Plot your trajectories clearly showing the iterations of the gradient algorithm. You should also show either by displaying the level sets of the objective or the objective function itself (if resorting to a 3D plot). \n\n**Answer as text here**\n**Solution** at: https://en.wikipedia.org/wiki/Gradient_descent\n\nQuestion: 2.4.1\n\nSince $Q$ is positive definite, then $$x^TQx>0 \\Rightarrow convex \\ optimization$$ if $Q$ is not positive difinite then the problem is not convex optimization.\n\nQuestion: 2.4.2,\n\nIf the fixed step size $\\alpha$ is too small, it will take long time to converge and if the $\\alpha$ is too big, we may miss the mimum point.\n\n\n\n```python\n''' Answer as code here '''\n```\n\n\n\n\n ' Answer as code here '\n\n\n\n### Question 2.5. (2 pts)\nChoose one of the versions of the problem and algorithms in **Question 2.4** that finds the correct solution.\n\n1. Use objective function itself or a norm of its gradient as a descent (Lyapunov) function that establishes the convergence of the solution algorithm $A(x)$. Plot the value of the chosen descent function versus the trajectory or steps.\n2. Calculate and plot $||x(n)-x^*||$ over iterations $n=0,\\ldots$, to establish that your solution algorithm leads to a pseudo-contraction.\n\n\n**Answer as text here**\n\n\n```python\n''' Answer as code here '''\n```\n\n\n\n\n ' Answer as code here '\n\n\n\n# Section 3: Constrained Optimisation\n\n## 3.1 _Example_. Waterfilling in Communications\n\n_by Robert Gowers, Roger Hill, Sami Al-Izzi, Timothy Pollington and Keith Briggs.\nFrom the book by Boyd and Vandenberghe, Convex Optimization, Example 5.2 page 245._\n\n$$\\min_{x} \\sum_{i=1}^N -\\log(\\alpha_i + x_i)$$ \n\n$$\\text{subject to } x_i \\geq 0, \\; \\forall i, \\text{ and } \\sum_{i=1}^N x_i = P $$\n\nThis problem arises in information/communication theory, in allocating power to a\nset of $n$ communication channels. The variable $x_i$ represents the transmitter power\nallocated to the _i-th_ channel, and $\\log(\\alpha_i + x_i)$ gives the capacity or communication rate of the channel, where $\\alpha_i>0$ represents the floor above the baseline at which power can be added to the channel. The problem is to allocate a total power of one to the channels,\nin order to maximize the total communication rate.\n\nThis can be solved using a classic [water filling algorithm](https://en.wikipedia.org/wiki/Water_filling_algorithm). \n\n\n\n\n### Question 3.1. (4 pts)\n\n1. (1 pt) Is the problem in Example 3.1 convex? Formally explain/argue why or why not. What does this imply regarding the solution? \n2. (2 pts) Solve the problem above for $N=8$ and a randomly chosen $\\alpha$ vector. You can use for example _Cvxpy_ package. Cross-check your answer with another software (package), e.g. Matlab or Scipy. \n3. (1 pt) Write the Lagrangian, KKT conditions, and find numerically the Lagrange multipliers associated with the solution (using the software package/function). Which constraints are active? Explain and discuss briefly. \n\n**Answer as text here**\n\n**Solution** at https://www.cvxpy.org/examples/applications/water_filling_BVex5.2.html \n\nQuestion 3.1.1\n\nConvex Optimization:\n\\begin{equation}\n\\begin{split}\nf(x_i) &= \\sum_{i=1}^N - \\log(\\alpha_i + x_i) \\\\\n\\Rightarrow f^{'}(x_i) &= \\frac{\\partial}{\\partial x_i} \\sum_{i=1}^N - \\log(\\alpha_i + x_i) \n= -\\sum_{i=1}^N \\frac{1}{(\\alpha_i + x_i)ln(10)} \n= -\\sum_{i=1}^N \\frac{(\\alpha_i + x_i)^{-1}}{ln(10)} \\\\\n\\end{split}\n\\end{equation}\n\n\\begin{equation}\n\\begin{split}\n\\Rightarrow f^{''}(x_i) = -\\sum_{i=1}^N (-1) \\frac{(\\alpha_i + x_i)^{-2}}{ln(10)} \n= -\\sum_{i=1}^N \\frac{1}{(\\alpha_i + x_i)^2 ln(10)}\n\\end{split}\n\\end{equation}\nSince both $x_i, \\alpha_i > 0$, $\\Rightarrow convex \\ optimization \\ problem$.\n\nQuestion 3.1.3\n\nLagrangian condition:\n\\begin{equation}\n\\mathcal{L}(x, \\lambda, \\nu) = f_0 (x) + \\sum_{i=1}^M \\lambda_i f_i(x) + \\sum_{i=1}^N \\nu_i h_i(x) \\\\\n\\Rightarrow \\mathcal{L}(x, \\lambda, \\nu) = \\sum_{i=1}^N -log(\\alpha_i + x_i) - \\sum_{i=1}^N \\lambda_i x_i + \\sum_{i=1}^N \\nu_i(x_i - P)\n\\end{equation}\n\nKKT condition:\n\\begin{equation}\nx^* \\geq 0 \\\\\nx^* = P \\\\\n\\lambda* \\geq 0 \\\\\n\\lambda* x_i^* = 0, i=1,2..., N \\\\\n-\\frac{1}{(\\alpha_i + x_i^*)} - \\lambda^* + \\nu^* = 0, i=1,2..., N\n\\end{equation}\n\n\n\n```python\n''' Answer as code here '''\n#!/usr/bin/env python3\n# @author: R. Gowers, S. Al-Izzi, T. Pollington, R. Hill & K. Briggs\nimport numpy as np\nimport cvxpy as cp\n\ndef water_filling(n, a, sum_x=1):\n '''\n Boyd and Vandenberghe, Convex Optimization, example 5.2 page 145\n Water-filling.\n\n This problem arises in information theory, in allocating power to a set of\n n communication channels in order to maximise the total channel capacity.\n The variable x_i represents the transmitter power allocated to the ith channel,\n and log(α_i+x_i) gives the capacity or maximum communication rate of the channel.\n The objective is to minimise -∑log(α_i+x_i) subject to the constraint ∑x_i = 1\n '''\n\n # Declare variables and parameters\n x = cp.Variable(shape=n)\n alpha = cp.Parameter(n, nonneg=True)\n alpha.value = a\n\n # Choose objective function. Interpret as maximising the total communication rate of all the channels\n obj = cp.Maximize(cp.sum(cp.log(alpha + x)))\n\n # Declare constraints\n constraints = [x >= 0, cp.sum(x) - sum_x == 0]\n\n # Solve\n prob = cp.Problem(obj, constraints)\n prob.solve()\n if(prob.status=='optimal'):\n return prob.status, prob.value, x.value\n else:\n return prob.status, np.nan, np.nan\n \n# As an example, we will solve the water filling problem with 3 buckets, each with different α\nnp.set_printoptions(precision=3)\nbuckets = 3\nalpha = np.array([0.8, 1.0, 1.2])\n\nstat, prob, x = water_filling(buckets, alpha)\nprint('Problem status: {}'.format(stat))\nprint('Optimal communication rate = {:.4g} '.format(prob))\nprint('Transmitter powers:\\n{}'.format(x))\n\n```\n\n## 3.2 _Example_. Economic Dispatch in Power Generation\n\nThe problem is formulated as\n$$ \\min_P \\sum_{i=1}^N c_i P_i $$\n$$\\text{subject to } P_{i,max} \\geq P_i \\geq 0, \\; \\forall i, \\text{ and } \\sum_{i=1}^N P_i = P_{demand} $$\n\nHere, $P_1,\\ldots P_N$ are the power generated by Generators $1,\\ldots,N$, $c_i$ is the per-unit generation cost of the i-_th_ generator, and $P_{demand}$ is the instantaneous power demand that needs to be satisfied by aggregate generation. More complex formulations take into account transmission, generator ramp-up and down constraints, and reactive power among other things.\n\n### Question 3.2. (4 pts)\n\nLet us get inspired from generation in Victoria with $N=12$ biggest generators that have more than 200MW capacity. Choose their maximum generation randomly or from the Victoria generator report if you wish to be more realistic. Generate a random cost vector $c$ varying between $10-50$ AUD per MWh. _(Optionally, you can search and find how much different generation types cost if you are interested)._ Let the demand be $P_{demand}=5000MW$. \n\nSolve this simplified [economic dispatch](https://en.wikipedia.org/wiki/Economic_dispatch) problem defined above. The resulting [merit order](https://en.wikipedia.org/wiki/Merit_order) is the generation that would have been if there was no NEM (electricity market).\n\nMore about electricity market and generation at https://www.aemo.com.au/ See also this [NEM overview introductory document (right click to download)](./files/National_Electricity_Market_Fact_Sheet.pdf) and the [Victoria generator report as of January 2019](files/Generation_Information_VIC_January_2019.xlsx).\n\n1. Solve the problem using _cvxpy._ \n2. What type of an optimisation problem is this? Briefly explain.\n3. Formulate by hand the dual problem and solve it with _cvxpy._ Is there a duality gap? Explain briefly why or why not.\n4. Briefly comment on simplex algorithm and solve the problem using [Scipy and simplex algorithm.](https://docs.scipy.org/doc/scipy/reference/optimize.linprog-simplex.html) Compare your results.\n\n\n**Answer as text here**\n\n\n```python\n''' Answer as code here '''\n```\n\n\n\n\n ' Answer as code here '\n\n\n\n## 3.3 _Example_. Power Control in Wireless Communication\n\n *Adapted from Boyd, Kim, Vandenberghe, and Hassibi,* \"[A Tutorial on Geometric Programming](https://web.stanford.edu/~boyd/papers/pdf/gp_tutorial.pdf).\"\n\nThe [power control problem in wireless communications](http://winlab.rutgers.edu/~narayan/PAPERS/PC%20for%20Wireless%20Data.pdf) aims to minimise the total transmitter power available across $N$ trasmitters while concurrently achieving good (or a pre-defined minimum) performance. \n\nThe technical setup is as follows. Each transmitter $i$ transmits with a power level $P_i$ bounded below and above by a minimum and maximum level. The power of the signal received from transmitter $j$ at receiver $i$ is $G_{ij} P_{j}$, where $G_{ij} > 0$ represents the path gain (often loss) from transmitter $j$ to receiver $i$. The signal power at the intended receiver $i$ is $G_{ii} P_i$, and the interference power at receiver $i$ from other transmitters is given by $\\sum_{k \\neq i} G_{ik}P_k$. The (background) noise power at receiver $i$ is $\\sigma_i$. Thus, the _Signal to Interference and Noise Ratio (SINR)_ of the $i$th receiver-transmitter pair is\n\n$$ S_i = \\frac{G_{ii}P_i}{\\sum_{k \\neq i} G_{ik}P_k + \\sigma_i }. $$\n\nThe minimum SINR represents a performance lower bound for this system, $S^{\\text min}$. \n\nThe resulting optimisation problem is formulated as\n\n$$\n\\begin{array}{ll}\n\\min_{P} & \\sum_{i=1}^N P_i \\\\\n\\text{subject to} & P^{min} \\leq P_i \\leq P^{max}, \\; \\forall i \\\\\n& \\dfrac{G_{ii}P_i}{\\sigma_i + \\sum_{k \\neq i} G_{ik}P_k} \\geq S^{min} , \\; \\forall i \\\\\n\\end{array}\n$$\n\n### Question 3.3. (10 pts)\n\nLet $N=6$, $P^{min}=0.1$, $P^{max}=5$, $\\sigma=0.2$ (same for all). Create a random path loss matrix $G$, where off-diagonal elements are between $0.1$ and $0.9$ and the diagonal elements are equal to $1$. \n\n1. (2 pts) Write down the Langrangian and KKT conditions of this problem.\n2. (2 pts) Solve the problem first with $S^{min}=0$ using _cvxpy_. Plot the power levels and SINRs that you obtain. \n3. (2 pts) What happens if you choose an $S^{min}$ that is larger? Solve the problem again and document your results. What happens if you choose a very large $S^{min}$? Observe and comment. \n4. (4 pts) Solve the problem using a combination of active set and penalty function methods. Specifically, choose a penalty function to impose the $S^{min}$ constraint and use an active set method for $P^{min}$, $P^{max}$ power constraints. Choose tighter constraints to make the problem more interesting.\n\n**Answer as text here**\n\n\n```python\n''' Answer as code here '''\nimport cvxpy as cp\n\n# Create two scalar optimization variables.\nx = cp.Variable()\ny = cp.Variable()\nprint(x)\nprint(type(x))\n\"\"\"\n# Create two constraints.\nconstraints = [x + y == 1,\n x - y >= 1]\n\n# Form objective.\nobj = cp.Minimize((x - y)**2)\n\n# Form and solve problem.\nprob = cp.Problem(obj, constraints)\nprob.solve() # Returns the optimal value.\nprint(\"status:\", prob.status)\nprint(\"optimal value\", prob.value)\nprint(\"optimal var\", x.value, y.value)\n\"\"\"\n```\n\n var28\n \n\n\n\n\n\n '\\n# Create two constraints.\\nconstraints = [x + y == 1,\\n x - y >= 1]\\n\\n# Form objective.\\nobj = cp.Minimize((x - y)**2)\\n\\n# Form and solve problem.\\nprob = cp.Problem(obj, constraints)\\nprob.solve() # Returns the optimal value.\\nprint(\"status:\", prob.status)\\nprint(\"optimal value\", prob.value)\\nprint(\"optimal var\", x.value, y.value)\\n'\n\n\n\n## 3.4 (_Optional_ Bonus, 10 pts) Model Predictive Control\n\n\n\nIt is possible to formulate a **discrete-time, finite-horizon optimal-control** as a constrained optimisation problem. This is quite useful since it allows making use of powerful optimisation solvers in addressing the [control problem](https://en.wikipedia.org/wiki/Control_system). This formulation is called Model Predictive Control [(MPC).](https://en.wikipedia.org/wiki/Model_predictive_control) \n\nSpecifically, consider a system with a state vector $x_t\\in {\\bf R}^n$ that varies over the discrete time steps $t=0,\\ldots,T$, and control actions $u_t\\in {\\bf R}^m$ that affect the state as part of a linear dynamical system formulated as \n\n$$ x_{t+1} = A x_t + B u_t, $$\nwhere $A \\in {\\bf R}^{n\\times n}$ and $B \\in {\\bf R}^{n\\times m}$ are system matrices.\n\nThe goal is to find the optimal actions $u_0,\\ldots,u_{T-1}$ over the finite horizon $T$ by solving the optimization problems\n\n\\begin{array}{ll} \\mbox{minimize} & \\sum_{t=0}^{T-1} \\ell (x_t,u_t) + \\ell_T(x_T)\\\\\n\\mbox{subject to} & x_{t+1} = Ax_t + Bu_t\\\\%, \\quad t=0, \\ldots, T-1\\\\\n& (x_t,u_t) \\in \\mathcal C, \\quad x_T\\in \\mathcal C_T,\n%, \\quad \\quad t=0, \\ldots, T\n\\end{array}\n\nwhere $\\ell: {\\bf R}^n \\times {\\bf R}^m\\to {\\bf R}$ is the stage cost, $\\ell_T$ is the terminal cost,\n$\\mathcal C$ is the state/action constraints, and $\\mathcal C_T$ is the terminal constraint.\n\n1. Choose a simple linear dynamical system that you are interested in and formulate its state evolution as $x_{t+1} = A x_t + B u_t$. This can be a very well-known system, you don't need to be original.\n2. Define the objective, i.e. ongoing (and if there are terminal) costs imposed on states and control actions (cost of good/bad states, cost of taking a control action). \n3. Solve the problem over a finite horizon. Apply actions to compute and plot the evolution of states.\n\nA recent research paper (which has won the best student paper award) using MPC formulation is [available here (right click to download).](files/MPC_paper.pdf)\n\n### 3.5 (_Optional_ without bonus :) How do optimisation software handle non-standard problems?\n\n_This is just for those of you, who are very interested and have spare time and bored and have nothing else to do!_\n\nTry to solve Question 6 from Module 2, Lesson 2 (Constrained Optimisation) using the software packages (Python ones and Matlab). How do various software packages handle such non-standard situations? Observe and add to your report briefly with a sentence or two.\n\n# Workshop Report Submission Instructions \n\n_You should ideally complete the workshop tasks and answer the questions within the respective session!_ The submission deadline is usually Friday, the week after. Submission deadlines will be announced on LMS.\n\nIt is **mandatory to follow all of the submissions guidelines** given below. _Don't forget the Report submission information on top of this notebook!_\n\n1. The completed Jupyter notebook and its Pdf version (you can simply print-preview and then print as pdf from within your browser) should be uploaded to the right place in LMS by the announced deadline. _It is your responsibility to follow the announcements!_ **Late submissions will be penalised (up to 100% of the total mark depending on delay amount)!**\n2. Filename should be “ELEN90061 Workshop **W: StudentID1-StudentID2** of session **Day-Time**\", where **W** refers to the workshop number, **StudentID1-StudentID2** are your student numbers, **Day-Time** is your session day and time, e.g. *Tue-14*.\n3. Answers to questions, simulation results and diagrams should be included in the Jupyter notebook as text, code, plots. *If you don't know latex, you can write formulas/text to a paper by hand, scan it and then include as image within Markdown cells.*\n4. One report submission per group. \n \n### Additional guidelines for your programs:\n\n* Write modular code using functions. \n* Properly indent your code. But Python forces you do that anyway ;)\n* Heavily comment the code to describe your implementation and to show your understanding. No comments, no credit!\n* Make the code your own! It is encouraged to find and get inspired by online examples but you should exactly understand, modify as needed, and explain your code via comments. There will be no credit for blind copy/paste even if it somehow works (and it is easier to detect it than you might think)!\n\n\n```python\n\n```\n", "meta": {"hexsha": "9204e87fa62a1bb98eda180ea92fffc5de18bfd4", "size": 194924, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "WS1-Solution.ipynb", "max_stars_repo_name": "JaneHQ1/Predicting-Stroke-Severity-from-Computed-Tomography-Images", "max_stars_repo_head_hexsha": "6988ec693d44da52c1d09946bda0246205de3703", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "WS1-Solution.ipynb", "max_issues_repo_name": "JaneHQ1/Predicting-Stroke-Severity-from-Computed-Tomography-Images", "max_issues_repo_head_hexsha": "6988ec693d44da52c1d09946bda0246205de3703", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "WS1-Solution.ipynb", "max_forks_repo_name": "JaneHQ1/Predicting-Stroke-Severity-from-Computed-Tomography-Images", "max_forks_repo_head_hexsha": "6988ec693d44da52c1d09946bda0246205de3703", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 110.6265607264, "max_line_length": 51264, "alphanum_fraction": 0.8005735569, "converted": true, "num_tokens": 8041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. YES\n\n", "lm_q1_score": 0.3812195803163617, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.23165309857740496}} {"text": "```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n```\n\nOne of the basic things we have to do in math is to express numbers. Numbers are the basic particles of essence so it makes sense to start with them first. We'll start with the *natural numbers* and work our way up through the whole spectrum of numbers finally arriving at the *complex numbers*.\n\nWe'll see that every type of number has a use. These numbers are not just cooked up because somebody figured that would be cool. No, every number serves a definite purpose and even though we might not always understand completely what that purpose is that does not mean we shouldn't use them in order to try a greater understanding.\n\nTake for example the number $\\sqrt{2}$ which is a perfectly fine number nowadays. However, how hard we might try, there's really no other way to write down this number. We could try for an approximation like $1.4142135\\ldots$ but that's really just being sloppy. There *are* other ways to write this number but we will never get a *real* number out of it. Only approximations.\n\n### natural numbers\nSome people like to include the number zero in this set but we'll stick with with the numbers $1, 2, 3, \\ldots, n$ where $n \\gt 0$. They are basically all the whole numbers.\n\n$$\\mathbb{N} = {1, 2, 3, \\ldots}$$\n\nIf we want to be really unambiguous about what we mean we could be extra explicit.\n\n$$\n\\begin{align}\n\\mathbb{N^0} = \\mathbb{N_0} & = {0, 1, 2, 3, \\ldots}\\\\\n\\mathbb{N^*} = \\mathbb{N^+} = \\mathbb{N_1} = \\mathbb{N_{\\gt 0}} & = {1, 2, 3, \\ldots}\n\\end{align}\n$$\n\nIf we really want to include zero in this text we'll use a different set though.\n\n### whole numbers\nThis is all of the numbers in $\\mathbb{N}$ and the number zero. We don't have any cool letter for this though but we can say it's all the whole numbers $0, 1, 2, \\ldots, n$ where $n \\ge 0$.\n\n### integers\nNow this is an interesting set. If only because it's so prevalent in almost all math that we do. For example, computers love integers because they can be so easily represented by a sequence of bits. \n\nIntegers is the set of *whole numbers* but it also includes all the negatives of the *natural numbers*. So now were talking about $-n, \\ldots, -2, -1, 0, 1, 2, \\ldots, n$. This set is important enough to get its own symbol:\n\n$$\\mathbb{Z} = {-n, \\ldots, -2, -1, 0, 1, 2, \\ldots, n}$$\n\n### interlude: integers\nEven though we are not even half-way up our ladder of number systems those integers are already getting a bit interesting. Why do we like them so much in computing? Well, because they can easily be represented as a sequence of one and zero. How does this work though?\n\nIf we look at any integer, let's take for example $321$ and analyze what it means we can come to the insight that:\n\n$$321 = (3 \\times 100) + (2 \\times 10) + (1 \\times 1)$$\n\nIf we look a little deeper we can also see that $100 = 10^2$, $10 = 10^1$ and $1 = 10^0$ so in other words:\n\n$$321 = (3 \\times 10^2) + (2 \\times 10^1) + (1 \\times 10^0)$$\n\nOur number system is called the *decimal* system and that's because we have base `10` numbers. There other number systems. Other sytems that are in commonly in use are *binary*, *hexadecimal* and sometimes *octal*. The binary system is popular because it aligns with electronic switches that can be either on or off. There are only two possibilities and that is what binary means. The octal system is sometimes used because it aligns nicely with the *byte* memory unit in computers but you don't see it much these days. However, the hexadecimal system is still prevalent and you'll see a lot, for example in color codes.\n\nSo how does the binary system work? Well remember that the decimal system operates on *powers* of ten so the binary system operates on power of two.\n\n$$\n\\begin{align}\n0 = 0 \\times 2^0 & = 0\\\\\n1 = 1 \\times 2^0 & = 1 \\\\\n2 = (1 \\times 2^1) + (0 \\times 2^0) & = 10 \\\\\n3 = (1 \\times 2^1) + (1 \\times 2^0) & = 11 \\\\\n4 = (1 \\times 2^2) + (0 \\times 2^1) + (0 \\times 2^0) & = 100 \\\\\n5 = (1 \\times 2^2) + (0 \\times 2^1) + (1 \\times 2^0) & = 101 \\\\\n6 = (1 \\times 2^2) + (1 \\times 2^1) + (0 \\times 2^0) & = 110 \\\\\n7 = (1 \\times 2^2) + (1 \\times 2^1) + (1 \\times 2^1) & = 111\n\\end{align}\n$$\n\n### rational numbers\nWe get rational numbers when we need to express one integer as some part of another. When people started doing real math this problem soon cropped up. The easier way to deal with it is to kind of *not* deal with it and just say well it's this number expressed as some ratio of another. This might be a bit abstract so let's take an example.\n\nWhen we first started doing divisions we took stuff like $\\frac{3}{3} = 1$ and the world was good. As people started doing more fancy stuff with math and numbers things got a bit out of hand though. At some point we found ourselfs in the need to express something else than *integers*. As always, when math runs into a wall we'll just invent something to get over it. And as such we got *rational numbers* which are basically just *fractions* like $\\frac{1}{3}$ or $\\frac{1}{\\pi}$.\n\nAt this point note that in order to get better numbers we just take some existing numbers we know and combine them in some way that makes sense but is somewhat unexpected. I mean, people are still drawing out proplems with triangles and such and now you're starting to abstract some of this stuff away. And it makes sense too because you don't want to lose any information. By keeping that number in its exact *ratio* $\\frac{1}{3}$ you will have a clean number to calculate with.\n\nWhich leads us to the unfortunately necessary...\n\n### real numbers\nLet me start by saying that *real numbers* are unfortunately named because most of them are anything but real. Real numbers are supposed to be plotted along a line (usually the x-axis) and they are but when we *do have* to work with them they are usually just an approximation of a rational number.\n\nWe like to be pure as long as we can so we'll use rational numbers over real numbers but sometimes (especially dealing with computers) we'll *have* to convert our rational number to some *real* approximation. For most purposes you can just think of a *real* number as an *approximation* of some rational number that is to be used for real-life purposes.\n\n### irrational numbers\nThese are interesting numbers because they are so called *real* numbers but we cannot express them as a rational number. As always, when we encounter such a thing in math we tend to give it a name or a convenient notation. Examples are $\\pi$, our friend $\\sqrt{2}$ and $e$.\n\nIrrational numbers are awkward and in order to stay pure we sometimes can do no better than express something as a fraction of an irrational unit. Of course we could try to get a *real* number out but we have to remember that this will always be an approximiation. This might be fine though depending on our purposes.\n\n### imaginary numbers\nThis is where things start to get really interesting (and strange). After hundreds of years of working on math puzzles mathematicians where getting annoyed by the fact that this $\\sqrt{-1}$ kept popping up in their would-be solutions. And (at that time) there was no possible way to calculate a negative *square root* so they just gave up... Mostly. Finally they just decided to go with it and complete the calculations involving the negative square root $\\sqrt{-1}$ and things turned out beautifully. \n\nAfter a few more hundred years it has become so useful that we gave it a special notation and even a special algebra so it all makes sense as a number as well.\n\nSo the first thing we have to consider is that we have this new number now called $i$ which is defined as $i^2 = -1$ so $i = \\sqrt{-1}$. Now we can just use regular algebra to express any negative root, for example if we need $\\sqrt{-5}$ I could just go ${i \\times \\sqrt{5}}$ and this simple transformation allows us to actually calculate with those things.\n\nNote that the name *imaginary* is actually a bad name. These numbers *are* real in the normal sense of that word. The fact that we describe them this way is just byproduct of the way we write math in general. It's better to look at any number and imagine it to have a so-called *imaginary* component. In a lot of cases this will just be $0 \\times i$ (no imaginary component) but sometimes they do.\n\n### complex numbers\nIn some sense, this is the best way to describe a number. This form of numbers is called *complex* buty they are not really that complex though. Again, this is kind of a misnomer and actually complex numbers are very easy. In fact, they are just numbers.\n\nIt's just so many numbers we deal with are on the x-axis of the *complex plane* that we don't even notice we are dealing with complex numbers at all. Thanks to a lot of evolution and schooling we can now reasonably *feel* how most numbers work up to and including rational numbers. However, *imaginary* and *complex numbers* are still a bit weird.\n\nOne of the best ways to show how complex numbers enter math is to show an innocent looking equation like: $y = x^2 + 1$. If we try to solve this for $y = 0$ we get $0 = x^2 + 1$. And going further we get $-1 = x^2 \\implies x = \\sqrt{-1}$. Before complex numbers there was no such thing as $\\sqrt{-1}$ and we would have simply given up.\n\nNowadays we can say that the solution is $i$ (and $-i$ is a valid solution too).\n\n\n```python\n\n```\n", "meta": {"hexsha": "085c2d4db75401948d1493138416437fbd6c820d", "size": 11117, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "math_and_notation.ipynb", "max_stars_repo_name": "basp/notes", "max_stars_repo_head_hexsha": "8831f5f44fc675fbf1c3359a8743d2023312d5ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-12-09T13:58:13.000Z", "max_stars_repo_stars_event_max_datetime": "2016-12-09T13:58:13.000Z", "max_issues_repo_path": "math_and_notation.ipynb", "max_issues_repo_name": "basp/notes", "max_issues_repo_head_hexsha": "8831f5f44fc675fbf1c3359a8743d2023312d5ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "math_and_notation.ipynb", "max_forks_repo_name": "basp/notes", "max_forks_repo_head_hexsha": "8831f5f44fc675fbf1c3359a8743d2023312d5ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 74.1133333333, "max_line_length": 629, "alphanum_fraction": 0.6649275884, "converted": true, "num_tokens": 2457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. YES", "lm_q1_score": 0.3923368301671084, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.231042894885315}} {"text": "```python\n%matplotlib inline\n```\n\n\n파이프라인 병렬화로 트랜스포머 모델 학습시키기\n==============================================\n\n**Author**: `Pritam Damania `_\n **번역**: `백선희 `_\n\n이 튜토리얼은 파이프라인(pipeline) 병렬화(parallelism)를 사용하여 여러 GPU에 걸친 거대한 트랜스포머(transformer)\n모델을 어떻게 학습시키는지 보여줍니다. `NN.TRANSFORMER 와 TORCHTEXT 로 시퀀스-투-시퀀스(SEQUENCE-TO-SEQUENCE) 모델링하기 `__ 튜토리얼의\n확장판이며 파이프라인 병렬화가 어떻게 트랜스포머 모델 학습에 쓰이는지 증명하기 위해 이전 튜토리얼에서의\n모델 규모를 증가시켰습니다.\n\n선수과목(Prerequisites):\n\n * `Pipeline Parallelism `__\n * `NN.TRANSFORMER 와 TORCHTEXT 로 시퀀스-투-시퀀스(SEQUENCE-TO-SEQUENCE) 모델링하기 `__\n\n\n모델 정의하기\n-------------\n\n\n\n\n이번 튜토리얼에서는, 트랜스포머 모델을 두 개의 GPU에 걸쳐서 나누고 파이프라인 병렬화로 학습시켜 보겠습니다.\n모델은 바로 `NN.TRANSFORMER 와 TORCHTEXT 로 시퀀스-투-시퀀스(SEQUENCE-TO-SEQUENCE) 모델링하기\n`__ 튜토리얼과\n똑같은 모델이지만 두 단계로 나뉩니다. 대부분 파라미터(parameter)들은\n`nn.TransformerEncoder `__ 계층(layer)에 포함됩니다.\n`nn.TransformerEncoder `__ 는\n`nn.TransformerEncoderLayer `__ 의 ``nlayers`` 로 구성되어 있습니다.\n결과적으로, 우리는 ``nn.TransformerEncoder`` 에 중점을 두고 있으며,\n``nn.TransformerEncoderLayer`` 의 절반은 한 GPU에 두고\n나머지 절반은 다른 GPU에 있도록 모델을 분할합니다. 이를 위해서 ``Encoder`` 와\n``Decoder`` 섹션을 분리된 모듈로 빼낸 다음, 원본 트랜스포머 모듈을\n나타내는 nn.Sequential을 빌드 합니다.\n\n\n\n\n```python\nimport sys\nimport math\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport tempfile\nfrom torch.nn import TransformerEncoder, TransformerEncoderLayer\n\nif sys.platform == 'win32':\n print('Windows platform is not supported for pipeline parallelism')\n sys.exit(0)\nif torch.cuda.device_count() < 2:\n print('Need at least two GPU devices for this tutorial')\n sys.exit(0)\n\nclass Encoder(nn.Module):\n def __init__(self, ntoken, ninp, dropout=0.5):\n super(Encoder, self).__init__()\n self.pos_encoder = PositionalEncoding(ninp, dropout)\n self.encoder = nn.Embedding(ntoken, ninp)\n self.ninp = ninp\n self.init_weights()\n\n def init_weights(self):\n initrange = 0.1\n self.encoder.weight.data.uniform_(-initrange, initrange)\n\n def forward(self, src):\n # 인코더로 (S, N) 포맷이 필요합니다.\n src = src.t()\n src = self.encoder(src) * math.sqrt(self.ninp)\n return self.pos_encoder(src)\n\nclass Decoder(nn.Module):\n def __init__(self, ntoken, ninp):\n super(Decoder, self).__init__()\n self.decoder = nn.Linear(ninp, ntoken)\n self.init_weights()\n\n def init_weights(self):\n initrange = 0.1\n self.decoder.bias.data.zero_()\n self.decoder.weight.data.uniform_(-initrange, initrange)\n\n def forward(self, inp):\n # 파이프라인 결과물을 위해 먼저 배치 차원 필요합니다.\n return self.decoder(inp).permute(1, 0, 2)\n```\n\n``PositionalEncoding`` 모듈은 시퀀스 안에서 토큰의 상대적인 또는 절대적인 포지션에 대한 정보를 주입합니다.\n포지셔널 인코딩은 임베딩과 합칠 수 있도록 똑같은 차원을 가집니다. 여기서\n다른 주기(frequency)의 ``sine`` 과 ``cosine`` 함수를 사용합니다.\n\n\n\n\n```python\nclass PositionalEncoding(nn.Module):\n\n def __init__(self, d_model, dropout=0.1, max_len=5000):\n super(PositionalEncoding, self).__init__()\n self.dropout = nn.Dropout(p=dropout)\n\n pe = torch.zeros(max_len, d_model)\n position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)\n div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))\n pe[:, 0::2] = torch.sin(position * div_term)\n pe[:, 1::2] = torch.cos(position * div_term)\n pe = pe.unsqueeze(0).transpose(0, 1)\n self.register_buffer('pe', pe)\n\n def forward(self, x):\n x = x + self.pe[:x.size(0), :]\n return self.dropout(x)\n```\n\n데이터 로드하고 배치 만들기\n---------------------------\n\n\n\n\n학습 프로세스는 ``torchtext`` 의 Wikitext-2 데이터셋을 사용합니다.\ntorchtext 데이터셋에 접근하기 전에, https://github.com/pytorch/data 을 참고하여 torchdata를 설치하시기 바랍니다.\n\n단어 오브젝트는 훈련 데이터셋으로 만들어지고, 토큰을 텐서(tensor)로 수치화하는데 사용됩니다.\n시퀀스 데이터로부터 시작하여, ``batchify()`` 함수는 데이터셋을 열(column)들로 정리하고,\n``batch_size`` 사이즈의 배치들로 나눈 후에 남은 모든 토큰을 버립니다.\n예를 들어, 알파벳을 시퀀스(총 길이 26)로 생각하고 배치 사이즈를 4라고 한다면,\n알파벳을 길이가 6인 4개의 시퀀스로 나눌 수 있습니다:\n\n\\begin{align}\\begin{bmatrix}\n \\text{A} & \\text{B} & \\text{C} & \\ldots & \\text{X} & \\text{Y} & \\text{Z}\n \\end{bmatrix}\n \\Rightarrow\n \\begin{bmatrix}\n \\begin{bmatrix}\\text{A} \\\\ \\text{B} \\\\ \\text{C} \\\\ \\text{D} \\\\ \\text{E} \\\\ \\text{F}\\end{bmatrix} &\n \\begin{bmatrix}\\text{G} \\\\ \\text{H} \\\\ \\text{I} \\\\ \\text{J} \\\\ \\text{K} \\\\ \\text{L}\\end{bmatrix} &\n \\begin{bmatrix}\\text{M} \\\\ \\text{N} \\\\ \\text{O} \\\\ \\text{P} \\\\ \\text{Q} \\\\ \\text{R}\\end{bmatrix} &\n \\begin{bmatrix}\\text{S} \\\\ \\text{T} \\\\ \\text{U} \\\\ \\text{V} \\\\ \\text{W} \\\\ \\text{X}\\end{bmatrix}\n \\end{bmatrix}\\end{align}\n\n이 열들은 모델에 의해서 독립적으로 취급되며, 이는\n``G`` 와 ``F`` 의 의존성이 학습될 수 없다는 것을 의미하지만, 더 효율적인\n배치 프로세싱(batch processing)을 허용합니다.\n\n\n\n\n\n```python\nimport torch\nfrom torchtext.datasets import WikiText2\nfrom torchtext.data.utils import get_tokenizer\nfrom torchtext.vocab import build_vocab_from_iterator\n\ntrain_iter = WikiText2(split='train')\ntokenizer = get_tokenizer('basic_english')\nvocab = build_vocab_from_iterator(map(tokenizer, train_iter), specials=[\"\"])\nvocab.set_default_index(vocab[\"\"])\n\ndef data_process(raw_text_iter):\n data = [torch.tensor(vocab(tokenizer(item)), dtype=torch.long) for item in raw_text_iter]\n return torch.cat(tuple(filter(lambda t: t.numel() > 0, data)))\n\ntrain_iter, val_iter, test_iter = WikiText2()\ntrain_data = data_process(train_iter)\nval_data = data_process(val_iter)\ntest_data = data_process(test_iter)\n\ndevice = torch.device(\"cuda\")\n\ndef batchify(data, bsz):\n # 데이터셋을 bsz 파트들로 나눕니다.\n nbatch = data.size(0) // bsz\n # 깔끔하게 나누어 떨어지지 않는 추가적인 부분(나머지)은 잘라냅니다.\n data = data.narrow(0, 0, nbatch * bsz)\n # 데이터를 bsz 배치들로 동일하게 나눕니다.\n data = data.view(bsz, -1).t().contiguous()\n return data.to(device)\n\nbatch_size = 20\neval_batch_size = 10\ntrain_data = batchify(train_data, batch_size)\nval_data = batchify(val_data, eval_batch_size)\ntest_data = batchify(test_data, eval_batch_size)\n```\n\n입력과 타겟 시퀀스를 생성하기 위한 함수들\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n\n\n\n``get_batch()`` 함수는 트랜스포머 모델을 위한 입력과 타겟 시퀀스를\n생성합니다. 이 함수는 소스 데이터를 ``bptt`` 길이를 가진 덩어리로 세분화합니다.\n언어 모델링 과제를 위해서, 모델은 다음 단어인 ``Target`` 이 필요합니다. 에를 들어 ``bptt`` 의 값이 2라면,\n``i`` = 0 일 때 다음의 2 개 변수(Variable)를 얻을 수 있습니다:\n\n\n\n\n변수 덩어리는 트랜스포머 모델의 ``S`` 차원과 일치하는 0 차원에 해당합니다.\n배치 차원 ``N`` 은 1 차원에 해당합니다.\n\n\n\n\n\n```python\nbptt = 25\ndef get_batch(source, i):\n seq_len = min(bptt, len(source) - 1 - i)\n data = source[i:i+seq_len]\n target = source[i+1:i+1+seq_len].view(-1)\n # 파이프라인 병렬화를 위해 먼저 배치 차원이 필요합니다.\n return data.t(), target\n```\n\n모델 규모와 파이프 초기화\n-------------------------\n\n\n\n\n파이프라인 병렬화를 활용한 대형 트랜스포머 모델 학습을 증명하기 위해서\n트랜스포머 계층 규모를 적절히 확장시킵니다. 4096차원의 임베딩 벡터, 4096의 은닉 사이즈,\n16개의 어텐션 헤드(attention head)와 총 12 개의 트랜스포머 계층\n(``nn.TransformerEncoderLayer``)를 사용합니다. 이는 최대\n**1.4억** 개의 파라미터를 갖는 모델을 생성합니다.\n\nPipe는 `RRef `__ 를 통해\n`RPC 프레임워크 `__ 에 의존하는데\n이는 향후 호스트 파이프라인을 교차 확장할 수 있도록 하기 때문에\nRPC 프레임워크를 초기화해야 합니다. 이때 RPC 프레임워크는 오직 하나의 하나의 worker로 초기화를 해야 하는데,\n여러 GPU를 다루기 위해 프로세스 하나만 사용하고 있기 때문입니다.\n\n그런 다음 파이프라인은 한 GPU에 8개의 트랜스포머와\n다른 GPU에 8개의 트랜스포머 레이어로 초기화됩니다.\n\n

Note

효율성을 위해 ``Pipe`` 에 전달된 ``nn.Sequential`` 이\n 오직 두 개의 요소(2개의 GPU)로만 구성되도록 합니다. 이렇게 하면\n Pipe가 두 개의 파티션에서만 작동하고\n 파티션 간 오버헤드를 피할 수 있습니다.

\n\n\n\n\n```python\nntokens = len(vocab) # 단어 사전(어휘집)의 크기\nemsize = 4096 # 임베딩 차원\nnhid = 4096 # nn.TransformerEncoder 에서 순전파(feedforward) 신경망 모델의 차원\nnlayers = 12 # nn.TransformerEncoder 내부의 nn.TransformerEncoderLayer 개수\nnhead = 16 # multiheadattention 모델의 헤드 개수\ndropout = 0.2 # dropout 값\n\nfrom torch.distributed import rpc\ntmpfile = tempfile.NamedTemporaryFile()\nrpc.init_rpc(\n name=\"worker\",\n rank=0,\n world_size=1,\n rpc_backend_options=rpc.TensorPipeRpcBackendOptions(\n init_method=\"file://{}\".format(tmpfile.name),\n # _transports와 _channels를 지정하는 것이 해결 방법이며\n # PyTorch 버전 >= 1.8.1 에서는 _transports와 _channels를\n # 지정하지 않아도 됩니다.\n _transports=[\"ibv\", \"uv\"],\n _channels=[\"cuda_ipc\", \"cuda_basic\"],\n )\n)\n\nnum_gpus = 2\npartition_len = ((nlayers - 1) // num_gpus) + 1\n\n# 처음에 인코더를 추가합니다.\ntmp_list = [Encoder(ntokens, emsize, dropout).cuda(0)]\nmodule_list = []\n\n# 필요한 모든 트랜스포머 블록들을 추가합니다.\nfor i in range(nlayers):\n transformer_block = TransformerEncoderLayer(emsize, nhead, nhid, dropout)\n if i != 0 and i % (partition_len) == 0:\n module_list.append(nn.Sequential(*tmp_list))\n tmp_list = []\n device = i // (partition_len)\n tmp_list.append(transformer_block.to(device))\n\n# 마지막에 디코더를 추가합니다.\ntmp_list.append(Decoder(ntokens, emsize).cuda(num_gpus - 1))\nmodule_list.append(nn.Sequential(*tmp_list))\n\nfrom torch.distributed.pipeline.sync import Pipe\n\n# 파이프라인을 빌드합니다.\nchunks = 8\nmodel = Pipe(torch.nn.Sequential(*module_list), chunks = chunks)\n\n\ndef get_total_params(module: torch.nn.Module):\n total_params = 0\n for param in module.parameters():\n total_params += param.numel()\n return total_params\n\nprint ('Total parameters in model: {:,}'.format(get_total_params(model)))\n```\n\n모델 실행하기\n-------------\n\n\n\n\n손실(loss)을 추적하기 위해 `CrossEntropyLoss `__ 가\n적용되며, 옵티마이저(optimizer)로서 `SGD `__\n는 확률적 경사하강법(stochastic gradient descent method)을 구현합니다. 초기\n학습률(learning rate)은 5.0로 설정됩니다. `StepLR `__ 는\n에폭(epoch)에 따라서 학습률을 조절하는 데 사용됩니다. 학습하는 동안,\n기울기 폭발(gradient exploding)을 방지하기 위해 모든 기울기를 함께 조정(scale)하는 함수\n`nn.utils.clip_grad_norm\\_ `__\n을 이용합니다.\n\n\n\n\n\n```python\ncriterion = nn.CrossEntropyLoss()\nlr = 5.0 # 학습률\noptimizer = torch.optim.SGD(model.parameters(), lr=lr)\nscheduler = torch.optim.lr_scheduler.StepLR(optimizer, 1.0, gamma=0.95)\n\nimport time\ndef train():\n model.train() # 훈련 모드로 전환\n total_loss = 0.\n start_time = time.time()\n ntokens = len(vocab)\n\n # 스크립트 실행 시간을 짧게 유지하기 위해서 50 배치만 학습합니다.\n nbatches = min(50 * bptt, train_data.size(0) - 1)\n\n for batch, i in enumerate(range(0, nbatches, bptt)):\n data, targets = get_batch(train_data, i)\n optimizer.zero_grad()\n # Pipe는 단일 호스트 내에 있고\n # forward 메서드로 반환된 ``RRef`` 프로세스는 이 노드에 국한되어 있기 때문에\n # ``RRef.local_value()`` 를 통해 간단히 찾을 수 있습니다.\n output = model(data).local_value()\n # 타겟을 파이프라인 출력이 있는\n # 장치로 옮겨야합니다.\n loss = criterion(output.view(-1, ntokens), targets.cuda(1))\n loss.backward()\n torch.nn.utils.clip_grad_norm_(model.parameters(), 0.5)\n optimizer.step()\n\n total_loss += loss.item()\n log_interval = 10\n if batch % log_interval == 0 and batch > 0:\n cur_loss = total_loss / log_interval\n elapsed = time.time() - start_time\n print('| epoch {:3d} | {:5d}/{:5d} batches | '\n 'lr {:02.2f} | ms/batch {:5.2f} | '\n 'loss {:5.2f} | ppl {:8.2f}'.format(\n epoch, batch, nbatches // bptt, scheduler.get_lr()[0],\n elapsed * 1000 / log_interval,\n cur_loss, math.exp(cur_loss)))\n total_loss = 0\n start_time = time.time()\n\ndef evaluate(eval_model, data_source):\n eval_model.eval() # 평가 모드로 전환\n total_loss = 0.\n ntokens = len(vocab)\n # 스크립트 실행 시간을 짧게 유지하기 위해 50 배치만 평가합니다.\n nbatches = min(50 * bptt, data_source.size(0) - 1)\n with torch.no_grad():\n for i in range(0, nbatches, bptt):\n data, targets = get_batch(data_source, i)\n output = eval_model(data).local_value()\n output_flat = output.view(-1, ntokens)\n # 타겟을 파이프라인 출력이 있는\n # 장치로 옮겨야합니다.\n total_loss += len(data) * criterion(output_flat, targets.cuda(1)).item()\n return total_loss / (len(data_source) - 1)\n```\n\n에폭을 반복합니다. 만약 검증 오차(validation loss)가 지금까지 관찰한 것 중 최적이라면\n모델을 저장합니다. 각 에폭 이후에 학습률을 조절합니다.\n\n\n\n\n```python\nbest_val_loss = float(\"inf\")\nepochs = 3 # 에폭 수\nbest_model = None\n\nfor epoch in range(1, epochs + 1):\n epoch_start_time = time.time()\n train()\n val_loss = evaluate(model, val_data)\n print('-' * 89)\n print('| end of epoch {:3d} | time: {:5.2f}s | valid loss {:5.2f} | '\n 'valid ppl {:8.2f}'.format(epoch, (time.time() - epoch_start_time),\n val_loss, math.exp(val_loss)))\n print('-' * 89)\n\n if val_loss < best_val_loss:\n best_val_loss = val_loss\n best_model = model\n\n scheduler.step()\n```\n\n평가 데이터셋으로 모델 평가하기\n-------------------------------\n\n\n\n\n평가 데이터셋에서의 결과를 확인하기 위해 최고의 모델을 적용합니다.\n\n\n\n\n```python\ntest_loss = evaluate(best_model, test_data)\nprint('=' * 89)\nprint('| End of training | test loss {:5.2f} | test ppl {:8.2f}'.format(\n test_loss, math.exp(test_loss)))\nprint('=' * 89)\n```\n", "meta": {"hexsha": "6a6e54e3f1cf0ac67591549675e46840456db474", "size": 26597, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/_downloads/d9fe745d7a46067a343337497f7074cd/pipeline_tutorial.ipynb", "max_stars_repo_name": "9bow/PyTorch-Tutorials-KR", "max_stars_repo_head_hexsha": "bfddf43a696545cb0991262faeb653affe1040b4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 44, "max_stars_repo_stars_event_min_datetime": "2021-12-07T14:51:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:34:17.000Z", "max_issues_repo_path": "docs/_downloads/d9fe745d7a46067a343337497f7074cd/pipeline_tutorial.ipynb", "max_issues_repo_name": "9bow/PyTorch-Tutorials-KR", "max_issues_repo_head_hexsha": "bfddf43a696545cb0991262faeb653affe1040b4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 128, "max_issues_repo_issues_event_min_datetime": "2021-12-02T18:11:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T05:16:39.000Z", "max_forks_repo_path": "docs/_downloads/d9fe745d7a46067a343337497f7074cd/pipeline_tutorial.ipynb", "max_forks_repo_name": "9bow/PyTorch-Tutorials-KR", "max_forks_repo_head_hexsha": "bfddf43a696545cb0991262faeb653affe1040b4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2021-12-02T18:56:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T07:18:23.000Z", "avg_line_length": 116.1441048035, "max_line_length": 3073, "alphanum_fraction": 0.6686092416, "converted": true, "num_tokens": 5450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.23017174404733065}} {"text": "## DW mid-terms 2018 solutions
\n### These solutions are student compiled and might contain errors (especially for qn 1 & 2)
Credit goes to Team Anonymous on Piazza

Part A\n\n\n```python\nx = 'aces'\ny = 1.23\nz = x\nx = y\ny = z\nprint(x, y)\n```\n\n### Q1(a) After the above code is executed, at line 6, what is seen on the screen is 1.23aces.

By explaining what each line of the code below (for lines 1 to 5) does, show how the code below switches the objects assigned to variables x and y.

Your explanation must state when objects are created and their data types, and also how names are assigned to these objects. Diagrams could be helpful in your explanation. (6 points)\n\n**Sample answer 1:**
\nAt line 1, string object 'aces' is assigned to frame 'x'. At line 2, float object of value 1.23 is assigned to frame 'y'. At line 3, a shallow copy of string object 'aces' from frame 'x' is assigned to frame 'z'. At line 4, a shallow copy of the float object of value 1.23 from frame 'y' is assigned to frame 'x' and overwirtes the string object 'aces'. At line 5, a shallow copy of string object 'aces' from frame 'z' is assigned to frame 'y' and overwrites the float object of value 1.23. The final result is:
\nStack | Object after line 3 > 4 > 5
\nx\t| 'aces' > 1.23 > 1.23
\ny\t| 1.23 > 1.23 > 'aces'
\nz\t| 'aces' > 'aces' > 'aces'
\nThe contents of both x & y are fetched when print(x,y) is executed at line 6. Thus, 1.23aces is printed in the order of x then y.\n\n### Q1(b) When the following code is executed, after line 12, what is seen on the screen is True.

i) Using how names are assigned to objects in memory, explain why. Diagrams could be helpful in your explanation. (3 points)

ii) The intention of the programmer is to create two lists showing the words for ‘seven’, ‘eight’ and ‘nine’ for both Greek and French. State one modification to the code at line 8 so that line 13 prints out the correct output. (1point)\n\n\n```python\nfrench= [ 'sept', 'huit', 'neuf'] # the words mean 'seven','eight','nine'.\ngreek = french # this is line 8\ngreek[0] = 'epta' # 'seven'\ngreek[1] = 'okto' # 'eight'\ngreek[2] = 'enea' # 'nine'\nprint(greek is french) # this is 'line 12'\nprint(french, greek)\n```\n\n**Sample answer 1:**
\ni) At line 1, a list object is created for frame 'french'. At line 2, frame 'greek' is assigned to refer to the same list object as frame 'french'. Thus, even after the contents of the list is changed, line 12's shallow equivalence check 'is' returns true as both frames 'french' and 'greek' still refers to the same list object in memory.

\nii) I would repace line 8 with 'greek = list(french)' to another list object similar in contents to frame 'french' is created for frame 'greek'.\n\n\n### Q2 [10 points]\n### a) Is there anything wrong with the following program? If yes, what is wrong? (2 points)\n\n\n```python\nimport = int(input(\"Enter a number: \"))\nif import==2:\n print(\"Yes\")\nelse: \n print(\"No\")\n```\n\n**Sample solution 1:**
\nSynthax error. 'import' is a reserved keyword in python and neither be used as a variable name nor be assigned to an 'int' type object. \n\n### b) If break is removed from the following programand the program is run, what will be printed out? (2 points)\n\n\n```python\nmy_string = \"Computing\" \nfor character in my_string:\n print(character)\n if character == \"u\":\n print(\"Found 'u' :)\")\n```\n\n**Solution:**
\nC
\no
\nm
\np
\nu
\nFound 'u' :)
\nt
\ni
\nn
\ng
\n\n### c) Look at the following function:\n\n\n```python\ndef my_function(n): \n return_value = None \n if n == 0 or n == 1: \n return_value = False # not run \n i=2 \n while i*0.5: \n if n%i==0: \n return_value = False # not run \n break # not run \n i += 1 \n return_value = True \n return return_value\nmy_function(37)\n```\n\n### Let the function tested to be my_function(37)

a) What will be the output? (1 point)

b) Identify the lines of the program which will be executed when the input is 37. Do this by entering the codes from those lines to eDimension. (2 points)\n\n**Solution:**
\na) True.
\nb) (enter those lines of code not tagged by # not run)\n\n### d) In the context of the 1D projects you have completed so far in this course, look at the following function:\n\n\n```python\ndef forward(speed, duration):\n robot.wheels(speed, speed)\n robot.sleep(duration)\n robot.wheels(0,0)\n```\n\n### a) Why is it not necessary to have a return statement in this function? (1 point)

b) If we change robot.wheels(speed, speed) to robot.wheels(speed1, speed2) and the function header is also modified to take in speed1 and speed2, how will the movement of the robot change? You can assume that speed1 and speed2 are different and both speed1 and speed2 are positive numbers. (1 point)\n\n**Sample solution 1:**
\na) In the above function to move the robot forward at some speed for some duration, no values are expected to be reused or caught by the function. Hence, no return statement is required.

\nb) If speed1 > speed2, the robot will still travel forward but with a leftwards dispalcement. If speed1 < speed2, the robot will still travel forward but with a rightwards dispalcement. \n\n### Part B

Q3 [10 points]

A frustum is a parallel truncation of a right pyramid. A piece of metal is in the shape of a frustum with a square base. The side length of the top square is s1 and the side length of the bottom square is s2. The height of the frustum is H.

The volume of the frustum is given by the formula:
$$Volume = \\frac{H}{3}(A1 + A2 + \\sqrt{A1 \\text{ x } A2})$$ where A1 is the area of the upper square, A2 is the area of the lower square, and H is the height of the frustum.\n\n### a) Write a python function area_square(s) that takes the side of a square as an input argument s, and returns the area of the square.

b) Write a python function vol_frustum(top_area, bottom_area, height) that takes three arguments, a top area, a bottom area and a height in that order, and returns the volume of the frustum.

c) Write a python function get_volume(s1, s2, height) that takes three arguments, a top side length, a bottom side length and a height and returns the volume of a frustum based on those dimensions. This function should first call area_square to obtain the two needed areas, and then call vol_frustum to evaluate the volume.

All input arguments and return values are floats. Please round only your final output of get_volume to three decimal places. Please use math.sqrt() to compute the square root in your python code. Note that you get only full marks if your get_volume function makes use of the other two functions.\n\n\n```python\nimport math\ndef area_square(s):\n return s**2.\n\ndef vol_frustum(top_area, bottom_area, height):\n return (height/3)*(top_area + bottom_area + math.sqrt(top_area*bottom_area))\n \ndef get_volume(s1, s2, height):\n return round(vol_frustum(area_square(s1), area_square(s2), height), 3)\n\n## TEST CASES ##\nprint('{:.3f}'.format(area_square(2)))\nprint('{:.3f}'.format(area_square(3)))\nprint('{:.3f}'.format(vol_frustum(1,4,2)))\nprint('{:.3f}'.format(vol_frustum(2,2,2)))\nprint('{:.3f}'.format(get_volume(1,2,2)))\nprint('{:.3f}'.format(get_volume(1.5,3.3,5.0)))\nprint('{:.3f}'.format(get_volume(3.6,6.4,4.0)))\n```\n\n### Q4 [10 points]

Implement a function determinant(matrix) that takes a matrix as input (represented as a nested list) and returns its determinant as output. The function should satisfy the following requirements:

1) If the input matrixis not of dimension n x n (for 1 ≤n ≤3), the function should return None

2) The function is to be implemented withoutimporting any libraries.\n\n\n```python\ndef determinant(matrix):\n M = matrix\n try:\n a = len(M)\n a = len(M[0])\n except:\n return None\n \n if len(M) == 1:\n for row in M:\n if len(row) != 1:\n return None\n return M[0][0]\n if len(M) == 2:\n for row in M:\n if len(row) != 2:\n return None\n return M[0][0] * M[1][1] - M[0][1]*M[1][0]\n if len(M) == 3:\n for row in M:\n if len(row) != 3:\n return None\n return (M[0][0] * M[1][1] * M[2][2] \n + M[1][0] * M[2][1] * M[0][2] \n + M[2][0] * M[0][1] * M[1][2]\n - M[0][2] * M[1][1] * M[2][0]\n - M[1][0] * M[0][1] * M[2][2]\n - M[0][0] * M[2][1] * M[1][2])\n \n## TEST CASES ##\nprint(determinant([[100]]))\nprint(determinant([[-5, -4],[-2, -3]]))\nprint(determinant([[2, -3, 1], [2, 0, -1],[1, 4, 5]]))\nprint(determinant([[0, 3, 5],[5, 5, 2],[3, 4, 3]]))\nprint(determinant([[23], [-4, 4]]))\n```\n\n### Q5 [15 points]

The Newton-Raphson (NR) method is an iterative method that approximates the root of a function. The accuracy of the answer is enhanced in successive iterations.

You need two create two functions: nrootand nroot_complex. The function nroot(n, i, num) is to determine the root of non-negative num. The function nroot_complex(n,i,num) to determine the root of negative num. Thefunction nroot_complex should call nroot to do the NR approximation. Note the output should give a constant$*$1j where j is the imaginary square root of -1. For odd n the output should give a negative value instead of constant$*$1j. This means that:

• When num is a non-negative number, nroot_complex should give the same result as nroot.
• When num is a negative number and n is even, nroot_complex should give a complex number with no real part, and its magnitude is the same as the output of nrootwhen num is positive.
• When numis a negative number and n is odd, nroot_complex should give a negative real number, and its magnitude is the same as the output of nroot when numis positive.

Round the output of nroot to 3 decimal places.Use x = 1 as your initial value.\n\n\n```python\ndef nroot(n,t,num):\n x = 1\n for i in range(t):\n x -= ((x**n - num)/(n*(x**(n-1))))\n return round(x,3)\n\ndef nroot_complex(n,t,num):\n if num > 0 or num == 0:\n return nroot(n,t,num)\n if num < 0 and n%2 == 1:\n return -nroot(n,t,-num)\n else:\n return str(nroot(n,t,-num)) + 'j'\n \n## TEST CASES ##\nprint(nroot(2,5,2))\nprint(nroot_complex(2,5,-4))\nprint(nroot_complex(3,5,-8))\n```\n\n### Q6 [30 points]

In this problem you will write a program to find a path through MRT stations from a starting station to an ending station with a maximum of one interchange.

The overall function is called find_path and it takes three arguments: (1) a file object to a text file containing the MRT lines and stations, (2) the starting station, and (3) the ending station.

This function should return a list of stations from a starting station to an ending station with a maximum of one interchange. The problem is decomposed by writing several other functions, described in the following parts.

For simplicity, the information given to you in this question is limited to the North South line and the East West line. Also, the branch line to Changi Airport is treated as a separate line. Hence the three lines are labelled in this question as follows: (1) NorthSouthLine (2) EastWestLine (EW) and (3) EastWestLine (CG).

a) read_stations(f): This function takes in a file object and returnsa dictionary. The dictionary has the MRT lines as its keys. The value of each key is a list of stations in that MRT line.

b) get_stationline(mrt): This function takes in a dictionary of MRT lines (i.e. the output of part (a) ). The function returns another dictionary which contains all the stations as its keys. The value for each key is a list of the MRT lines for that particular station. Note that if the station is an interchange, the list should contain all the lines calling at that station.

c) get_interchange(stationline): This function takes in a dictionary of stations and their lines (i.e. the output of part (b)). The function returns another dictionary which contains all the interchange stations as its keys. The value for each key is a list of the MRT lines for that particular interchange stations.

d) find_path(f, start, end): This function takes in three arguments: (1) the file object to a text file containing all the MRT lines and stations, (2) the startingstation, and (3) the endingstation. The function should return a list of stations starting from the starting station to the ending station with a maximum of one interchange.If there are more than one possible paths, the following considerations should be taken into account:

• If there is a path without changing MRT lines, the result should return this path.
• If the path must involve changing MRT lines, it will return the path with a minimum number of stations and containing only one interchange station.
• If no such path can be found as above, it will return None.\n\n\n```python\n## PART A ##\ndef read_stations(s):\n st = ''.join(s.readlines()).split(\"=\")\n ans = {}\n for i in range(int((len(st)-1)/2)):\n ans[st[2*i+1]] = (st[2*(i+1)].strip(\"\\n\")).split(\", \")\n return ans\n\n## PART B ##\ndef get_stationline(mrt):\n ans = {}\n for lines in mrt:\n for station in mrt[lines]:\n if station not in ans:\n ans[station] = []\n ans[station].append(lines)\n else:\n ans[station].append(lines)\n return ans\n\n## PART C ##\ndef get_interchange(stationline):\n ans = {}\n for stations in stationline:\n if len(stationline[stations]) > 1:\n ans[stations] = stationline[stations]\n return ans\n\n## PART D ##\ndef create_graph(f):\n stations = read_stations(f)\n stationline = get_stationline(stations)\n interchange = [*get_interchange(stationline)]\n network = {}\n # Create a dictionary where station (key) is linked to all its connected stations (values)\n for line in stations:\n stations_ = stations.get(line)\n network[stations_[-1]]=[stations_[-2]] # End stations only conencted to one other station\n for station in range(0,len(stations_)-1): \n network.setdefault(stations_[station],[stations_[station-1]]).append(stations_[station+1]) \n if stations_[0] not in interchange: \n network[stations_[0]]=[stations_[1]] # Removing non interchange connections that loops\n network['City Hall'].append('Dhoby Ghaut') # Add this pesky back edge \n for key in network:\n network[key] = set(network.get(key)) # Apply set structure to dictionary values \n return network\n\ndef bfs_paths(graph, start, goal):\n # Since we only want the shortest path, we use Breath First Search on a queue structure for efficiency\n queue = [(start, [start])]\n while queue:\n (vertex, path) = queue.pop(0)\n for next in graph[vertex] - set(path):\n if next == goal:\n yield path + [next]\n else:\n queue.append((next, path + [next]))\n \n\nimport collections as c \ndef find_path(f, start, end):\n try: \n graph = create_graph(f)\n possible_paths = list(bfs_paths(graph,start,end))\n f.seek(0) # remember to reset readlines() counter to 0\n stations = read_stations(f)\n stationline = get_stationline(stations)\n interchange = [*get_interchange(stationline)]\n ans = []\n for path in possible_paths:\n line_counter = []\n for station in path:\n line_counter.append(stationline.get(station)[0])\n # We count the total number of line types present. More than 1 interchange used if line type > 2 \n if len(c.Counter(line_counter)) <= 2:\n ans.append(path)\n return ans[0] # Since we used BFS, first path found is always the shortest\n except:\n # A general catch block to return None \n return None \n\n## TEST CASES ##\nprint('Test 1')\nf=open('mrt_lines_short.txt','r') # Make sure directory is correct\nans=find_path(f,'Boon Lay', 'Clementi')\nprint(ans)\nf.close()\nprint('Test 2')\nf=open('mrt_lines_short.txt','r') # Make sure directory is correct\nans=find_path(f,'Changi Airport', 'Orchard')\nprint(ans)\nf.close()\nprint('Test 3')\nf=open('mrt_lines_short.txt','r') # Make sure directory is correct\nans=find_path(f,'Boon Lay', 'Bukit Gombak')\nprint(ans)\nf.close()\nprint('Test 4')\nf=open('mrt_lines_short.txt','r') # Make sure directory is correct\nans=find_path(f,'Tanah Merah', 'Orchard')\nprint(ans)\nf.close()\n```\n\n### Q7 [15 points]

Write a function decompose(pence), that takes as input some number of pence (as an integer), and returns as output an integer expressing how many different ways that the amount can be made up by using the available coins. At present, there are eight coins in general circulation:

1p, 2p, 5p, 10p, 20p, 50p, £1, and £2

Note that the function decompose(pence) can be implemented in a number of different ways, including by using brute force (i.e. exhaustive search). However, brute force implementations may only score a maximum of 12 points; the full 15 are only available for more elegant/efficient solutions.\n\n**Sample Solution 1: Naive for loops (Brute force; Don't even try to time it)**\n\n\n```python\ndef decompose(pence):\n coins = [1,2,5,10,20,50,100,200]\n count = 0\n for x1 in range(pence):\n for x2 in range(pence):\n for x3 in range(pence):\n for x4 in range(pence):\n for x5 in range(pence):\n for x6 in range(pence):\n for x7 in range(pence):\n for x8 in range(pence):\n if (x1 * coins[0] + x2 * coins[1] + x3 * coins[2] + x4 * coins[3]\n + x5 * coins[4] + x6 * coins[5] + x7 * coins[6] + x8 * coins[7])\n == pence:\n count += 1 # Cancer\n \n return count + 1\n\n## TEST CASES ## \nimport time\nstart_time = time.time()\nprint (decompose(1))\nprint (decompose(5))\nprint (decompose(7))\nprint (decompose(130))\nprint (decompose(200))\nprint (decompose(700))\nprint(\"--- %s seconds ---\" % (time.time() - start_time)) \n```\n\n**Sample Solution 2: Pure recursion (Exhasutive; ~10mins)**\n\n\n```python\ndef decompose(pence, num_types = len(coins)): \n coins = [1,2,5,10,20,50,100,200]\n # If pence = 0 then there is only 1 solution\n if (pence == 0): \n return 1\n \n # If n is less than 0 then no solution exists \n if (pence < 0): \n return 0; \n \n # If there are no coins and n is greater than 0, then no solution exist \n if (num_types <=0 and pence >= 1): \n return 0\n \n # Recursion step \n return decompose( pence, num_types - 1 ) + decompose( pence - coins[num_types-1], num_types);\n\n## TEST CASES ## \nimport time\nstart_time = time.time()\nprint (decompose(1))\nprint (decompose(5))\nprint (decompose(7))\nprint (decompose(130))\nprint (decompose(200))\nprint (decompose(700))\nprint(\"--- %s seconds ---\" % (time.time() - start_time)) \n```\n\n**Sample Solution 3: Recursion with some memomisation (Exhasutive with some elegance; ~5mins)**\n\n\n```python\ndef decompose(pence, coins = [1,2,5,10,20,50,100,200]):\n \n # If pence = 0 then there is only 1 solution\n if pence == 0:\n return 1\n \n # If n is less than 0 then no solution exists \n if pence < 0:\n return 0\n num_ways = 0\n \n # Store previously computed sub-problems in a dictionary to avoid re-computing it\n dic_ways = {}\n for i in range(len(coins)):\n coin = coins[i]\n if pence-coin not in dic_ways:\n # Recursion step\n num_ways += decompose(pence - coin, coins[i:])\n dic_ways[pence-coin] = True\n return num_ways\n\n## TEST CASES ## \nimport time\nstart_time = time.time()\nprint (decompose(1))\nprint (decompose(5))\nprint (decompose(7))\nprint (decompose(130))\nprint (decompose(200))\nprint (decompose(700))\nprint(\"--- %s seconds ---\" % (time.time() - start_time)) \n```\n\n**Sample solution 4: Expansion of partition equation into series (Elegant but inefficient; ~30s)**\n\n\n```python\nfrom sympy import *\ndef decompose(pence):\n x = symbols('x')\n partition_series = series(1/(( 1 - x)*(1-x**2)*(1-x**5)*(1-x**10)\n *(1-x**20)*(1-x**50)*(1-x**100)*(1-x**200)), n = pence+2)\n coef = Poly(partition_series.removeO(),x)\n return coef.all_coeffs()[1]\n\n## TEST CASES ## \nimport time\nstart_time = time.time()\nprint (decompose(1))\nprint (decompose(5))\nprint (decompose(7))\nprint (decompose(130))\nprint (decompose(200))\nprint (decompose(700))\nprint(\"--- %s seconds ---\" % (time.time() - start_time)) \n```\n\n**Sample solution 5: Smart brute force (Efficent but inelegant; 1.5s)**\n\n\n```python\ndef decompose(pence):\n count = 0\n for x1 in range(0,pence+1,200):\n for x2 in range(x1,pence+1,100):\n for x3 in range(x2,pence+1,50):\n for x4 in range(x3,pence+1,20):\n for x5 in range(x4,pence+1,10):\n for x6 in range(x5,pence+1,5):\n for x7 in range(x6,pence+1,2):\n count+=1\n return count\n\n## TEST CASES ## \nimport time\nstart_time = time.time()\nprint (decompose(1))\nprint (decompose(5))\nprint (decompose(7))\nprint (decompose(130))\nprint (decompose(200))\nprint (decompose(700))\nprint(\"--- %s seconds ---\" % (time.time() - start_time)) \n```\n\n**Sample solution 6: Top-down Dynamic Programming; Recursion with memoization & decorators (Efficient & quite elegant; ~0.002s)**\n\n\n```python\ndef memoize(func):\n cache = dict()\n def memoized_func(*args):\n if args in cache:\n return cache[args]\n result = func(*args)\n cache[args] = result\n return result\n return memoized_func\n ## The above code is a quick and dirty memo fucntion that can be used widely ##\n ## to speed up problems with overlapping sub-problems (avoid recomputation) ## \n\n@memoize\n## Pure recursion from sample solution 2 ##\ndef decompose(pence, num_types = len(coins)): \n coins = [1,2,5,10,20,50,100,200]\n # If pence = 0 then there is only 1 solution\n if (pence == 0): \n return 1\n \n # If n is less than 0 then no solution exists \n if (pence < 0): \n return 0; \n \n # If there are no coins and n is greater than 0, then no solution exist \n if (num_types <=0 and pence >= 1): \n return 0\n \n # Recursion step \n return decompose( pence, num_types - 1 ) + decompose( pence - coins[num_types-1], num_types);\n\n## TEST CASES ## \nimport time\nstart_time = time.time()\nprint (decompose(1))\nprint (decompose(5))\nprint (decompose(7))\nprint (decompose(130))\nprint (decompose(200))\nprint (decompose(700))\nprint(\"--- %s seconds ---\" % (time.time() - start_time)) \n```\n\n**Sample Solution 7: Bottom-up Dynamic Programming (Most elegant & efficient; ~0.001s)**\n\n\n```python\ndef decompose(pence): \n try: \n coins = [1,2,5,10,20,50,100,200]\n num_types = len(coins)\n # table[i] will be storing the number of solutions for \n # value i. We need n+1 rows as the table is constructed \n # in bottom up manner using the base case (pence = 0) \n # We first initialize all table values as 0 \n table = [0 for accumulative_num_of_ways in range(pence+1)] \n \n # If pence = 0 then there is only 1 solution\n table[0] = 1\n \n # Pick all coins one by one and update the table[] values \n # after the index greater than or equal to the value of the \n # picked coin \n for type_ in range(0,num_types): \n for value in range(coins[type_],pence+1): \n table[value] += table[value-coins[type_]] \n # We only want the number of ways to find change for value = pence \n return table[pence]\n except:\n # Our bottom up approach innately deals with special cases\n # this line catches invalid arguments\n return 0 \n\n## TEST CASES ## \nimport time\nstart_time = time.time()\nprint (decompose(1))\nprint (decompose(5))\nprint (decompose(7))\nprint (decompose(130))\nprint (decompose(200))\nprint (decompose(700))\nprint(\"--- %s seconds ---\" % (time.time() - start_time)) \n```\n\n\n```python\n \n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "154de6502422468ac4296ad658eadd1ee2b77275", "size": 33100, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "midterm2018_solutions.ipynb", "max_stars_repo_name": "ed-ke/DW2018", "max_stars_repo_head_hexsha": "5a36a3f83c0ccc7ebbdbbe3add12a2f7c10e5e39", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-02-28T12:51:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-09T01:44:51.000Z", "max_issues_repo_path": "midterm2018_solutions.ipynb", "max_issues_repo_name": "JoeAverage12/DW2018", "max_issues_repo_head_hexsha": "5a36a3f83c0ccc7ebbdbbe3add12a2f7c10e5e39", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "midterm2018_solutions.ipynb", "max_forks_repo_name": "JoeAverage12/DW2018", "max_forks_repo_head_hexsha": "5a36a3f83c0ccc7ebbdbbe3add12a2f7c10e5e39", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-02-19T09:28:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-29T07:37:18.000Z", "avg_line_length": 40.6134969325, "max_line_length": 2620, "alphanum_fraction": 0.5573716012, "converted": true, "num_tokens": 6735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. YES", "lm_q1_score": 0.43782348444346736, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.22916572099991694}} {"text": "```python\nfrom IPython.core.display import HTML\ndef css_styling():\n styles = open(\"./styles/custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()\n```\n\n\n\n\n\n\n\n\n\n### BEFORE YOU DO ANYTHING...\nIn the terminal:\n1. Navigate to __inside__ your ILAS_Python repository.\n2. __COMMIT__ any un-commited work on your personal computer.\n3. __PULL__ any changes *you* have made using another computer.\n4. __PULL__ textbook updates (including homework answers).\n\n1. __Open Jupyter notebook:__ Start >> Programs (すべてのプログラム) >> Programming >> Anaconda3 >> JupyterNotebook\n1. __Navigate to the ILAS_Python folder__. \n1. __Open Seminar 7___ by clicking on 7_Numerical_computation_with_Numpy.\n\n

Numerical Computation with Numpy

\n\n

Lesson Goal

\n\nCompose programs to solve simple mathematical problems using the Python Numpy package. \n\n## Objectives\n- Represent data using the `array` data structure for numerical computation.\n- Use 1D and 2D arrays to represent vectors and matrices. \n- Manipulate arrays (indexing, slicing, vectorising etc)\n- Perform familiar numerical operations using Python.\n- Compare efficiency of vectorised and non-vectorised functions.\n\n## Why are we studying this?\nNumerical computation is central to almost all scientific and engineering problems.\n\nThere are programming languages specifically designed for numerical computation:\n- Fortran\n- MATLAB\n\nThere are libaries dedicated to efficient numerical computations:\n- Numpy\n- Scipy\n- Sympy ...\n\nNumPy (http://www.numpy.org/) \n - The most widely used Python library for numerical computations. \n - Large, extensive library of data structures and functions for numerical computation.\n - Useful for perfoming operation you will learn on mathematics-based courses.\n\n\nScipy (https://www.scipy.org/)\n- Builds on Numpy, additional functionality\n- More specialised data structures and functions over NumPy.\n\n\n\n\nIf you are familiar with MATLAB, NumPy and SciPy provide similar functionality. \n\n\n\nLast week we covered an introduction to some basic functions of Numpy.\n\nNumPy is a very extensisve library.\n\nThis seminar will:\n- Introduce some useful functions\n- Briefly discuss how to search for additional functions you may need. \n\nyour best resources are search engines, such as http://stackoverflow.com/.\n\n\n\n## Importing the NumPy module\n\nTo make NumPy functions and variables available to use in our program in our programs, we need to __import__ it using.\n\n`import numpy`\n\nWe typically import all modules at the start of a program or notebook. \n\n\n```python\nimport numpy as np\n```\n\nThe shortened name `np` is often used for numpy. \n\nAll Numpy functions can be called using `np.function()`. \n\n## Data Structure: The Numpy `array`\n\n### Why do we need another data structure?\n\nPython lists hold 'arrays' of data. \n\nLists are very flexible. e.g. holding mixed data type.\n\nThere is a trade off between flexibility and performance e.g. speed.\n\nScience engineering and mathematics problems often involve large amounts of data and numerous operations. \n\nWe therefore use specialised functions and data structures for numerical computation.\n\n## Numpy array\n\nA numpy array is a grid of values, *all of the same type*.\n\nTo create an array we use the Numpy `array` function.\n\nIt takes a list as an argument.\n\n\n```python\na = np.array([1, 2, 3])\n\nprint(type(a))\n\nprint(a.dtype)\n```\n\n \n int64\n\n\n\n```python\nb = [4.0, 5, 6.0]\n\nc = np.array(b) \n\nprint(type(b))\nprint(type(c))\nprint(c.dtype)\n```\n\n \n \n float64\n\n\n## Multi-dimensional arrays.\n\nUnlike the data types we have studied so far, arrays can have multiple dimensions.\n\n__`rank`:__ the number of *dimensons* of the array.\n\n__`shape`:__ a *tuple* of *integers* giving the *size* of the array along each *dimension*.\n\n\n```python\n# 1-dimensional array\na = np.array([1, 2, 3])\n\n# 2-dimensional array\nb = np.array([[1, 2, 3], [4, 5, 6]])\n\nb = np.array([[1, 2, 3], \n [4, 5, 6]])\n\nprint(a.shape)\nprint(b.shape)\n```\n\n (3,)\n (2, 3)\n\n\n\n```python\n# 3-dimensional array\n\nc = np.array(\n [[[1, 1],\n [1, 1]],\n \n [[1, 1],\n [1, 1]]])\n\nprint(c.shape)\n\nc = np.array(\n [[[1, 1],\n [1, 1]],\n \n [[1, 1],\n [1, 1]],\n \n [[1, 1],\n [1, 1]]])\n\nprint(c.shape)\n```\n\n (2, 2, 2)\n (3, 2, 2)\n\n\n\n```python\n# 3-dimensional array\n\nc = np.array(\n [[[1, 1],\n [1, 1]],\n \n [[1, 1],\n [1, 1]]])\n\n# 4-dimensional array\nd = np.array(\n [[[[1, 1],\n [1, 1]],\n \n [[1, 1],\n [1, 1]]],\n\n\n [[[1, 1],\n [1, 1]],\n \n [[1, 1],\n [1, 1]]]])\n\nprint(c.shape)\nprint(d.shape)\n```\n\n (2, 2, 2)\n (2, 2, 2, 2)\n\n\n## Creating a numpy array.\n\nThere are several other ways we can create an array\n\n\n```python\n# Create an array of all zeros\n# The zeros() function argument is the shape.\n# Shape: tuple of integers giving the size along each dimension.\n\na = np.zeros(5)\nprint(a)\n\nprint()\n\na = np.zeros((2,2)) \nprint(a) \n```\n\n [ 0. 0. 0. 0. 0.]\n \n [[ 0. 0.]\n [ 0. 0.]]\n\n\n\n```python\n# Create an array of all ones\n\nb = np.ones(5)\nprint(b)\n\nprint()\n\nb = np.ones((1, 4)) \nprint(b) \n```\n\n\n```python\n# Create a constant array\n# The second function argument is the constant value\n\nc = np.full(6, 8)\nprint(c)\n\nprint()\n\nc = np.full((2,2,2), 7) \nprint(c) \n\n```\n\n [8 8 8 8 8 8]\n \n [[[7 7]\n [7 7]]\n \n [[7 7]\n [7 7]]]\n\n\n## Subpackages\nPackages can also have subpackages. \n\nThe `numpy` package has a subpackage called `random`.\n\nIt contains functions to deal with random variables. \n\nIf the `numpy` package is imported with `import numpy as np`, functions in the `random` subpackage can be called using `np.random.function()`. \n\n\n```python\n# Create an array filled with random values\n\ne = np.random.rand(1)\nprint(e)\nprint()\n\ne = np.random.rand(3,2,1)\nprint(e)\nprint()\n\ne = np.random.random((2,2)) \nprint(e)\n```\n\n [ 0.1925726]\n \n [[[ 0.79990402]\n [ 0.63879192]]\n \n [[ 0.38519791]\n [ 0.0073061 ]]\n \n [[ 0.9293842 ]\n [ 0.77903214]]]\n \n [[ 0.09380194 0.32369848]\n [ 0.72059049 0.03877658]]\n\n\n\n```python\n# Create an array filled with random integrer values\n```\n\n\n```python\ne = np.random.randint(16, size=(4,4))\nprint(e)\n\nprint()\n\ne = np.random.randint(8, size=(2, 2, 2))\nprint(e)\n```\n\n## Indexing.\n\nWe can index into an array exactly the same way as the other data structures we have studied.\n\n\n```python\n\n```\n\n\n```python\nx = np.array([1, 2, 3, 4, 5])\n\n# Select a single element\nprint(x[4])\n\n# Select elements from 2 to the end\nprint(x[2:])\n```\n\n 5\n [3, 4, 5]\n\n\nFor an n-dimensional (nD) matrix we need n index values to address an element or range of elements.\n\nExample: The index of a 2D array is specified with two values:\n- first the row index\n- then the column index.\n\nNote the order in which dimensions are addressed.\n\n\n```python\n# 2 dimensional array\n\ny = np.array([[1, 2, 3], \n [4, 5, 6]])\n\n\n# Select a single element\nprint(y[1,2])\n\n# Select elements that are both in rows 1 to the end AND columns 0 to 2 \nprint(y[1:, 0:2])\n```\n\n 6\n [[4 5]]\n\n\nWe can address elements by selecting a range with a step by addig a \n\nFor example the index:\n\n`z[0, 0:]`\n\nselects every element of row 0 in array, `z`\n\nThe index:\n\n`z[0, 0::2]`\n\nselects every *other* element of row 0 in array, `z`\n\n\n```python\n# 2 dimensional array\n\nz = np.zeros((4,8))\n\n# Change every element of row 0\nz[0, 0:] = 10\n\n# Change every other element of row 1\nz[1, 0::2] = 10\n\nprint(z)\n```\n\n [[ 10. 10. 10. 10. 10. 10. 10. 10.]\n [ 10. 0. 10. 0. 10. 0. 10. 0.]\n [ 0. 0. 0. 0. 0. 0. 0. 0.]\n [ 0. 0. 0. 0. 0. 0. 0. 0.]]\n\n\n\n```python\nz = np.zeros((4,8))\n\n# Change the last 4 elements of row 2, in negative direction\n# You MUST include a step to count in the negative direction\nz[2, -1:-5:-1] = 10\n\n# Change every other element of the last 6 elements of row 3\n# in negative direction\nz[3, -2:-7:-2] = 10\n\nprint(z)\n```\n\n [[ 0. 0. 0. 0. 0. 0. 0. 0.]\n [ 0. 0. 0. 0. 0. 0. 0. 0.]\n [ 0. 0. 0. 0. 10. 10. 10. 10.]\n [ 0. 0. 10. 0. 10. 0. 10. 0.]]\n\n\n\n```python\n# 3-dimensional array\n\nc = np.array(\n [[[2, 1, 4],\n [2, 6, 8]],\n \n [[0, 1, 5],\n [7, 8, 9]]])\n\nprint(c[0, 1, 2])\n\n\n```\n\n 8\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\nWhere we want to select all elements in one dimension we can use :\n\n__Exception__: If it is the last element , we can omit it. \n\n\n```python\nprint(c[0, 1])\n\nprint(c[0, :, 1])\n```\n\n [2 6 8]\n [1 6]\n\n\n## Iterating over multi-dimensional arrays. \nWe can iterate over a 1D array in the same way as the data structures we have previously studied.\n\n\n```python\nA = np.array([1, 2, 3, 4, 5])\n```\n\n\n```python\nfor a in A:\n print(a)\n```\n\n 1\n 2\n 3\n 4\n 5\n\n\nTo loop through individual elements of a multi-dimensional array, we use a nested loop for each dimension of the array.\n\n\n```python\nB = np.array([[1, 2, 3], \n [4, 5, 6]])\n\nfor row in B:\n print(\"-----\")\n for col in row:\n print(col)\n```\n\n -----\n 1\n 2\n 3\n -----\n 4\n 5\n 6\n\n\n## Manipulating arrays\nWe can use many of the same operations to manipulate arrays as we use for lists.\n\n\n```python\n# Length of an array\n\na = np.array([1, 3, 4, 17, 3, 21, 2, 12])\n\nb = ([1, 3, 4, 17],\n [3, 21, 2, 12])\n\n\nprint(len(a))\nprint(len(b))\n\n\n```\n\n 8\n 2\n\n\nNote the length is the length of the first dimension (e.g. indexing). \n\n\n```python\n# Sort an array\n\na = np.array([1, 3, 4, 17, 3, 21, 2, 12])\n\n# The method sort() and function sorted() give the same result\na.sort()\n\na = sorted(a)\n\nprint(a)\n```\n\n [1, 2, 3, 3, 4, 12, 17, 21]\n\n\nArrays are *immutable* (unchangeable).\n\nTechnically you cannot delete an item from it. \n\nHowever, you can make a new array without the values you don't want: \n\n\n```python\n# Remove items from an array\n\nz = np.array([1, 3, 4, 17, 3, 21, 2, 12])\n\n\nz = np.delete(z, 3)\nprint(z)\n\nz = np.delete(z, [0, 1, 2])\nprint(z)\n\n```\n\n [ 1 3 4 3 21 2 12]\n [ 3 21 2 12]\n\n\n\n```python\n# Add items to an array\n\na = ([1, 2, 3])\na = np.insert(a, 1, 4)\nprint(a)\n```\n\n [1 4 2 3]\n\n\n\n```python\n# Add items to an array\n\nb = np.array([[1, 1], \n [2, 2], \n [3, 3]])\n\nb = np.insert(b, 1, 4)\nprint(b)\n```\n\n [1 4 1 2 2 3 3]\n\n\n\n```python\n# Add items to an array\n\nb = np.array([[1, 1], \n [2, 2], \n [3, 3]])\n\nb = np.insert(b, 1, 4, axis=1)\nprint(b)\n```\n\n [[1 4 1]\n [2 4 2]\n [3 4 3]]\n\n\n\n```python\n# Change items in an array\n\nc = np.array([1, 2, 3])\nc[1] = 4\nprint(c)\n```\n\n [1 4 3]\n\n\n### Boolean array indexing\n\nRecall that we can use *conditional operators* to check the value of a single variable against a condition.\n\nThe value returned is a Boolean True or False value.\n\n\n\n```python\na = 4\nprint('a < 2:', a < 2)\nprint('a > 2:', a > 2)\n```\n\n a < 2: False\n a > 2: True\n\n\nIf we instead use *conditional operators* to check the value of an array against a condition.\n\nThe value returned is an *array* of Boolean True or False values.\n\n\n```python\na = np.array([[1,2], \n [3, 4], \n [5, 6]])\n\nidx = a > 2\n\nprint(idx)\n```\n\n [[False False]\n [ True True]\n [ True True]]\n\n\nA particular elements of an array can be are specified by using a boolean array as an index. \n\nOnly the values of the array where the boolean array is `True` are selected. \n\nThe varaible `idx` can therefore now be used as the index to select all elements greater than 2.\n\n\n```python\nprint(a[idx]) \n```\n\n [3 4 5 6]\n\n\nTo do the whole process in a single step\n\n\n```python\nprint(a[a > 2]) \n```\n\n [3 4 5 6]\n\n\nUse shape to reshape the matrix? \n\nAnother example\n\n\n```python\na = np.arange(5)\nprint('the total array:', a)\nprint('values less than 3:', a[a < 3])\n```\n\n the total array: [0 1 2 3 4]\n values less than 3: [0 1 2]\n\n\n## Mathematics with arrays.\n\nUnlike lists, NumPy arrays support common arithmetic operations, such as addition of two arrays.\n\n\n```python\n# To add the elements of two lists we need the Numpy function: add\na = [1, 2, 3]\nb = [4, 5, 6]\n\nc = a + b\nprint(c)\n\nc = np.add(a, b)\nprint(c)\n```\n\n [1, 2, 3, 4, 5, 6]\n [5 7 9]\n\n\nTo add the elements of two arrays we can just use regular arithmetic operators.\n\n\n```python\na = np.array([1, 2, 3])\nb = np.ones((1,3))\n\nc = a + b\nprint(c)\n```\n\n [[ 2. 3. 4.]]\n\n\nAlgebraic operations are appled *elementwise* to an array.\n\nThis means the function is applied individually to each element in the list.\n\nFor addition and subtraction arrays behave like vectors and matrices.\n\nFor example, if you were to add or subtract two vectors/matrices in MATLAB. \n\n\n```python\na = np.array([1.0, 0.2, 1.2])\nb = np.array([2.0, 0.1, 2.1])\n\nprint(a - b)\n\nprint(np.subtract(a, b))\n```\n\nBut it is important to remember that arrays ARE NOT vectors and matrices.\n\nRegular mathematical operators perform *elementwise* operations on arrays. \n\n\n```python\na = np.array([1.0, 0.2, 1.2])\nb = np.array([2.0, 0.1, 2.1])\n\n# Elementwise multiplication of a and b\nprint(a * b)\nprint(np.multiply(a, b))\n\nprint()\n\n# Elementwise division of a and b\nprint(a / b)\nprint(np.divide(a, b))\n```\n\n [ 2. 0.02 2.52]\n [ 2. 0.02 2.52]\n \n [ 0.5 2. 0.57142857]\n [ 0.5 2. 0.57142857]\n\n\nIf the number of __columns in A__ \n
is the same as number of __rows in B__, \n
we can find the matrix product of $\\mathbf{A}$ and $\\mathbf{B}$.\n\n\n```python\n\\begin{equation*}\n\\underbrace{\n\\begin{bmatrix}\n1 & 2 & 3 \\\\\n4 & 5 & 6 \\\\\n7 & 8 & 9 \\\\\n\\end{bmatrix}\n}_{\\mathbf{A} \\text{ 3 rows} \\text{ 3 columns}}\n\\times\n\\underbrace{\n\\begin{bmatrix}\n10 & 11 \\\\\n12 & 13 \\\\\n14 & 15 \\\\\n\\end{bmatrix}\n}_{\\mathbf{B} \\text{ 3 rows} \\text{ 2 columns}}\n=\\underbrace{\n\\begin{bmatrix}\n(1 \\cdot 10 + 2 \\cdot 12 + 3 \\cdot 14) \\quad\n(1 \\cdot 11 + 2 \\cdot 13 + 3 \\cdot 15) \\\\\n(4 \\cdot 10 + 5 \\cdot 12 + 6 \\cdot 14) \\quad\n(4 \\cdot 11 + 5 \\cdot 13 + 6 \\cdot 15) \\\\\n(7 \\cdot 10 + 8 \\cdot 12 + 9 \\cdot 14) \\quad\n(7 \\cdot 11 + 8 \\cdot 13 + 9 \\cdot 15) \\\\\n\\end{bmatrix}\n}_{\\mathbf{C} \\text{ 3 rows} \\text{ 2 columns}}\n=\\underbrace{\n\\begin{bmatrix}\n76 & 82 \\\\\n184 & 199 \\\\\n292 & 316 \\\\\n\\end{bmatrix}\n}_{\\mathbf{C} \\text{ 3 rows} \\text{ 2 columns}}\n\\end{equation*}\n```\n\n## Mathematics with Vectors (1D arrays)\nLet's look at a previous example for computing the dot product of two vectors.\n\nThe dot product of two $n$-length-vectors:\n
$ \\mathbf{A} = [A_1, A_2, ... A_n]$\n
$ \\mathbf{B} = [B_1, B_2, ... B_n]$\n\n\\begin{align}\n\\mathbf{A} \\cdot \\mathbf{B} = \\sum_{i=1}^n A_i B_i.\n\\end{align}\n\nWe learnt to solve this very easily using a Python `for` loop.\n\nWith each iteration of the loop we increase the value of `dot_product` (initial value = 0.0) by the product of `a` and `b`. \n\n```python\nA = [1.0, 3.0, -5.0]\nB = [4.0, -2.0, -1.0]\n\n# Create a variable called dot_product with value, 0.\ndot_product = 0.0\n\nfor a, b in zip(A, B): \n dot_product += a * b\n\nprint(dot_product)\n```\n\nUsing Numpy arrays we can solve the dot product using the Numpy function `dot`.\n\n\n```python\nA = np.array([1.0, 3.0, -5.0])\nB = np.array([4.0, -2.0, -1.0])\n\nprint(np.dot(A,B))\n```\n\n 3.0\n\n\n__Try it yourself__\n\nRecap the Seminar 5: Functions; in the cell below write a function that takes two lists and returns the dot product using the code from Seminar 4: Data Structures (shown above).\n\nUse the magic function `%timeit` to compare the speed of the for loop with the Numpy `dot()` function for solving the dot product.\n\n\n```python\n# Write a function for the dot product of two vectors expressed as lists\n# Compare the speed of your function to the Numpy function\n```\n\n## Mathematics with Matrices (2D arrays)\nIf you have previously studied matrices, the operations in this section will be familiar. \n\nIf you have not yet studied matrices, you may want to refer back to this section once matrices have been covered in your mathematics classes.\n\nMaterial from this section will not be included in the exam.\n\n2D arrays are a convenient way to represents matrices.\n\nFor example, to create the matrix\n\n$$\nA = \n\\begin{bmatrix} \n3 & 5 & 7\\\\ \n2 & 4 & 6\n\\end{bmatrix} \n$$\n\n\n\n```python\nA = np.array([[3, 5, 7], \n [2, 4, 6]])\nprint(A)\n```\n\n [[3 5 7]\n [2 4 6]]\n\n\nRecall, the method `shape()` tells us the dimensions of an array.\n\nThis gives us the number of rows and the number of columns, expressed as a tuple.\n\nBy describe the dimensions of a matrix as as \"rows\" by \"columns\" matrix. \n\n\n```python\nprint(A.shape)\nprint(f\"Number of rows is {A.shape[0]}, number of columns is {A.shape[1]}\")\nprint(f\"A is an {A.shape[0]} by {A.shape[1]} matrix\")\n```\n\n (2, 3)\n Number of rows is 2, number of columns is 3\n\n\n### Matrix multiplication\n\nIf the number of __columns in A__ \n
is the same as number of __rows in B__, \n
we can find the matrix product of $\\mathbf{A}$ and $\\mathbf{B}$.\n\n\n\\begin{align}\n\\mathbf{A} \\mathbf{B} = \\mathbf{C} \n\\end{align}\n\nWe multiply each __row__ in \\mathbf{A} by each __column__ in \\mathbf{B}\n\n\n\n\\begin{equation*}\n\\underbrace{\n\\begin{bmatrix}\na_{11} & a_{12} & a_{13} \\\\\na_{21} & a_{22} & a_{23} \\\\\na_{31} & a_{32} & a_{33} \\\\\n\\end{bmatrix}\n}_{\\mathbf{A} \\text{ 3 rows} \\text{ 3 columns}}\n\\times\n\\underbrace{\n\\begin{bmatrix}\nb_{11} \\\\\nb_{21} \\\\\nb_{31} \\\\\n\\end{bmatrix}\n}_{\\mathbf{B} \\text{ 3 rows} \\text{ 1 column}}\n=\\underbrace{\n\\begin{bmatrix}\na_{11}b_{11} + a_{12}b_{21} + a_{13}b_{31} \\\\\na_{21}b_{11} + a_{22}b_{21} + a_{23}b_{31} \\\\\na_{31}b_{11} + a_{32}b_{21} + a_{33}b_{31} \\\\\n\\end{bmatrix}\n}_{\\mathbf{C} \\text{ 3 rows} \\text{ 1 column}}\n\\end{equation*}\n\nIn matrix $\\mathbf{C}$, the element in \n
__row $i$__, \n
__column $j$__ \n\nis equal to the dot product of \n
__$i$th row__ of $\\mathbf{A}$, \n
__$j$th column__ of $\\mathbf{B}$.\n\nMatrix $\\mathbf{C}$ therefore has \n
the same number of __rows as A__,\n
the same number of __columns as B__.\n\n#### Example 1: THIS EXAMPLE IS WRONG MAKE A GOOD ONE!!!\n\n\n\n#### Example 2:\n\\begin{equation*}\n\\underbrace{\n\\begin{bmatrix}\n1 & 2 & 3 \\\\\n4 & 5 & 6 \\\\\n7 & 8 & 9 \\\\\n\\end{bmatrix}\n}_{\\mathbf{A} \\text{ 3 rows} \\text{ 3 columns}}\n\\times\n\\underbrace{\n\\begin{bmatrix}\n10 & 11 \\\\\n12 & 13 \\\\\n14 & 15 \\\\\n\\end{bmatrix}\n}_{\\mathbf{B} \\text{ 3 rows} \\text{ 2 columns}}\n=\\underbrace{\n\\begin{bmatrix}\n(1 \\cdot 10 + 2 \\cdot 12 + 3 \\cdot 14) \\quad\n(1 \\cdot 11 + 2 \\cdot 13 + 3 \\cdot 15) \\\\\n(4 \\cdot 10 + 5 \\cdot 12 + 6 \\cdot 14) \\quad\n(4 \\cdot 11 + 5 \\cdot 13 + 6 \\cdot 15) \\\\\n(7 \\cdot 10 + 8 \\cdot 12 + 9 \\cdot 14) \\quad\n(7 \\cdot 11 + 8 \\cdot 13 + 9 \\cdot 15) \\\\\n\\end{bmatrix}\n}_{\\mathbf{C} \\text{ 3 rows} \\text{ 2 columns}}\n=\\underbrace{\n\\begin{bmatrix}\n76 & 82 \\\\\n184 & 199 \\\\\n292 & 316 \\\\\n\\end{bmatrix}\n}_{\\mathbf{C} \\text{ 3 rows} \\text{ 2 columns}}\n\\end{equation*}\n\n\n```python\n#Example 1\nA = np.array([[1, 1, 2],\n [2, 1, 3],\n [1, 4, 2]])\n\nB = np.array([[3], \n [1], \n [2]])\n\nC = A.dot(B)\nprint(C)\n\nprint()\n\nC = np.dot(A,B)\nprint(C)\n```\n\n [[ 8]\n [13]\n [11]]\n \n [[ 8]\n [13]\n [11]]\n\n\n\n```python\n#Example 2\nA = np.array([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]])\n\nB = np.array([[10, 11], \n [12, 13], \n [14, 15]])\n\nC = A.dot(B)\nprint(C)\n\nprint()\n\nC = np.dot(A,B)\nprint(C)\n```\n\n [[ 76 82]\n [184 199]\n [292 316]]\n \n [[ 76 82]\n [184 199]\n [292 316]]\n\n\nWe can find the inverse $\\mathbf{A}^{-1}$, of a sqaure matrix, $\\mathbf{A}$. \n\n\n```python\nA = np.array([[1,2], \n [3, 4]]) \n\nAinv = np.linalg.inv(A)\n\nprint(f\"A = \\n {A}\")\nprint(f\"Inverse of A = \\n {Ainv}\")\n```\n\n A = \n [[1 2]\n [3 4]]\n Inverse of A = \n [[-2. 1. ]\n [ 1.5 -0.5]]\n\n\nWe can find the determinant, $\\textrm{det}(\\mathbf{A})$, of a sqaure matrix, $\\mathbf{A}$. \n\n\n```python\nA = np.array([[1,2], \n [3, 4]]) \n\nAdet = np.linalg.det(A)\n\nprint(f\"A = \\n {A}\")\nprint(f\"Determinant of A = {round(Adet, 2)}\")\n```\n\n A = \n [[1 2]\n [3 4]]\n Determinant of A = -2.0\n\n\nWe can generate an *identity matrix*.\n\n\n```python\nI = np.eye(2)\nprint(I)\n\nprint()\n\nI = np.eye(4)\nprint(I)\n```\n\n [[ 1. 0.]\n [ 0. 1.]]\n \n [[ 1. 0. 0. 0.]\n [ 0. 1. 0. 0.]\n [ 0. 0. 1. 0.]\n [ 0. 0. 0. 1.]]\n\n\n\n```python\nprint(np.sqrt(a))\nprint(a ** (1/2))\n\n```\n\n## Vectorising Functions\n\nNumpy functions applied to a single array, will be performed on each element in the array. \n\nThe function takes an array of values as an input argument.\n\n\n```python\nprint(np.sqrt(a))\nprint(a ** (1/2))\n\n```\n\nFor example, we can apply trigonometric functions, elementwise, to arrays, lists and tuples.\n\n\n```python\nx = np.array([0.0, np.pi/2, np.pi, 3*np.pi/2])\ny = [0.0, np.pi/2, np.pi, 3*np.pi/2]\nz = (0.0, np.pi/2, np.pi, 3*np.pi/2)\n\nprint(np.sin(x))\nprint(np.cos(y))\nprint(np.tan(z))\n\n```\n\n [ 0.00000000e+00 1.00000000e+00 1.22464680e-16 -1.00000000e+00]\n [ 1.00000000e+00 6.12323400e-17 -1.00000000e+00 -1.83697020e-16]\n [ 0.00000000e+00 1.63312394e+16 -1.22464680e-16 5.44374645e+15]\n\n\nAn array of values does not work as an input for all functions.\n\n\n```python\ndef func(x):\n if x < 0:\n f = 2 * x\n else:\n f = 3 * x\n return f\n\nx = np.array([2,2])\ny = func(x) # Run this line after removing the # to se\n```\n\nThis doesn't work because Python doesn't know what to do with the line \n\n`if x < 0` \n\nwhen `x` contains many values. \n\nFor some values of `x` the `if` statement may be `True`, for others it may be `False`. \n\n\n\nA simple way around this problem is to vectorise the function. \n\nWe create a new function that is a *vectorized* form of the original function.\n\nThe new function and can be called with an array as an argument. \n\n\n```python\nfuncvec = np.vectorize(func)\n\nx = np.random.randint(4,size =(2,2))\n\ny = funcvec(x)\nprint(x)\nprint(y)\n```\n\n [[3 0]\n [2 3]]\n [[9 0]\n [6 9]]\n\n\n## Broadcasting\n\n\n```python\na = np.array([1, 2, 3, 4])\nb = np.ones((3,1))\n\nc = a + b\n\nprint(b)\nprint()\nprint(c)\n```\n\n [[ 1.]\n [ 1.]\n [ 1.]]\n \n [[ 2. 3. 4. 5.]\n [ 2. 3. 4. 5.]\n [ 2. 3. 4. 5.]]\n\n\n## Review Exercises\n\nThe folowing exercises are provided to practise what you have learnt in today's seminar.\n\nThere are some extension excercises for you to complete if you are familiar with using matrices and want to practise matrix manipulation using Python.\n\nIf you have not yet studeied matrices, you can come back to this section when the mathematics used is more familiar to you. \n\n\n\n### Review Exercise: Arrays and indices\n\nIn the cell below:\n\n1. Create an array of zeros with length 25. \n\n2. Change the first 10 values to 5. \n\n3. Change the next 10 values to a sequence starting at 12 and increasig with steps of 2 to 30 - do this with one command. \n\n4. Set the final 5 values to 30. \n\n\n```python\n\n```\n\n### Review Exercise: Two-dimensional array indices\n\nIn the cell below, for the array `x`, write code to print: \n\n* the first row of `x`\n* the first column of `x`\n* the third row of `x`\n* the last two columns of `x`\n* the four values in the upper right hand corner of `x`\n* the four values at the center of `x`\n\n\n\n```python\nx = np.array([[4, 2, 3, 2],\n [2, 4, 3, 1],\n [2, 4, 1, 3],\n [4, 1, 2, 3]])\n```\n\n### Review Exercise: Fix the error \nThe code below, is supposed to:\n- change the last 5 values of the array `x` to the values [50, 52, 54, 56, 58] \n- print the result\n\nThere are some errors in the code. \n\nRemove the comment markers and run the code to see the error message. \n\nThen fix the code and run it again.\n\n\n```python\n\n```\n", "meta": {"hexsha": "a447c6ab7f010f386613e5fd2691651d2dcae3fd", "size": 51580, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "7_Numerical_computation_with_Numpy.ipynb", "max_stars_repo_name": "konshte/Python_K", "max_stars_repo_head_hexsha": "6ab7ebfcd0e31d3ca4cee6b5cfc71dced3ce3a62", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "7_Numerical_computation_with_Numpy.ipynb", "max_issues_repo_name": "konshte/Python_K", "max_issues_repo_head_hexsha": "6ab7ebfcd0e31d3ca4cee6b5cfc71dced3ce3a62", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "7_Numerical_computation_with_Numpy.ipynb", "max_forks_repo_name": "konshte/Python_K", "max_forks_repo_head_hexsha": "6ab7ebfcd0e31d3ca4cee6b5cfc71dced3ce3a62", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0989699955, "max_line_length": 954, "alphanum_fraction": 0.4698332687, "converted": true, "num_tokens": 8142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.22276476751978636}} {"text": "Nota para antes de leer este documento:
\n 1. El paquete dst contiene toda la implementación de las ideas aquí expuestas. El notebook 2. Implementación incluye implementaciones para distintas configuraciones. En el presente documento se expondrá código de manera ilustrativa, sin embargo, el paquete es el encargado de realizar los procedimientos aquí expuestos. Para ver la implementación puede dirigirse al código fuente, al enlace a colab o al notebook de experimentos. \n

\n 2. La implementación que se realizo esta basada en el documento Image Style Transfer Using Convolutional Neural Networks, en el blog de tensorflow y en el blog de Marko Jerkic\n

\n 3. La implementación está escrita en Python3 usando Tensorflow y Keras.\n\n

Aprendizaje profundo para la transferencia de estilo

\n

Universidad de Antioquia
Angelower Santana Velasquez
Martin Elias Quintero Osorio

\n\n\n\n

Motivación

\n

El Deep Learning (Aprendizaje Profundo) es un campo específico del aprendizaje automático (Machine Learning)y en consecuencia de la inteligencia artificial(AI), el cual, ha demostrado un avance exponencial los últimos años. El Deep Learning ha sorprendido por sus increíbles resultados en múltiples áreas para solucionar distintos tipos de problema. Específicamente el deep learning gira en torno al estudio de modelos basados en redes neuronales artificiales, sus funciones de pérdida, la capacidad de distintos tipos de optimización, estrategias para evitar el sobreajuste, el diseño de arquitecturas de redes neuronales enfocadas a cumplir objetivos desde distintos enfoques de aprendizaje, entre muchas otras estrategias que son de gran importancia dentro del Machine Learning. Podemos encontrar varias ramas del Deep Learning como el procesamiento de lenguaje natural (NLP) y la visión por computadora (Computer Vision -CV), siendo esta última materia de estudio desde hace más de una década teniendo avances sorprendentes. Hoy día podemos ver el aprovechamiento de la visión computacional en aplicaciones implementadas en aeropuertos, automóviles, en la industria y, no muy alejado, en nuestros teléfonos inteligentes. Dentro del Deep Learning existe un tipo de red neuronal capaz de emular, según algunas personas, el comportamiento biológico que ocurre en los seres humanos en el proceso de \"visión\", las redes neuronales convolucionales(CNN), llamadas así por realizar operaciones de convolución dentro del proceso de entrenamiento, operador bastante utilizado en el procesamiento de señales. Y son este tipo de redes neuronales casi la opción por defecto para tratar problemas de visión computacional.

\n\n

La capacidad de cómputo que disponemos actualmente ha permitido que se realicen múltiples experimentos y se desarrollen ideas sorprendentes para el ojo común. Sistemas que controlan automóviles, aplicaciones que determinan cierto tipo de enfermedades en plantas, filtros y aplicación de diferentes \"máscaras\" en imágenes en tiempo real (por ejemplo instagram y snapchat), detección de enfermedades bajo la deteccion de patrones (por ejemplo la retinopatía diabética) y la clasificación de objetos son ejemplos de la capacidad que pueden lograr sistemas basados en redes neuronales convolucionales.

\n\n

Una cita de uno de los artistas más importantes del siglo XX, Pablo Picasso, dice : “La pintura es más fuerte que yo, siempre consigue que haga lo que ella quiere”. El presente informe explora una aplicación bastante ingeniosa para generar \"arte\" a partir de técnicas de Deep Learning con redes neuronales convolucionales. Que de forma similar a la frase de Picasso, será nuestro modelo el encargado de generar una imagen a su antojo a partir de dos fuentes de datos: Una imagen de contenido y otra de estilo. Ahora, ¿podrías imaginar como Vincent van Gogh había pintado a Medellín?

\n\n

imagen 1
The starry night in Medellín
Imagen contenido: Fotografia del centro de Medellín
Imagen estilo: The Starry Night - Vincent van Gogh

\n\n

Contenido y estilo

\n\nEl cubismo fue un movimiento artístico donde se quería representar elementos de la cotidianidad en composiciones de formas geométricas bien definidas. Es decir, tomar un elemento, capturar su esencia y plasmarla en cubos, triangulos y rectangulos. De esa manera definimos el contenido de una imagen como la esencia que tiene dejando a un lado elementos como el color y la textura. Por otro lado, cuando hablemos de estilo nos referimos a la forma, los colores, sombras y otros matices que no sean la esencia. De hecho, la transferencia de estilo busca tomar la esencia y plasmar en ella la forma y colores de otra imagen. Por ejemplo, en la imagen 1 , el contenido es la fotografía de Medellín imagen 2 lado derecho superior y el estilo es la famosa pintura de Vicent Van Gogh : The starry night. imagen 2 lado derecho inferior \n\n\n

imagen 2
The starry night in Medellín (Contenido, estilo y resultado)
Lado izquierdo: Resultado de Deep Transfer Style
Lado Derecho parte superior: Contenido
Lado Derecho parte inferior: Estilo

\n\n\n

Deep Transfer Style

\n\nLa idea detrás de la técnica de transferencia de estilo es la representación interna que producen las redes neuronales convolucionales una vez entrenadas. Dichas redes están conformadas por capas que tienen por objetivo propósitos específicos: Algunas sirven como mapa de activación que nos indica que tan sensible es una imagen a un patrón o filtro. En otras palabras, si aplicamos un filtro que detecte bordes y formas cuadradas a una imagen de un televisor probablemente la forma del televisor se activará con dicho filtros. Dentro del proceso de entrenamiento la red aprende a detectar estas formas que inician con figuras muy básicas hasta evolucionar a detalles y figuras compuestas, aunque no por esto se llaman redes convolucionadas.\n\nEn la imagen 3 se puede observar una arquitectura de red bastante famosa, VGG16. \n\n\n

imagen 3
How convolutional neural networks see the world
Fuente: Blog

\n\nVGG16 cuenta con 5 bloques internos compuestos por capas de convolución y de pooling (este tipo de capas reduce el volumen de los mapas de características, en la imagen 3 en rojo).Cada bloque cuenta con cierta cantidad de capas de convolución, una notación para determinar las capas es especificar el número de bloque y la posición que esta tiene dentro del arreglo.Por ejemplo la capa convolucional dos del bloque uno se representa como :Conv2_1, mientras la capa convolucional tres en el bloque cuatro sería: Conv4_3.
Como se mencionó anteriormente en el proceso de entrenamiento la red aprende múltiples filtros, la siguiente pregunta que debemos realizar es : ¿Qué está viendo la red realmente?, ¿Qué es lo que está detectando esos filtros?\n \n\nLa imagen 4 nos da una respuesta a dichas preguntas. Podemos observar que luego del entrenamiento conv1_1 es capaz de detectar ciertos colores y un par de texturas. Mientras tanto conv2_1 parece ser el resultado de combinar las texturas y colores de conv1_1, , recordemos que en medio de estas capas y de las siguientes que mencionaremos existen otras capas y operaciones que tendrán combinaciones de este tipo.
\nPasando a conv3_1, podemos hacer dos observaciones, la primera es que los colores se ven mucho más granulados que en las dos capas anteriormente estudiadas y empieza a aparecer forma más definidas como líneas diagonales curvas o puntos bien detallados.
\nConv4_1 nos muetra un salto enorme respecto a conv3_1. Podemos identificar con facilidad formas más específicas, agrupaciones de líneas, círculos y combinación de colores que se organizan de forma no uniforme.
\nFinalmente, conv5_1, muestra filtros que ya saben detectar formas bien definidas, más delineadas, llevando las imágenes a una representación más abstracta a medida que avanza por las diferentes capas.\n\n\n

imagen 4
How convolutional neural networks see the world
Fuente: Blog de Keras por Francois Chollet

\n\nEl análisis anterior es el pilar de la técnica de transferencia de estilo presentada por León A. Gatys en el articulo Image Style Transfer Using Convolutional Neural Networks. Dicho comportamiento ha sido bastante estudiado y es el que logra que las redes neuronales convolucionales capturen detalles y formas, que a su vez, las vuelven enormemente potentes en tareas de clasificación. Es evidente que se empiezan con estructuras muy primitivas como en conv1_1 hasta llegar a formas más estructuradas en conv5_1.
\nLo importante es entender esta capacidad de las CNN para nuestro tema de interés, es que mientras las primeras capas de la red son más sensibles a los colores y texturas, las últimas capas son capaces de capturar la forma de los objetos. Dicho de otra manera, de las primeras capas capturaremos la representación de la imagen de estilo,luego, de la imagen de contenido obtendremos la representación de alguna de las últimas capas, por ejemplo de conv5_1.\n\nEspecíficamente en el artículo de León A. Gatys se usa para capturar el estilo:conv1_1, conv2_1, conv3_1, conv4_1, conv5_1 y para capturar el contenido : conv5_2\n\n\nDe esa manera el primer paso es tomar una red neuronal entrenada y pasar a través de ella dos imágenes, una para el contenido y otra para el estilo. Luego, capturar las respectivas capas de interés para cada una.\n\nAhora, debemos generar una tercer imagen la cual será el resultado(por ejemplo ver imagen 1) de la combinación de las dos anteriores. En el articulo generan una imagen con ruido gaussiano. Experimentos posteriores de la tesis demuestra que al usar la imagen de contenido como imagen de inicio da resultados más consistentes. En los experimentos usaremos ambas.\n\nLuego, pasaremos la imagen generada por la red extrayendo tanto las capas de contenido como de estilo y calcularemos una pérdida de estilo respecto a las capas obtenidas de la imagen de estilo, y otra pérdida de contenido respecto a las capas de la imagen de contenido.\n\n\n

Funciones de costo

\n\n

Pérdida de estilo

\n\nNecesitamos una forma especial para calcular la perdida de estilo. El estilo esta relacionado con la correlacion que hay entre los pixeles de una imagen. Una matriz Gram nos genera una representacion de como son dichas correlaciones. El siguiente video se muestra una explicacion de como funcion y se opera una matriz Gram.\n\n\n```python\nfrom IPython.display import HTML\nHTML('')\n```\n\n\n\n\n\n\n\n\n

fuente : Udacity

\n\nEn el articulo Image Style Transfer Using Convolutional Neural Networks se muestra el calculo de la matriz gram de la siguiente forma: \n\n\\begin{equation}\nG_{i j}^{l}=\\sum_{k} F_{i k}^{l} F_{j k}^{l}\n\\end{equation}\n\nLuego, podemos calcular el error de las matrices Gram como la diferencia de las matrices Gram para las capas $l$ respectivas entre la imagen de estilo y la imagen generada. En el articulo el error cuadratico esta escrito como :\n\n\\begin{equation}\nE_{l}=\\frac{1}{4 N_{l}^{2} M_{l}^{2}} \\sum_{i, j}\\left(G_{i j}^{l}-A_{i j}^{l}\\right)^{2}\n\\end{equation}\n\nAhora, la perdida de estilo se calcula como la sumatoria de los errores de las matrices Gram para cada capa $l$ multiplicado por un peso que se le da a cada capa. En el articulo dicho peso es el mismo para cada una de las capas.\n\n\\begin{equation}\n\\mathcal{L}_{\\text { style }}(\\vec{a}, \\vec{x})=\\sum_{l=0}^{L} w_{l} E_{l}\n\\end{equation}\n\n

Perdida de contenido

\n\nLa perdida de contenido es la suma de las distancias euclidianas de las capas que representan el contenido. Asi , sea $\\vec{p}$ la imagen original, $\\vec{x}$ la imagen generada y $l$ la capa contenido, la perdida sera.\n\n\\begin{equation}\n\\mathcal{L}_{\\text { content }}(\\vec{p}, \\vec{x}, l)=\\frac{1}{2} \\sum_{i, j}\\left(F_{i j}^{l}-P_{i j}^{l}\\right)^{2}\n\\end{equation}\n\n$F^{l}$ es el mapa de caracteristicas de la capa $l$ de la imagen original, mientras $P^{l}$ es el mapa de caracteristicas de la capa $l$ de la imagen generada.\n\n

Perdida total y actualizacion de imagen

\n\nPara la perdida total se realiza la suma entre las perdidas de estilo y contenido.\n\n\\begin{equation}\n\\mathcal{L}_{\\text { total }}(\\vec{p}, \\vec{a}, \\vec{x})=\\alpha \\mathcal{L}_{\\text { content }}(\\vec{p}, \\vec{x})+\\beta \\mathcal{L}_{\\text { style }}(\\vec{a}, \\vec{x})\n\\end{equation}\n\nDonde alpha $\\alpha$ es el peso que se le dara al contenido y $\\beta$ el peso que se le dara al estilo.\n\nSolo quedaria calcular el gradiente de la perdida total respecto a la imagen generada, de forma tal, que al cumplir cierto numero de iteraciones el error total disminuya y la imagen generada adquiera el contenido de la imagen de contenido y el estilo de la imagen de estilo. Los parametros $\\alpha$ y $\\beta$ son de suma importancia dado que determinaran la forma en como se generara la imagen. El articulo propone ciertas correspondecias para obtener diferentes salidas.\n\n

Estrategia de generación de imagen

\n\nPara finalizar, discutiremos el flujo de lo revisado hasta el momento paso por paso.\n\n\nEn primer lugar pasamos la imagen de estilo y la imagen de contenido a través de la red neuronal ya entrenada. Obtenemos las capas convolucionales que deseemos de cada una de ellas. Según el artículo para la imagen de estilo obtendremos los mapas de características ubicados en las capas conv1_1, conv2_1, conv3_1, conv4_1, conv5_1 , l mismo tiempo, para la imagen de contenido obtenemos solo conv5_2.\n
\n\nPara conv1_1, conv2_1, conv3_1, conv4_1, conv5_1, conv5_2 de la imagen de estilo calculamos las matrices gram.\n\nPosteriormente necesitamos una imagen que nos servirá de lienzo para la imagen generada. Esta imagen puede ser una imagen que generemos con ruido (puede ser una imagen generada mediante una distribución normal) o la imagen de contenido. Los experimentos mostrados en la tesis y el artículo muestran que si se inicia con la imagen de contenido la transferencia de estilo es más estable y fiel al contenido. Esta imagen generada se pasa por la red neuronal y se extrae de ella tanto las capas que se obtuvieron de la imagen de estilo como la de contenido, en otras palabras, de la imagen generada se obtendrá.\n\nAhora, calculamos las matrices gram de la imagen generada y realizamos la pérdida de estilo respecto a las matrices gram de la imagen de estilo. De forma similar, calculamos la diferencia de conv5_2 de la imagen generada respecto a la imagen de contenido.\n\nSumamos ambos errores y a continuación calculamos los gradiente de la imagen generada respecto al error total. Repetimos este proceso el número de optimización que se le quieran realizar a la imagen generada. A mayor número de iteración se espera que la imagen generada tenga mejores resultados.\n\n", "meta": {"hexsha": "dc3fb20511604221225dfc9abe6765f13239c207", "size": 21787, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/1.Aprendizaje profundo para la transferencia de estilo.ipynb", "max_stars_repo_name": "cactusAi/DeepTransferStyle", "max_stars_repo_head_hexsha": "b49014e952413934e46e868b817a178811fd9681", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-29T22:18:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:18:34.000Z", "max_issues_repo_path": "notebooks/1.Aprendizaje profundo para la transferencia de estilo.ipynb", "max_issues_repo_name": "cactusAi/DeepTransferStyle", "max_issues_repo_head_hexsha": "b49014e952413934e46e868b817a178811fd9681", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-05-21T15:32:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T00:06:57.000Z", "max_forks_repo_path": "notebooks/1.Aprendizaje profundo para la transferencia de estilo.ipynb", "max_forks_repo_name": "cactusAi/DeepTransferStyle", "max_forks_repo_head_hexsha": "b49014e952413934e46e868b817a178811fd9681", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-04-08T20:02:01.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T20:02:01.000Z", "avg_line_length": 56.8851174935, "max_line_length": 1761, "alphanum_fraction": 0.6877954744, "converted": true, "num_tokens": 4523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2220755216739912}} {"text": "\n# PHY321: Two-body problems and Gravitational Forces\n\n \n**[Morten Hjorth-Jensen](http://mhjgit.github.io/info/doc/web/)**, Department of Physics and Astronomy and Facility for Rare Ion Beams (FRIB), Michigan State University, USA and Department of Physics, University of Oslo, Norway\n\nDate: **Mar 22, 2021**\n\nCopyright 1999-2021, [Morten Hjorth-Jensen](http://mhjgit.github.io/info/doc/web/). Released under CC Attribution-NonCommercial 4.0 license\n\n\n\n\n## Aims and Overarching Motivation\n\n\n### Monday\n\n1. Computational topics: functions and classes (continuation of Julie's lecture from last Friday).\n\n2. From the harmonic oscillator to the gravitational force and Kepler's laws\n\n**Reading suggestion**: Taylor section 8.4 and Lecture notes\n\n\n### Wednesday\n\n1. Discussion of elliptical orbits and Kepler's laws\n\n**Reading suggestion**: Taylor sections 8.5-8.8\n\n### Friday\n\n1. Physical interpretation of various orbit types and start discussion two-body scattering\n\n**Reading suggestion**: Taylor section 8.5-8.8 and sections 14.1-14.2 \n\n\n\n\n## Deriving Elliptical Orbits\n\nKepler's laws state that a gravitational orbit should be an ellipse\nwith the source of the gravitational field at one focus. Deriving this\nis surprisingly messy. To do this, we first use angular momentum\nconservation to transform the equations of motion so that it is in\nterms of $r$ and $\\theta$ instead of $r$ and $t$. The overall strategy\nis to\n\n\n1. Find equations of motion for $r$ and $t$ with no angle ($\\theta$) mentioned, i.e. $d^2r/dt^2=\\cdots$. Angular momentum conservation will be used, and the equation will involve the angular momentum $L$.\n\n2. Use angular momentum conservation to find an expression for $\\dot{\\theta}$ in terms of $r$.\n\n3. Use the chain rule to convert the equations of motions for $r$, an expression involving $r,\\dot{r}$ and $\\ddot{r}$, to one involving $r,dr/d\\theta$ and $d^2r/d\\theta^2$. This is quitecomplicated because the expressions will also involve a substitution $u=1/r$ so that one finds an expression in terms of $u$ and $\\theta$.\n\n4. Once $u(\\theta)$ is found, you need to show that this can be converted to the familiar form for an ellipse.\n\nThe equations of motion give\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:radialeqofmotion} \\tag{1}\n\\frac{d}{dt}r^2&=&\\frac{d}{dt}(x^2+y^2)=2x\\dot{x}+2y\\dot{y}=2r\\dot{r},\\\\\n\\nonumber\n\\dot{r}&=&\\frac{x}{r}\\dot{x}+\\frac{y}{r}\\dot{y},\\\\\n\\nonumber\n\\ddot{r}&=&\\frac{x}{r}\\ddot{x}+\\frac{y}{r}\\ddot{y}\n+\\frac{\\dot{x}^2+\\dot{y}^2}{r}\n-\\frac{\\dot{r}^2}{r}.\n\\end{eqnarray}\n$$\n\nRecognizing that the numerator of the third term is the velocity squared, and that it can be written in polar coordinates,\n\n\n
\n\n$$\n\\begin{equation}\nv^2=\\dot{x}^2+\\dot{y}^2=\\dot{r}^2+r^2\\dot{\\theta}^2,\n\\label{_auto1} \\tag{2}\n\\end{equation}\n$$\n\none can write $\\ddot{r}$ as\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:radialeqofmotion2} \\tag{3}\n\\ddot{r}&=&\\frac{F_x\\cos\\theta+F_y\\sin\\theta}{m}+\\frac{\\dot{r}^2+r^2\\dot{\\theta}^2}{r}-\\frac{\\dot{r}^2}{r}\\\\\n\\nonumber\n&=&\\frac{F}{m}+\\frac{r^2\\dot{\\theta}^2}{r}\\\\\n\\nonumber\nm\\ddot{r}&=&F+\\frac{L^2}{mr^3}.\n\\end{eqnarray}\n$$\n\nThis derivation used the fact that the force was radial,\n$F=F_r=F_x\\cos\\theta+F_y\\sin\\theta$, and that angular momentum is\n$L=mrv_{\\theta}=mr^2\\dot{\\theta}$. The term $L^2/mr^3=mv^2/r$ behaves\nlike an additional force. Sometimes this is referred to as a\ncentrifugal force, but it is not a force. Instead, it is the\nconsequence of considering the motion in a rotating (and therefore\naccelerating) frame.\n\nNow, we switch to the particular case of an attractive inverse square\nforce, $F=-\\alpha/r^2$, and show that the trajectory, $r(\\theta)$, is\nan ellipse. To do this we transform derivatives w.r.t. time to\nderivatives w.r.t. $\\theta$ using the chain rule combined with angular\nmomentum conservation, $\\dot{\\theta}=L/mr^2$.\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:rtotheta} \\tag{4}\n\\dot{r}&=&\\frac{dr}{d\\theta}\\dot{\\theta}=\\frac{dr}{d\\theta}\\frac{L}{mr^2},\\\\\n\\nonumber\n\\ddot{r}&=&\\frac{d^2r}{d\\theta^2}\\dot{\\theta}^2\n+\\frac{dr}{d\\theta}\\left(\\frac{d}{dr}\\frac{L}{mr^2}\\right)\\dot{r}\\\\\n\\nonumber\n&=&\\frac{d^2r}{d\\theta^2}\\left(\\frac{L}{mr^2}\\right)^2\n-2\\frac{dr}{d\\theta}\\frac{L}{mr^3}\\dot{r}\\\\\n\\nonumber\n&=&\\frac{d^2r}{d\\theta^2}\\left(\\frac{L}{mr^2}\\right)^2\n-\\frac{2}{r}\\left(\\frac{dr}{d\\theta}\\right)^2\\left(\\frac{L}{mr^2}\\right)^2\n\\end{eqnarray}\n$$\n\nEquating the two expressions for $\\ddot{r}$ in Eq.s ([3](#eq:radialeqofmotion2)) and ([4](#eq:rtotheta)) eliminates all the derivatives w.r.t. time, and provides a differential equation with only derivatives w.r.t. $\\theta$,\n\n\n
\n\n$$\n\\begin{equation}\n\\label{eq:rdotdot} \\tag{5}\n\\frac{d^2r}{d\\theta^2}\\left(\\frac{L}{mr^2}\\right)^2\n-\\frac{2}{r}\\left(\\frac{dr}{d\\theta}\\right)^2\\left(\\frac{L}{mr^2}\\right)^2\n=\\frac{F}{m}+\\frac{L^2}{m^2r^3},\n\\end{equation}\n$$\n\nthat when solved yields the trajectory, i.e. $r(\\theta)$. Up to this\npoint the expressions work for any radial force, not just forces that\nfall as $1/r^2$.\n\nThe trick to simplifying this differential equation for the inverse\nsquare problems is to make a substitution, $u\\equiv 1/r$, and rewrite\nthe differential equation for $u(\\theta)$.\n\n$$\n\\begin{eqnarray}\nr&=&1/u,\\\\\n\\nonumber\n\\frac{dr}{d\\theta}&=&-\\frac{1}{u^2}\\frac{du}{d\\theta},\\\\\n\\nonumber\n\\frac{d^2r}{d\\theta^2}&=&\\frac{2}{u^3}\\left(\\frac{du}{d\\theta}\\right)^2-\\frac{1}{u^2}\\frac{d^2u}{d\\theta^2}.\n\\end{eqnarray}\n$$\n\nPlugging these expressions into Eq. ([5](#eq:rdotdot)) gives an\nexpression in terms of $u$, $du/d\\theta$, and $d^2u/d\\theta^2$. After\nsome tedious algebra,\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{d^2u}{d\\theta^2}=-u-\\frac{F m}{L^2u^2}.\n\\label{_auto2} \\tag{6}\n\\end{equation}\n$$\n\nFor the attractive inverse square law force, $F=-\\alpha u^2$,\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{d^2u}{d\\theta^2}=-u+\\frac{m\\alpha}{L^2}.\n\\label{_auto3} \\tag{7}\n\\end{equation}\n$$\n\nThe solution has two arbitrary constants, $A$ and $\\theta_0$,\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:Ctrajectory} \\tag{8}\nu&=&\\frac{m\\alpha}{L^2}+A\\cos(\\theta-\\theta_0),\\\\\n\\nonumber\nr&=&\\frac{1}{(m\\alpha/L^2)+A\\cos(\\theta-\\theta_0)}.\n\\end{eqnarray}\n$$\n\nThe radius will be at a minimum when $\\theta=\\theta_0$ and at a\nmaximum when $\\theta=\\theta_0+\\pi$. The constant $A$ is related to the\neccentricity of the orbit. When $A=0$ the radius is a constant\n$r=L^2/(m\\alpha)$, and the motion is circular. If one solved the\nexpression $mv^2/r=-\\alpha/r^2$ for a circular orbit, using the\nsubstitution $v=L/(mr)$, one would reproduce the expression\n$r=L^2/(m\\alpha)$.\n\nThe form describing the elliptical trajectory in\nEq. ([8](#eq:Ctrajectory)) can be identified as an ellipse with one\nfocus being the center of the ellipse by considering the definition of\nan ellipse as being the points such that the sum of the two distances\nbetween the two foci are a constant. Making that distance $2D$, the\ndistance between the two foci as $2a$, and putting one focus at the\norigin,\n\n$$\n\\begin{eqnarray}\n2D&=&r+\\sqrt{(r\\cos\\theta-2a)^2+r^2\\sin^2\\theta},\\\\\n\\nonumber\n4D^2+r^2-4Dr&=&r^2+4a^2-4ar\\cos\\theta,\\\\\n\\nonumber\nr&=&\\frac{D^2-a^2}{D+a\\cos\\theta}=\\frac{1}{D/(D^2-a^2)-a\\cos\\theta/(D^2-a^2)}.\n\\end{eqnarray}\n$$\n\nBy inspection, this is the same form as Eq. ([8](#eq:Ctrajectory)) with $D/(D^2-a^2)=m\\alpha/L^2$ and $a/(D^2-a^2)=A$.\n\n\nLet us remind ourselves about what an ellipse is before we proceed.\n\n\n```python\n%matplotlib inline\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom math import pi\n\nu=1. #x-position of the center\nv=0.5 #y-position of the center\na=2. #radius on the x-axis\nb=1.5 #radius on the y-axis\n\nt = np.linspace(0, 2*pi, 100)\nplt.plot( u+a*np.cos(t) , v+b*np.sin(t) )\nplt.grid(color='lightgray',linestyle='--')\nplt.show()\n```\n\n## Effective or Centrifugal Potential\n\nThe total energy of a particle is\n\n$$\n\\begin{eqnarray}\nE&=&V(r)+\\frac{1}{2}mv_\\theta^2+\\frac{1}{2}m\\dot{r}^2\\\\\n\\nonumber\n&=&V(r)+\\frac{1}{2}mr^2\\dot{\\theta}^2+\\frac{1}{2}m\\dot{r}^2\\\\\n\\nonumber\n&=&V(r)+\\frac{L^2}{2mr^2}+\\frac{1}{2}m\\dot{r}^2.\n\\end{eqnarray}\n$$\n\nThe second term then contributes to the energy like an additional\nrepulsive potential. The term is sometimes referred to as the\n\"centrifugal\" potential, even though it is actually the kinetic energy\nof the angular motion. Combined with $V(r)$, it is sometimes referred\nto as the \"effective\" potential,\n\n$$\n\\begin{eqnarray}\nV_{\\rm eff}(r)&=&V(r)+\\frac{L^2}{2mr^2}.\n\\end{eqnarray}\n$$\n\nNote that if one treats the effective potential like a real potential, one would expect to be able to generate an effective force,\n\n$$\n\\begin{eqnarray}\nF_{\\rm eff}&=&-\\frac{d}{dr}V(r) -\\frac{d}{dr}\\frac{L^2}{2mr^2}\\\\\n\\nonumber\n&=&F(r)+\\frac{L^2}{mr^3}=F(r)+m\\frac{v_\\perp^2}{r},\n\\end{eqnarray}\n$$\n\nwhich is indeed matches the form for $m\\ddot{r}$ in Eq. ([3](#eq:radialeqofmotion2)), which included the **centrifugal** force.\n\nThe following code plots this effective potential for a simple choice of parameters, with a standard gravitational potential $-\\alpha/r$. Here we have chosen $L=m=\\alpha=1$.\n\n\n```python\n# Common imports\nimport numpy as np\nfrom math import *\nimport matplotlib.pyplot as plt\n\nDeltax = 0.01\n#set up arrays\nxinitial = 0.3\nxfinal = 5.0\nalpha = 1.0 # spring constant\nm = 1.0 # mass, you can change these\nAngMom = 1.0 # The angular momentum\nn = ceil((xfinal-xinitial)/Deltax)\nx = np.zeros(n)\nfor i in range(n):\n x[i] = xinitial+i*Deltax\nV = np.zeros(n)\nV = -alpha/x+0.5*AngMom*AngMom/(m*x*x)\n# Plot potential\nfig, ax = plt.subplots()\nax.set_xlabel('r[m]')\nax.set_ylabel('V[J]')\nax.plot(x, V)\nfig.tight_layout()\nplt.show()\n```\n\n### Gravitational force example\n\nUsing the above parameters, we can now study the evolution of the system using for example the velocity Verlet method.\nThis is done in the code here for an initial radius equal to the minimum of the potential well. We seen then that the radius is always the same and corresponds to a circle (the radius is always constant).\n\n\n```python\n# Common imports\nimport numpy as np\nimport pandas as pd\nfrom math import *\nimport matplotlib.pyplot as plt\nimport os\n\n# Where to save the figures and data files\nPROJECT_ROOT_DIR = \"Results\"\nFIGURE_ID = \"Results/FigureFiles\"\nDATA_ID = \"DataFiles/\"\n\nif not os.path.exists(PROJECT_ROOT_DIR):\n os.mkdir(PROJECT_ROOT_DIR)\n\nif not os.path.exists(FIGURE_ID):\n os.makedirs(FIGURE_ID)\n\nif not os.path.exists(DATA_ID):\n os.makedirs(DATA_ID)\n\ndef image_path(fig_id):\n return os.path.join(FIGURE_ID, fig_id)\n\ndef data_path(dat_id):\n return os.path.join(DATA_ID, dat_id)\n\ndef save_fig(fig_id):\n plt.savefig(image_path(fig_id) + \".png\", format='png')\n\n\n# Simple Gravitational Force -alpha/r\n \nDeltaT = 0.01\n#set up arrays \ntfinal = 100.0\nn = ceil(tfinal/DeltaT)\n# set up arrays for t, v and r\nt = np.zeros(n)\nv = np.zeros(n)\nr = np.zeros(n)\n# Constants of the model, setting all variables to one for simplicity\nalpha = 1.0\nAngMom = 1.0 # The angular momentum\nm = 1.0 # scale mass to one\nc1 = AngMom*AngMom/(m*m)\nc2 = AngMom*AngMom/m\nrmin = (AngMom*AngMom/m/alpha)\n# Initial conditions\nr0 = rmin\nv0 = 0.0\nr[0] = r0\nv[0] = v0\n# Start integrating using the Velocity-Verlet method\nfor i in range(n-1):\n # Set up acceleration\n a = -alpha/(r[i]**2)+c1/(r[i]**3)\n # update velocity, time and position using the Velocity-Verlet method\n r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a\n anew = -alpha/(r[i+1]**2)+c1/(r[i+1]**3)\n v[i+1] = v[i] + 0.5*DeltaT*(a+anew)\n t[i+1] = t[i] + DeltaT\n # Plot position as function of time\nfig, ax = plt.subplots(2,1)\nax[0].set_xlabel('time')\nax[0].set_ylabel('radius')\nax[0].plot(t,r)\nax[1].set_xlabel('time')\nax[1].set_ylabel('Velocity')\nax[1].plot(t,v)\nsave_fig(\"RadialGVV\")\nplt.show()\n```\n\nChanging the value of the initial position to a value where the energy is positive, leads to an increasing radius with time, a so-called unbound orbit. Choosing on the other hand an initial radius that corresponds to a negative energy and different from the minimum value leads to a radius that oscillates back and forth between two values. \n\n### Harmonic Oscillator in two dimensions\n\nConsider a particle of mass $m$ in a 2-dimensional harmonic oscillator with potential\n\n$$\nV=\\frac{1}{2}kr^2=\\frac{1}{2}k(x^2+y^2).\n$$\n\nIf the orbit has angular momentum $L$, we can find the radius and angular velocity of the circular orbit as well as the b) the angular frequency of small radial perturbations.\n\nWe consider the effective potential. The radius of a circular orbit is at the minimum of the potential (where the effective force is zero).\nThe potential is plotted here with the parameters $k=m=0.1$ and $L=1.0$.\n\n\n```python\n# Common imports\nimport numpy as np\nfrom math import *\nimport matplotlib.pyplot as plt\n\nDeltax = 0.01\n#set up arrays\nxinitial = 0.5\nxfinal = 3.0\nk = 1.0 # spring constant\nm = 1.0 # mass, you can change these\nAngMom = 1.0 # The angular momentum\nn = ceil((xfinal-xinitial)/Deltax)\nx = np.zeros(n)\nfor i in range(n):\n x[i] = xinitial+i*Deltax\nV = np.zeros(n)\nV = 0.5*k*x*x+0.5*AngMom*AngMom/(m*x*x)\n# Plot potential\nfig, ax = plt.subplots()\nax.set_xlabel('r[m]')\nax.set_ylabel('V[J]')\nax.plot(x, V)\nfig.tight_layout()\nplt.show()\n```\n\n$$\n\\begin{eqnarray*}\nV_{\\rm eff}&=&\\frac{1}{2}kr^2+\\frac{L^2}{2mr^2}\n\\end{eqnarray*}\n$$\n\nThe effective potential looks like that of a harmonic oscillator for\nlarge $r$, but for small $r$, the centrifugal potential repels the\nparticle from the origin. The combination of the two potentials has a\nminimum for at some radius $r_{\\rm min}$.\n\n$$\n\\begin{eqnarray*}\n0&=&kr_{\\rm min}-\\frac{L^2}{mr_{\\rm min}^3},\\\\\nr_{\\rm min}&=&\\left(\\frac{L^2}{mk}\\right)^{1/4},\\\\\n\\dot{\\theta}&=&\\frac{L}{mr_{\\rm min}^2}=\\sqrt{k/m}.\n\\end{eqnarray*}\n$$\n\nFor particles at $r_{\\rm min}$ with $\\dot{r}=0$, the particle does not\naccelerate and $r$ stays constant, i.e. a circular orbit. The radius\nof the circular orbit can be adjusted by changing the angular momentum\n$L$.\n\nFor the above parameters this minimum is at $r_{\\rm min}=1$.\n\n Now consider small vibrations about $r_{\\rm min}$. The effective spring constant is the curvature of the effective potential.\n\n$$\n\\begin{eqnarray*}\nk_{\\rm eff}&=&\\left.\\frac{d^2}{dr^2}V_{\\rm eff}(r)\\right|_{r=r_{\\rm min}}=k+\\frac{3L^2}{mr_{\\rm min}^4}\\\\\n&=&4k,\\\\\n\\omega&=&\\sqrt{k_{\\rm eff}/m}=2\\sqrt{k/m}=2\\dot{\\theta}.\n\\end{eqnarray*}\n$$\n\nBecause the radius oscillates with twice the angular frequency,\nthe orbit has two places where $r$ reaches a minimum in one\ncycle. This differs from the inverse-square force where there is one\nminimum in an orbit. One can show that the orbit for the harmonic\noscillator is also elliptical, but in this case the center of the\npotential is at the center of the ellipse, not at one of the foci.\n\nThe solution is also simple to write down exactly in Cartesian coordinates. The $x$ and $y$ equations of motion separate,\n\n$$\n\\begin{eqnarray*}\n\\ddot{x}&=&-kx,\\\\\n\\ddot{y}&=&-ky.\n\\end{eqnarray*}\n$$\n\nThe general solution can be expressed as\n\n$$\n\\begin{eqnarray*}\nx&=&A\\cos\\omega_0 t+B\\sin\\omega_0 t,\\\\\ny&=&C\\cos\\omega_0 t+D\\sin\\omega_0 t.\n\\end{eqnarray*}\n$$\n\nThe code here finds the solution for $x$ and $y$ using the code we\ndeveloped in homework 5 and 6 and the midterm. Note that this code is\ntailored to run in Cartesian coordinates. There is thus no angular\nmomentum dependent term.\n\nHere we have chose initial conditions that\ncorrespond to the minimum of the effective potential\n$r_{\\mathrm{min}}$. We have chosen $x_0=r_{\\mathrm{min}}$ and\n$y_0=0$. Similarly, we use the centripetal acceleration to determine\nthe initial velocity so that we have a circular motion (see back to the\nlast question of the midterm). This means that we set the centripetal\nacceleration $v^2/r$ equal to the force from the harmonic oscillator $-k\\boldsymbol{r}$. Taking the\nmagnitude of $\\boldsymbol{r}$ we have then\n$v^2/r=k/mr$, which gives $v=\\pm\\omega_0r$. \n\nSince the code here solves the equations of motion in cartesian\ncoordinates and the harmonic oscillator potential leads to forces in\nthe $x$- and $y$-directions that are decoupled, we have to select the initial velocities and positions so that we don't get that for example $y(t)=0$.\n\nWe set $x_0$ to be different from zero and $v_{y0}$ to be different from zero.\n\n\n```python\n\nDeltaT = 0.00001\n#set up arrays \ntfinal = 10.0\nn = ceil(tfinal/DeltaT)\n# set up arrays\nt = np.zeros(n)\nv = np.zeros((n,2))\nr = np.zeros((n,2))\nradius = np.zeros(n)\n# Constants of the model\nk = 1.0 # spring constant\nm = 1.0 # mass, you can change these\nomega02 = k/m # Frequency\nAngMom = 1.0 # The angular momentum\n# Potential minimum\nrmin = (AngMom*AngMom/k/m)**0.25\n# Initial conditions as compact 2-dimensional arrays, x0=rmin and y0 = 0\nx0 = rmin; y0= 0.0\nr0 = np.array([x0,y0])\n#vy0 = 2.0 ; vx0 = 0.0 \nvy0 = sqrt(omega02)*rmin; vx0 = 0.0\nv0 = np.array([vx0,vy0])\nr[0] = r0\nv[0] = v0\n# Start integrating using the Velocity-Verlet method\nfor i in range(n-1):\n # Set up the acceleration\n a = -r[i]*omega02 \n # update velocity, time and position using the Velocity-Verlet method\n r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a\n anew = -r[i+1]*omega02 \n v[i+1] = v[i] + 0.5*DeltaT*(a+anew)\n t[i+1] = t[i] + DeltaT\n# Plot position as function of time\nradius = np.sqrt(r[:,0]**2+r[:,1]**2)\nfig, ax = plt.subplots(3,1)\nax[0].set_xlabel('time')\nax[0].set_ylabel('radius squared')\nax[0].plot(t,r[:,0]**2+r[:,1]**2)\nax[1].set_xlabel('time')\nax[1].set_ylabel('x position')\nax[1].plot(t,r[:,0])\nax[2].set_xlabel('time')\nax[2].set_ylabel('y position')\nax[2].plot(t,r[:,1])\n\nfig.tight_layout()\nsave_fig(\"2DimHOVV\")\nplt.show()\n```\n\nWe see that the radius (to within a given error), we obtain a constant radius.\n\n\nThe following code shows first how we can solve this problem using the radial degrees of freedom only.\nHere we need to add the explicit centrifugal barrier. Note that the variable $r$ depends only on time. There is no $x$ and $y$ directions\nsince we have transformed the equations to polar coordinates.\n\n\n```python\nDeltaT = 0.01\n#set up arrays \ntfinal = 10.0\nn = ceil(tfinal/DeltaT)\n# set up arrays for t, v and r\nt = np.zeros(n)\nv = np.zeros(n)\nr = np.zeros(n)\nE = np.zeros(n)\n# Constants of the model\nAngMom = 1.0 # The angular momentum\nm = 1.0\nk = 1.0\nomega02 = k/m\nc1 = AngMom*AngMom/(m*m)\nc2 = AngMom*AngMom/m\nrmin = (AngMom*AngMom/k/m)**0.25\n# Initial conditions\nr0 = rmin\nv0 = 0.0\nr[0] = r0\nv[0] = v0\nE[0] = 0.5*m*v0*v0+0.5*k*r0*r0+0.5*c2/(r0*r0)\n# Start integrating using the Velocity-Verlet method\nfor i in range(n-1):\n # Set up acceleration\n a = -r[i]*omega02+c1/(r[i]**3) \n # update velocity, time and position using the Velocity-Verlet method\n r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a\n anew = -r[i+1]*omega02+c1/(r[i+1]**3)\n v[i+1] = v[i] + 0.5*DeltaT*(a+anew)\n t[i+1] = t[i] + DeltaT\n E[i+1] = 0.5*m*v[i+1]*v[i+1]+0.5*k*r[i+1]*r[i+1]+0.5*c2/(r[i+1]*r[i+1])\n # Plot position as function of time\nfig, ax = plt.subplots(2,1)\nax[0].set_xlabel('time')\nax[0].set_ylabel('radius')\nax[0].plot(t,r)\nax[1].set_xlabel('time')\nax[1].set_ylabel('Energy')\nax[1].plot(t,E)\nsave_fig(\"RadialHOVV\")\nplt.show()\n```\n\nWith some work using double angle formulas, one can calculate\n\n$$\n\\begin{eqnarray*}\nr^2&=&x^2+y^2\\\\\n\\nonumber\n&=&(A^2+C^2)\\cos^2(\\omega_0t)+(B^2+D^2)\\sin^2\\omega_0t+(AB+CD)\\cos(\\omega_0t)\\sin(\\omega_0t)\\\\\n\\nonumber\n&=&\\alpha+\\beta\\cos 2\\omega_0 t+\\gamma\\sin 2\\omega_0 t,\\\\\n\\alpha&=&\\frac{A^2+B^2+C^2+D^2}{2},~~\\beta=\\frac{A^2-B^2+C^2-D^2}{2},~~\\gamma=AB+CD,\\\\\nr^2&=&\\alpha+(\\beta^2+\\gamma^2)^{1/2}\\cos(2\\omega_0 t-\\delta),~~~\\delta=\\arctan(\\gamma/\\beta),\n\\end{eqnarray*}\n$$\n\nand see that radius oscillates with frequency $2\\omega_0$. The\nfactor of two comes because the oscillation $x=A\\cos\\omega_0t$ has two\nmaxima for $x^2$, one at $t=0$ and one a half period later.\n\n\n\n\n## Stability of Orbits\n\nThe effective force can be extracted from the effective potential, $V_{\\rm eff}$. Beginning from the equations of motion, Eq. ([1](#eq:radialeqofmotion)), for $r$,\n\n$$\n\\begin{eqnarray}\nm\\ddot{r}&=&F+\\frac{L^2}{mr^3}\\\\\n\\nonumber\n&=&F_{\\rm eff}\\\\\n\\nonumber\n&=&-\\partial_rV_{\\rm eff},\\\\\n\\nonumber\nF_{\\rm eff}&=&-\\partial_r\\left[V(r)+(L^2/2mr^2)\\right].\n\\end{eqnarray}\n$$\n\nFor a circular orbit, the radius must be fixed as a function of time,\nso one must be at a maximum or a minimum of the effective\npotential. However, if one is at a maximum of the effective potential\nthe radius will be unstable. For the attractive Coulomb force the\neffective potential will be dominated by the $-\\alpha/r$ term for\nlarge $r$ because the centrifugal part falls off more quickly, $\\sim\n1/r^2$. At low $r$ the centrifugal piece wins and the effective\npotential is repulsive. Thus, the potential must have a minimum\nsomewhere with negative potential. The circular orbits are then stable\nto perturbation.\n\n\nThe effective potential is sketched for two cases, a $1/r$ attractive\npotential and a $1/r^3$ attractive potential. The $1/r$ case has a\nstable minimum, whereas the circular orbit in the $1/r^3$ case is\nunstable.\n\n\nIf one considers a potential that falls as $1/r^3$, the situation is\nreversed and the point where $\\partial_rV$ disappears will be a local\nmaximum rather than a local minimum. **Fig to come here with code**\n\nThe repulsive centrifugal piece dominates at large $r$ and the attractive\nCoulomb piece wins out at small $r$. The circular orbit is then at a\nmaximum of the effective potential and the orbits are unstable. It is\nthe clear that for potentials that fall as $r^n$, that one must have\n$n>-2$ for the orbits to be stable.\n\n\nConsider a potential $V(r)=\\beta r$. For a particle of mass $m$ with\nangular momentum $L$, find the angular frequency of a circular\norbit. Then find the angular frequency for small radial perturbations.\n\n\nFor the circular orbit you search for the position $r_{\\rm min}$ where the effective potential is minimized,\n\n$$\n\\begin{eqnarray*}\n\\partial_r\\left\\{\\beta r+\\frac{L^2}{2mr^2}\\right\\}&=&0,\\\\\n\\beta&=&\\frac{L^2}{mr_{\\rm min}^3},\\\\\nr_{\\rm min}&=&\\left(\\frac{L^2}{\\beta m}\\right)^{1/3},\\\\\n\\dot{\\theta}&=&\\frac{L}{mr_{\\rm min}^2}=\\frac{\\beta^{2/3}}{(mL)^{1/3}}\n\\end{eqnarray*}\n$$\n\nNow, we can find the angular frequency of small perturbations about the circular orbit. To do this we find the effective spring constant for the effective potential,\n\n$$\n\\begin{eqnarray*}\nk_{\\rm eff}&=&\\partial_r^2 \\left.V_{\\rm eff}\\right|_{r_{\\rm min}}\\\\\n&=&\\frac{3L^2}{mr_{\\rm min}^4},\\\\\n\\omega&=&\\sqrt{\\frac{k_{\\rm eff}}{m}}\\\\\n&=&\\frac{\\beta^{2/3}}{(mL)^{1/3}}\\sqrt{3}.\n\\end{eqnarray*}\n$$\n\nIf the two frequencies, $\\dot{\\theta}$ and $\\omega$, differ by an\ninteger factor, the orbit's trajectory will repeat itself each time\naround. This is the case for the inverse-square force,\n$\\omega=\\dot{\\theta}$, and for the harmonic oscillator,\n$\\omega=2\\dot{\\theta}$. In this case, $\\omega=\\sqrt{3}\\dot{\\theta}$,\nand the angles at which the maxima and minima occur change with each\norbit.\n\n\n### Code example with gravitional force\n\nThe code example here is meant to illustrate how we can make a plot of the final orbit. We solve the equations in polar coordinates (the example here uses the minimum of the potential as initial value) and then we transform back to cartesian coordinates and plot $x$ versus $y$. We see that we get a perfect circle when we place ourselves at the minimum of the potential energy, as expected.\n\n\n```python\n\n# Simple Gravitational Force -alpha/r\n \nDeltaT = 0.001\n#set up arrays \ntfinal = 10.0\nn = ceil(tfinal/DeltaT)\n# set up arrays for t, v and r\nt = np.zeros(n)\nv = np.zeros(n)\nr = np.zeros(n)\nphi = np.zeros(n)\nx = np.zeros(n)\ny = np.zeros(n)\n# Constants of the model, setting all variables to one for simplicity\nalpha = 1.0\nAngMom = 1.0 # The angular momentum\nm = 1.0 # scale mass to one\nc1 = AngMom*AngMom/(m*m)\nc2 = AngMom*AngMom/m\nrmin = (AngMom*AngMom/m/alpha)\n# Initial conditions, place yourself at the potential min\nr0 = rmin\nv0 = 0.0 # starts at rest\nr[0] = r0\nv[0] = v0\nphi[0] = 0.0\n# Start integrating using the Velocity-Verlet method\nfor i in range(n-1):\n # Set up acceleration\n a = -alpha/(r[i]**2)+c1/(r[i]**3)\n # update velocity, time and position using the Velocity-Verlet method\n r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a\n anew = -alpha/(r[i+1]**2)+c1/(r[i+1]**3)\n v[i+1] = v[i] + 0.5*DeltaT*(a+anew)\n t[i+1] = t[i] + DeltaT\n phi[i+1] = t[i+1]*c2/(r0**2)\n# Find cartesian coordinates for easy plot \nx = r*np.cos(phi)\ny = r*np.sin(phi)\nfig, ax = plt.subplots(3,1)\nax[0].set_xlabel('time')\nax[0].set_ylabel('radius')\nax[0].plot(t,r)\nax[1].set_xlabel('time')\nax[1].set_ylabel('Angle $\\cos{\\phi}$')\nax[1].plot(t,np.cos(phi))\nax[2].set_ylabel('y')\nax[2].set_xlabel('x')\nax[2].plot(x,y)\n\nsave_fig(\"Phasespace\")\nplt.show()\n```\n\nTry to change the initial value for $r$ and see what kind of orbits you get.\nIn order to test different energies, it can be useful to look at the plot of the effective potential discussed above.\n\nHowever, for orbits different from a circle the above code would need modifications in order to allow us to display say an ellipse. For the latter, it is much easier to run our code in cartesian coordinates, as done here. In this code we test also energy conservation and see that it is conserved to numerical precision. The code here is a simple extension of the code we developed for homework 4.\n\n\n```python\n# Common imports\nimport numpy as np\nimport pandas as pd\nfrom math import *\nimport matplotlib.pyplot as plt\n\nDeltaT = 0.01\n#set up arrays \ntfinal = 10.0\nn = ceil(tfinal/DeltaT)\n# set up arrays\nt = np.zeros(n)\nv = np.zeros((n,2))\nr = np.zeros((n,2))\nE = np.zeros(n)\n# Constants of the model\nm = 1.0 # mass, you can change these\nalpha = 1.0\n# Initial conditions as compact 2-dimensional arrays\nx0 = 0.5; y0= 0.0\nr0 = np.array([x0,y0]) \nv0 = np.array([0.0,1.0])\nr[0] = r0\nv[0] = v0\nrabs = sqrt(sum(r[0]*r[0]))\nE[0] = 0.5*m*(v[0,0]**2+v[0,1]**2)-alpha/rabs\n# Start integrating using the Velocity-Verlet method\nfor i in range(n-1):\n # Set up the acceleration\n rabs = sqrt(sum(r[i]*r[i]))\n a = -alpha*r[i]/(rabs**3)\n # update velocity, time and position using the Velocity-Verlet method\n r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a\n rabs = sqrt(sum(r[i+1]*r[i+1]))\n anew = -alpha*r[i+1]/(rabs**3)\n v[i+1] = v[i] + 0.5*DeltaT*(a+anew)\n E[i+1] = 0.5*m*(v[i+1,0]**2+v[i+1,1]**2)-alpha/rabs\n t[i+1] = t[i] + DeltaT\n# Plot position as function of time\nfig, ax = plt.subplots(3,1)\nax[0].set_ylabel('y')\nax[0].set_xlabel('x')\nax[0].plot(r[:,0],r[:,1])\nax[1].set_xlabel('time')\nax[1].set_ylabel('y position')\nax[1].plot(t,r[:,0])\nax[2].set_xlabel('time')\nax[2].set_ylabel('y position')\nax[2].plot(t,r[:,1])\n\nfig.tight_layout()\nsave_fig(\"2DimGravity\")\nplt.show()\nprint(E)\n```\n\n## Scattering and Cross Sections\n\nScattering experiments don't measure entire trajectories. For elastic\ncollisions, they measure the distribution of final scattering angles\nat best. Most experiments use targets thin enough so that the number\nof scatterings is typically zero or one. The cross section, $\\sigma$,\ndescribes the cross-sectional area for particles to scatter with an\nindividual target atom or nucleus. Cross section measurements form the\nbasis for MANY fields of physics. BThe cross section, and the\ndifferential cross section, encapsulates everything measurable for a\ncollision where all that is measured is the final state, e.g. the\noutgoing particle had momentum $\\boldsymbol{p}_f$. y studying cross sections,\none can infer information about the potential interaction between the\ntwo particles. Inferring, or constraining, the potential from the\ncross section is a classic {\\it inverse} problem. Collisions are\neither elastic or inelastic. Elastic collisions are those for which\nthe two bodies are in the same internal state before and after the\ncollision. If the collision excites one of the participants into a\nhigher state, or transforms the particles into different species, or\ncreates additional particles, the collision is inelastic. Here, we\nconsider only elastic collisions.\n\nFor Coulomb forces, the cross section is infinite because the range of\nthe Coulomb force is infinite, but for interactions such as the strong\ninteraction in nuclear or particle physics, there is no long-range\nforce and cross-sections are finite. Even for Coulomb forces, the part\nof the cross section that corresponds to a specific scattering angle,\n$d\\sigma/d\\Omega$, which is a function of the scattering angle\n$\\theta_s$ is still finite.\n\nIf a particle travels through a thin target, the chance the particle\nscatters is $P_{\\rm scatt}=\\sigma dN/dA$, where $dN/dA$ is the number\nof scattering centers per area the particle encounters. If the density\nof the target is $\\rho$ particles per volume, and if the thickness of\nthe target is $t$, the areal density (number of target scatterers per\narea) is $dN/dA=\\rho t$. Because one wishes to quantify the collisions\nindependently of the target, experimentalists measure scattering\nprobabilities, then divide by the areal density to obtain\ncross-sections,\n\n$$\n\\begin{eqnarray}\n\\sigma=\\frac{P_{\\rm scatt}}{dN/dA}.\n\\end{eqnarray}\n$$\n\nInstead of merely stating that a particle collided, one can measure\nthe probability the particle scattered by a given angle. The\nscattering angle $\\theta_s$ is defined so that at zero the particle is\nunscattered and at $\\theta_s=\\pi$ the particle is scattered directly\nbackward. Scattering angles are often described in the center-of-mass\nframe, but that is a detail we will neglect for this first discussion,\nwhere we will consider the scattering of particles moving classically\nunder the influence of fixed potentials $U(\\boldsymbol{r})$. Because the\ndistribution of scattering angles can be measured, one expresses the\ndifferential cross section,\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{d^2\\sigma}{d\\cos\\theta_s~d\\phi}.\n\\label{_auto4} \\tag{9}\n\\end{equation}\n$$\n\nUsually, the literature expresses differential cross sections as\n\n\n
\n\n$$\n\\begin{equation}\nd\\sigma/d\\Omega=\\frac{d\\sigma}{d\\cos\\theta d\\phi}=\\frac{1}{2\\pi}\\frac{d\\sigma}{d\\cos\\theta},\n\\label{_auto5} \\tag{10}\n\\end{equation}\n$$\n\nwhere the last equivalency is true when the scattering does not depend\non the azimuthal angle $\\phi$, as is the case for spherically\nsymmetric potentials.\n\nThe differential solid angle $d\\Omega$ can be thought of as the area\nsubtended by a measurement, $dA_d$, divided by $r^2$, where $r$ is the\ndistance to the detector,\n\n$$\n\\begin{eqnarray}\ndA_d=r^2 d\\Omega.\n\\end{eqnarray}\n$$\n\nWith this definition $d\\sigma/d\\Omega$ is independent of the distance\nfrom which one places the detector, or the size of the detector (as\nlong as it is small).\n\nDifferential scattering cross sections are calculated by assuming a\nrandom distribution of impact parameters $b$. These represent the\ndistance in the $xy$ plane for particles moving in the $z$ direction\nrelative to the scattering center. An impact parameter $b=0$ refers to\nbeing aimed directly at the target's center. The impact parameter\ndescribes the transverse distance from the $z=0$ axis for the\ntrajectory when it is still far away from the scattering center and\nhas not yet passed it. The differential cross section can be expressed\nin terms of the impact parameter,\n\n\n
\n\n$$\n\\begin{equation}\nd\\sigma=2\\pi bdb,\n\\label{_auto6} \\tag{11}\n\\end{equation}\n$$\n\nwhich is the area of a thin ring of radius $b$ and thickness $db$. In\nclassical physics, one can calculate the trajectory given the incoming\nkinetic energy $E$ and the impact parameter if one knows the mass and\npotential. From the trajectory, one then finds the scattering angle\n$\\theta_s(b)$. The differential cross section is then\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{d\\sigma}{d\\Omega}=\\frac{1}{2\\pi}\\frac{d\\sigma}{d\\cos\\theta_s}=b\\frac{db}{d\\cos\\theta_s}=\\frac{b}{(d/db)\\cos\\theta_s(b)}.\n\\label{_auto7} \\tag{12}\n\\end{equation}\n$$\n\nTypically, one would calculate $\\cos\\theta_s$ and $(d/db)\\cos\\theta_s$\nas functions of $b$. This is sufficient to plot the differential cross\nsection as a function of $\\theta_s$.\n\nThe total cross section is\n\n\n
\n\n$$\n\\begin{equation}\n\\sigma_{\\rm tot}=\\int d\\Omega\\frac{d\\sigma}{d\\Omega}=2\\pi\\int d\\cos\\theta_s~\\frac{d\\sigma}{d\\Omega}. \n\\label{_auto8} \\tag{13}\n\\end{equation}\n$$\n\nEven if the total cross section is infinite, e.g. Coulomb forces, one\ncan still have a finite differential cross section as we will see\nlater on.\n\n\nAn asteroid of mass $m$ and kinetic energy $E$ approaches a planet of\nradius $R$ and mass $M$. What is the cross section for the asteroid to\nimpact the planet?\n\n### Solution\n\nCalculate the maximum impact parameter, $b_{\\rm max}$, for which the asteroid will hit the planet. The total cross section for impact is $\\sigma_{\\rm impact}=\\pi b_{\\rm max}^2$. The maximum cross-section can be found with the help of angular momentum conservation. The asteroid's incoming momentum is $p_0=\\sqrt{2mE}$ and the angular momentum is $L=p_0b$. If the asteroid just grazes the planet, it is moving with zero radial kinetic energy at impact. Combining energy and angular momentum conservation and having $p_f$ refer to the momentum of the asteroid at a distance $R$,\n\n$$\n\\begin{eqnarray*}\n\\frac{p_f^2}{2m}-\\frac{GMm}{R}&=&E,\\\\\np_fR&=&p_0b_{\\rm max},\n\\end{eqnarray*}\n$$\n\nallows one to solve for $b_{\\rm max}$,\n\n$$\n\\begin{eqnarray*}\nb_{\\rm max}&=&R\\frac{p_f}{p_0}\\\\\n&=&R\\frac{\\sqrt{2m(E+GMm/R)}}{\\sqrt{2mE}}\\\\\n\\sigma_{\\rm impact}&=&\\pi R^2\\frac{E+GMm/R}{E}.\n\\end{eqnarray*}\n$$\n\n## Rutherford Scattering\n\nThis refers to the calculation of $d\\sigma/d\\Omega$ due to an inverse\nsquare force, $F_{12}=\\pm\\alpha/r^2$ for repulsive/attractive\ninteraction. Rutherford compared the scattering of $\\alpha$ particles\n($^4$He nuclei) off of a nucleus and found the scattering angle at\nwhich the formula began to fail. This corresponded to the impact\nparameter for which the trajectories would strike the nucleus. This\nprovided the first measure of the size of the atomic nucleus. At the\ntime, the distribution of the positive charge (the protons) was\nconsidered to be just as spread out amongst the atomic volume as the\nelectrons. After Rutherford's experiment, it was clear that the radius\nof the nucleus tended to be roughly 4 orders of magnitude smaller than\nthat of the atom, which is less than the size of a football relative\nto Spartan Stadium.\n\n\n\nThe incoming and outgoing angles of the trajectory are at\n$\\pm\\theta'$. They are related to the scattering angle by\n$2\\theta'=\\pi+\\theta_s$.\n\nIn order to calculate differential cross section, we must find how the\nimpact parameter is related to the scattering angle. This requires\nanalysis of the trajectory. We consider our previous expression for\nthe trajectory where we derived the elliptic form for the trajectory,\nEq. ([8](#eq:Ctrajectory)). For that case we considered an attractive\nforce with the particle's energy being negative, i.e. it was\nbound. However, the same form will work for positive energy, and\nrepulsive forces can be considered by simple flipping the sign of\n$\\alpha$. For positive energies, the trajectories will be hyperbolas,\nrather than ellipses, with the asymptotes of the trajectories\nrepresenting the directions of the incoming and outgoing\ntracks. Rewriting Eq. ([8](#eq:Ctrajectory)),\n\n\n
\n\n$$\n\\begin{equation}\\label{eq:ruthtraj} \\tag{14}\nr=\\frac{1}{\\frac{m\\alpha}{L^2}+A\\cos\\theta}.\n\\end{equation}\n$$\n\nOnce $A$ is large enough, which will happen when the energy is\npositive, the denominator will become negative for a range of\n$\\theta$. This is because the scattered particle will never reach\ncertain angles. The asymptotic angles $\\theta'$ are those for which\nthe denominator goes to zero,\n\n\n
\n\n$$\n\\begin{equation}\n\\cos\\theta'=-\\frac{m\\alpha}{AL^2}.\n\\label{_auto9} \\tag{15}\n\\end{equation}\n$$\n\nThe trajectory's point of closest approach is at $\\theta=0$ and the\ntwo angles $\\theta'$, which have this value of $\\cos\\theta'$, are the\nangles of the incoming and outgoing particles. From\nFig (**to come**), one can see that the scattering angle\n$\\theta_s$ is given by,\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:sthetover2} \\tag{16}\n2\\theta'-\\pi&=&\\theta_s,~~~\\theta'=\\frac{\\pi}{2}+\\frac{\\theta_s}{2},\\\\\n\\nonumber\n\\sin(\\theta_s/2)&=&-\\cos\\theta'\\\\\n\\nonumber\n&=&\\frac{m\\alpha}{AL^2}.\n\\end{eqnarray}\n$$\n\nNow that we have $\\theta_s$ in terms of $m,\\alpha,L$ and $A$, we wish\nto re-express $L$ and $A$ in terms of the impact parameter $b$ and the\nenergy $E$. This will set us up to calculate the differential cross\nsection, which requires knowing $db/d\\theta_s$. It is easy to write\nthe angular momentum as\n\n\n
\n\n$$\n\\begin{equation}\nL^2=p_0^2b^2=2mEb^2.\n\\label{_auto10} \\tag{17}\n\\end{equation}\n$$\n\nFinding $A$ is more complicated. To accomplish this we realize that\nthe point of closest approach occurs at $\\theta=0$, so from\nEq. ([14](#eq:ruthtraj))\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:rminofA} \\tag{18}\n\\frac{1}{r_{\\rm min}}&=&\\frac{m\\alpha}{L^2}+A,\\\\\n\\nonumber\nA&=&\\frac{1}{r_{\\rm min}}-\\frac{m\\alpha}{L^2}.\n\\end{eqnarray}\n$$\n\nNext, $r_{\\rm min}$ can be found in terms of the energy because at the\npoint of closest approach the kinetic energy is due purely to the\nmotion perpendicular to $\\hat{r}$ and\n\n\n
\n\n$$\n\\begin{equation}\nE=-\\frac{\\alpha}{r_{\\rm min}}+\\frac{L^2}{2mr_{\\rm min}^2}.\n\\label{_auto11} \\tag{19}\n\\end{equation}\n$$\n\nOne can solve the quadratic equation for $1/r_{\\rm min}$,\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{1}{r_{\\rm min}}=\\frac{m\\alpha}{L^2}+\\sqrt{(m\\alpha/L^2)^2+2mE/L^2}.\n\\label{_auto12} \\tag{20}\n\\end{equation}\n$$\n\nWe can plug the expression for $r_{\\rm min}$ into the expression for $A$, Eq. ([18](#eq:rminofA)),\n\n\n
\n\n$$\n\\begin{equation}\nA=\\sqrt{(m\\alpha/L^2)^2+2mE/L^2}=\\sqrt{(\\alpha^2/(4E^2b^4)+1/b^2}\n\\label{_auto13} \\tag{21}\n\\end{equation}\n$$\n\nFinally, we insert the expression for $A$ into that for the scattering angle, Eq. ([16](#eq:sthetover2)),\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:scattangle} \\tag{22}\n\\sin(\\theta_s/2)&=&\\frac{m\\alpha}{AL^2}\\\\\n\\nonumber\n&=&\\frac{a}{\\sqrt{a^2+b^2}}, ~~a\\equiv \\frac{\\alpha}{2E}\n\\end{eqnarray}\n$$\n\nThe differential cross section can now be found by differentiating the\nexpression for $\\theta_s$ with $b$,\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:rutherford} \\tag{23}\n\\frac{1}{2}\\cos(\\theta_s/2)d\\theta_s&=&\\frac{ab~db}{(a^2+b^2)^{3/2}}=\\frac{bdb}{a^2}\\sin^3(\\theta_s/2),\\\\\n\\nonumber\nd\\sigma&=&2\\pi bdb=\\frac{\\pi a^2}{\\sin^3(\\theta_s/2)}\\cos(\\theta_s/2)d\\theta_s\\\\\n\\nonumber\n&=&\\frac{\\pi a^2}{2\\sin^4(\\theta_s/2)}\\sin\\theta_s d\\theta_s\\\\\n\\nonumber\n\\frac{d\\sigma}{d\\cos\\theta_s}&=&\\frac{\\pi a^2}{2\\sin^4(\\theta_s/2)},\\\\\n\\nonumber\n\\frac{d\\sigma}{d\\Omega}&=&\\frac{a^2}{4\\sin^4(\\theta_s/2)}.\n\\end{eqnarray}\n$$\n\nwhere $a= \\alpha/2E$. This the Rutherford formula for the differential\ncross section. It diverges as $\\theta_s\\rightarrow 0$ because\nscatterings with arbitrarily large impact parameters still scatter to\narbitrarily small scattering angles. The expression for\n$d\\sigma/d\\Omega$ is the same whether the interaction is positive or\nnegative.\n\n\nConsider a particle of mass $m$ and charge $z$ with kinetic energy $E$\n(Let it be the center-of-mass energy) incident on a heavy nucleus of\nmass $M$ and charge $Z$ and radius $R$. Find the angle at which the\nRutherford scattering formula breaks down.\n\n### Solution\n\nLet $\\alpha=Zze^2/(4\\pi\\epsilon_0)$. The scattering angle in Eq. ([22](#eq:scattangle)) is\n\n$$\n\\sin(\\theta_s/2)=\\frac{a}{\\sqrt{a^2+b^2}}, ~~a\\equiv \\frac{\\alpha}{2E}.\n$$\n\nThe impact parameter $b$ for which the point of closest approach\nequals $R$ can be found by using angular momentum conservation,\n\n$$\n\\begin{eqnarray*}\np_0b&=&b\\sqrt{2mE}=Rp_f=R\\sqrt{2m(E-\\alpha/R)},\\\\\nb&=&R\\frac{\\sqrt{2m(E-\\alpha/R)}}{\\sqrt{2mE}}\\\\\n&=&R\\sqrt{1-\\frac{\\alpha}{ER}}.\n\\end{eqnarray*}\n$$\n\nPutting these together\n\n$$\n\\theta_s=2\\sin^{-1}\\left\\{\n\\frac{a}{\\sqrt{a^2+R^2(1-\\alpha/(RE))}}\n\\right\\},~~~a=\\frac{\\alpha}{2E}.\n$$\n\nIt was from this departure of the experimentally measured\n$d\\sigma/d\\Omega$ from the Rutherford formula that allowed Rutherford\nto infer the radius of the gold nucleus, $R$.\n\n\n\nJust like electrodynamics, one can define \"fields\", which for a small\nadditional mass $m$ are the force per mass and the additional\npotential energy per mass. The {\\it gravitational field} related to\nthe force has dimensions of force per mass, or acceleration, and can\nbe labeled $\\boldsymbol{g}(\\boldsymbol{r})$. The potential energy per mass has\ndimensions of energy per mass. This is analogous to the\nelectromagnetic potential, which is the potential energy per charge,\nand the electric field which is the force per charge.\n\nBecause the field $\\boldsymbol{g}$ obeys the same inverse square law for a\npoint mass as the electric field does for a point charge, the\ngravitational field also satisfies a version of Gauss's law,\n\n\n
\n\n$$\n\\begin{equation}\n\\label{eq:GravGauss} \\tag{24}\n\\oint d\\boldsymbol{A}\\cdot\\boldsymbol{g}=-4\\pi GM_{\\rm inside}.\n\\end{equation}\n$$\n\nHere, $M_{\\rm inside}$ is the net mass inside a closed area.\n\nGauss's law can be understood by considering a nozzle that sprays\npaint in all directions uniformly from a point source. Let $B$ be the\nnumber of gallons per minute of paint leaving the nozzle. If the\nnozzle is at the center of a sphere of radius $r$, the paint per\nsquare meter per minute that is deposited on some part of the sphere\nis\n\n$$\n\\begin{eqnarray}\nF(r)&=&\\frac{B}{4\\pi r^2}.\n\\end{eqnarray}\n$$\n\nNow, let $F$ also be assigned a direction, so that it becomes a vector\npointing along the direction of the flying paint. For any surface that\nsurrounds the nozzle, not necessarily a sphere, one can state that\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:paint} \\tag{25}\n\\oint \\boldsymbol{dA}\\cdot\\boldsymbol{F}&=&B,\n\\end{eqnarray}\n$$\n\nregardless of the shape of the surface. This follows because the rate\nat which paint is deposited on the surface should equal the rate at\nwhich it leaves the nozzle. The dot product ensures that only the\ncomponent of $\\boldsymbol{F}$ into the surface contributes to the deposition\nof paint. Similarly, if $\\boldsymbol{F}$ is any radial inverse-square forces,\nthat falls as $B/(4\\pi r^2)$, then one can apply\nEq. ([25](#eq:paint)). For gravitational fields, $B/(4\\pi)$ is replaced\nby $GM$, and one quickly \"derives\" Gauss's law for gravity,\nEq. ([24](#eq:GravGauss)).\n\n\nConsider Earth to have its mass $M$ uniformly distributed in a sphere\nof radius $R$. Find the magnitude of the gravitational acceleration as\na function of the radius $r$ in terms of the acceleration of gravity\nat the surface $g(R)$. Assume $r\n
\n\n$$\n\\begin{equation}\nF=-\\frac{GM\\delta m}{D^2}+2\\frac{GM\\delta m}{D^3}\\Delta D+\\cdots\n\\label{_auto14} \\tag{26}\n\\end{equation}\n$$\n\nIf the $z$ direction points toward the large object, $\\Delta D$ can be\nreferred to as $z$. In the accelerating frame of an observer at the\ncenter of the planet,\n\n\n
\n\n$$\n\\begin{equation}\n\\delta m\\frac{d^2 z}{dt^2}=F-\\delta ma'+{\\rm other~forces~acting~on~} \\delta m,\n\\label{_auto15} \\tag{27}\n\\end{equation}\n$$\n\nwhere $a'$ is the acceleration of the observer. Because $\\delta ma'$\nequals the gravitational force on $\\delta m$ if it were located at the\nplanet's center, one can write\n\n\n
\n\n$$\n\\begin{equation}\nm\\frac{d^2z}{dt^2}=2\\frac{GM\\delta m}{D^3}z+{\\rm other~forces~acting~on~}\\delta m.\n\\label{_auto16} \\tag{28}\n\\end{equation}\n$$\n\nHere the other forces could represent the forces acting on $\\delta m$\nfrom the spherical planet such as the gravitational force or the\ncontact force with the surface. If $\\theta$ is the angle w.r.t. the\n$z$ axis, the effective force acting on $\\delta m$ is\n\n\n
\n\n$$\n\\begin{equation}\nF_{\\rm eff}\\approx 2\\frac{GM\\delta m}{D^3}r\\cos\\theta\\hat{z}+{\\rm other~forces~acting~on~}\\delta m.\n\\label{_auto17} \\tag{29}\n\\end{equation}\n$$\n\nThis first force is the \"tidal\" force. It pulls objects outward from the center of the object. If the object were covered with water, it would distort the objects shape so that the shape would be elliptical, stretched out along the axis pointing toward the large mass $M$. The force is always along (either parallel or antiparallel to) the $\\hat{z}$ direction.\n\n\nConsider the Earth to be a sphere of radius $R$ covered with water,\nwith the gravitational acceleration at the surface noted by $g$. Now\nassume that a distant body provides an additional constant\ngravitational acceleration $\\boldsymbol{a}$ pointed along the $z$ axis. Find\nthe distortion of the radius as a function of $\\theta$. Ignore\nplanetary rotation and assume $a<\n\n## Rollout collection\n\nRollout collection is designed to be as much `plug-n-play` as possible, i.e. it\nsupports **arbitrarily structured nested containers** of arrays or tensors for\nenvironment observations and actions. The actor, however, should **expose**\ncertain API (described below).\n\n\n```python\nfrom rlplay.engine import core\n\n# help(core.collect)\n```\n\nIt's role is to serve as a *middle-man* between the **actor-environment** pair\nand the **training loop**: to track the trajectory of the actor in the environment,\nand properly record it into the data buffer.\n\nFor example, it is not responsible for seeding or randomization of environments\n(i'm looking at you, `AtariEnv`), and datatype casting (except for rewards,\nwhich are cast to `fp32` automatically). In theory, there is **no need** for\nspecial data preprocessing, except for, perhaps, casting data to proper dtypes,\nlike from `numpy.float64` observations to `float32` in `CartPole`.\n\n#### Semantics\n\nThe collector just carefully records the trajectory by alternating between\nthe **REACT** and **STEP+EMIT** phases in the following fashion:\n\n$$\n \\cdots\n \\longrightarrow t\n \\overset{\\mathrm{REACT}}{\\longrightarrow} t + \\tfrac12\n \\overset{\\mathrm{STEP+EMIT}}{\\longrightarrow} t + 1\n \\longrightarrow \\cdots\n \\,, $$\n\nwhere the half-times $t + \\tfrac12$ are commonly referred to as the `afterstates`:\nthe actor has chosen an action in response to the current observation, yet has\nnot interacted with the environment.\n\nSo the `time` advances in halves, and the proper names for the half times\nin the diagram above are the `state`, the `afterstate` and the `next state`,\nrespectively.\n\nThe collected `fragment` data has the following structure:\n* `.state` $z_t$ **the current \"extended\" observation**\n * `.stepno` $n_t$ the step counter\n * `.obs` $x_t$ **the current observation** emitted by transitioning to $s_t$\n * `.act` $a_{t-1}$ **the last action** which caused $s_{t-1} \\longrightarrow s_t$ in the env\n * `.rew` $r_t$ **the previous reward** received by getting to $s_t$\n * `.fin` $d_t$ **the termination flag** indicating if $s_t$ is terminal in the env\n\n* `.actor` $A_t$ auxiliary data from the actor due to **REACT**\n\n* `.env` $E_{t+1}$ auxiliary data from the environment due to **STEP+EMIT**\n\n* `.hx` $h_0$ the starting recurrent state of the actor\n\nHere $s_t$ denotes **the unobserved true full state** of the environment.\n\nThe actor $\\theta$ interacts with the environment and generates the following\n**tracked** data during the rollout,\nunobserved/non-tracked data **in red**\nand $t = 0..T-1$:\n\n* ${\\color{orange}{h_0}}$, the starting recurrent state, is recorded in $\\,.\\!\\mathtt{hx}$\n\n* **REACT**: the actor performs the following update ($t \\to t + \\frac12$)\n\n$$ \n \\bigl(\n \\underbrace{\n .\\!\\mathtt{state}[\\mathtt{t}]\n }_{{\\color{orange}{z_t}}},\\,\n {\\color{red}{h_t}}\n \\bigr)\n \\overset{\\text{Actor}_{\\theta_{\\text{old}}}}{\\longrightarrow}\n \\bigl(\n \\underbrace{\n .\\!\\mathtt{state}.\\!\\mathtt{act}[\\mathtt{t+1}]\n }_{a_t \\leadsto {\\color{orange}{z_{t+1}}}},\\,\n \\underbrace{\n .\\!\\mathtt{actor}[\\mathtt{t}]\n }_{{\\color{orange}{A_t}}},\\,\n {\\color{red}{h_{t+1}}}\n \\bigr)\n \\,, $$\n\n* **STEP+EMIT**: the environment updates it's unobserved state and emits\nthe observed data ($t + \\frac12 \\to t+1_-$)\n\n$$ \n \\bigl(\n {\\color{red}{s_t}},\\,\n \\underbrace{\n .\\!\\mathtt{state}.\\!\\mathtt{act}[\\mathtt{t+1}]\n }_{a_t \\leadsto {\\color{orange}{z_{t+1}}}}\n \\bigr)\n \\overset{\\text{Env}}{\\longrightarrow}\n \\bigl(\n {\\color{red}{s_{t+1}}},\\,\n \\underbrace{\n .\\!\\mathtt{state}.\\!\\mathtt{obs}[\\mathtt{t+1}]\n }_{x_{t+1} \\leadsto {\\color{orange}{z_{t+1}}}},\\,\n \\underbrace{\n .\\!\\mathtt{state}.\\!\\mathtt{rew}[\\mathtt{t+1}]\n }_{r_{t+1} \\leadsto {\\color{orange}{z_{t+1}}}},\\,\n \\underbrace{\n .\\!\\mathtt{state}.\\!\\mathtt{fin}[\\mathtt{t+1}]\n }_{d_{t+1} \\leadsto {\\color{orange}{z_{t+1}}}},\\,\n \\underbrace{\n .\\!\\mathtt{env}[\\mathtt{t}]\n }_{{\\color{orange}{E_{t+1}}}}\n \\bigr)\n \\,, $$\n\n* collect loop ($t + 1_- \\to t+1$)\n\n$$ \n \\bigl(\n {\\color{orange}{n_t}},\\,\n {\\color{orange}{d_{t+1}}}\n \\bigr)\n \\longrightarrow\n \\underbrace{\n .\\!\\mathtt{state}.\\!\\mathtt{stepno}[\\mathtt{t+1}]\n }_{n_{t+1} \\leadsto {\\color{orange}{z_{t+1}}}}\n \\,. $$\n\nHere $r_t$ is a scalar reward, $d_t = \\top$ if $s_t$ is terminal, or $\\bot$\notherwise, $n_{t+1} = 0$ if $d_t = \\top$, else $1 + n_t$, and $a \\leadsto b$\nmeans $a$ being recored into $b$.\n\nIn general, we may treat $z_t$, the extended observation, as an ordinary\nobservation, by **suitably modifying** the environment: we can make it\nrecall the most recent action $a_{t-1}$ and compute the termination indicator\n$d_t$ of the current state, and let it keep track of the interaction counter\n$n_t$, and, finally, we can configure it to supply the most recent reward\n$r_t$ as part of the emitted observation.\n\nHence we essentially consider the following POMDP setup:\n\\begin{align}\n a_t, h_{t+1}, A_t\n &\\longleftarrow \\operatorname{Actor}(z_t, h_t; \\theta)\n \\,, \\\\\n z_{t+1}, r_{t+1}, E_{t+1}, s_{t+1}\n &\\longleftarrow \\operatorname{Env}(s_t, a_t)\n \\,, \\\\\n\\end{align}\n\nSpecifically, let $\n(z_t)_{t=0}^T\n = (n_t, x_t, a_{t-1}, r_t, d_t)_{t=0}^T\n$ be the trajectory fragment in `.state`, and $h_0$, `.hx`, be the starting\n(not necessarily the initial) recurrent state of the actor at the begining\nof the rollout.\n\n#### Requirements\n\n* all nested containers **must be** built from pure python `dicts`, `lists`, `tuples` or `namedtuples`\n\n* the environment communicates either in **numpy arrays** or in python **scalars**, but not in data types that are incompatible with pytorch (such as `str` or `bytes`)\n\n```python\n# example\nobs = {\n 'camera': {\n 'rear': numpy.zeros(3, 320, 240),\n 'front': numpy.zeros(3, 320, 240),\n },\n 'proximity': (+0.1, +0.2, -0.1, +0.0,),\n 'other': {\n 'fuel_tank': 78.5,\n 'passenger': False,\n },\n}\n```\n\n* the actor communicates in torch tensors **only**\n\n* the environment produces **float scalar** rewards (other data may be communicated through auxiliary environment info-dicts)\n\n### Container support with `.plyr`\n\nOne of the core tools used in `rlplay` is a high performing procedure that traverses\ncontainers of `list`, `dict` and `tuple` and calls the specified function with the \nnon-container objects found the containers as arguments (like `map`, but not an iterator\nfor arbitrarily and applicable to structured objects).\n\nSee [plyr](https://pypi.org/project/python-plyr/), its `README.md` and\n`plyr.apply` for docs.\n\nThe `apply` procedure has slightly faster specialized version `suply` and `tuply`,\nwhich do not waste time on validating the structure of the containers. They differ\nin the manner in which they call the specified function: the first passes positional\narguments, while the second passes all arguments in one tuple (think of `map` and\n`starmap` from `functools`)\n\n\n```python\n# appliers of functions to nested objects\nfrom plyr import apply, suply, tuply\n\n# `setitem` function with argument order, specialized for `apply`\nfrom plyr import xgetitem, xsetitem\n\n# help(apply)\n```\n\nHow to use `suply` to reset the recurrent state `hx` returned by `torch.nn.LSTM`:\n\n```python\n# the mask of inputs just after env resets\nfin = torch.randint(2, size=(10, 4), dtype=bool)\n\n# the tensors in `hx` must have the same 2nd dim as `fin`\nhx = torch.randn(2, 1, 4, 32, requires_grad=False).unbind()\nh0 = torch.zeros(2, 1, 4, 32, requires_grad=True).unbind()\n# XXX h0 and hx are tuples of tensors (but we're just as good with dicts)\n\n# get the masks at step 2, and make it broadcastable with 3d hx\nm = ~fin[2].unsqueeze(-1) # reset tensors at fin==False\n\n# multiply by zero the current `hx` (diff-able reset and grad stop)\nsuply(\n m.mul, # `.mul` method of the mask upcasts from bool to float if necessary\n hx, # arg `other` of `.mul`\n)\n\n# replace the reset batch elments by a diff-able init value\nsuply(\n torch.add, # .add(input, other, *, alpha=1.)\n suply(m.mul, hx), # arg `input` of `.add`\n suply(r.mul, h0), # arg `other` of `.add`\n # alpha=1. # pass other `alpha` if we want\n)\n\n# XXX `torch.where` does not have an `easily` callable interface\nsuply(\n lambda a, b: torch.where(m, a, b), # or `a.where(m, b)`\n hx, h0,\n)\n```\n\nFor example, this is used to manually run the recurrent network loop:\n```python\nfrom torch.nn.utils.rnn import pack_padded_sequence\nfrom torch.nn.utils.rnn import pad_packed_sequence\n\n\nif use_cudnn and sticky:\n # sequence padding (MUST have sampling with `sticky=True`)\n n_steps, n_env, *_ = fin.shape\n if n_steps > 1:\n # we assume sticky=True\n lengths = 1 + (~fin[1:]).sum(0).cpu() # first observation's fin should be ignored\n inputs = pack_padded_sequence(input, lengths, enforce_sorted=False)\n\n output, hx = self.core(inputs, hx)\n if n_steps > 1:\n output, lens = pad_packed_sequence(\n output, batch_first=False, total_length=n_steps)\n\nelse:\n # input is T x B x F, hx is either None, or a proper recurrent state\n outputs = []\n for x, m in zip(input.unsqueeze(1), ~fin.unsqueeze(-1)):\n # `m` indicates if no reset took place, otherwise\n # multiply by zero to stop the grads\n if hx is not None:\n hx = suply(m.mul, hx)\n\n output, hx = self.core(x, hx)\n outputs.append(output)\n\n output = torch.cat(outputs, dim=0)\n```\n\n
\n\n### Creating the actors\n\nRollout collection relies on the following API of the actor:\n* `.reset(j, hx)` reset the recurrent state of the j-th environment in the batch (if applicable)\n * `hx` contains tensors with shape `(n_lstm_layers * n_dir) x batch x hidden`, or is an empty tuple\n * the returned `hx` is the updated recurrent state\n\n\n* `.step(stepno, obs, act, rew, fin, /, *, hx, virtual)` get the next action $a_t$, the recurrent state $h_{t+1}$, and\nthe **extra info** in response to $n_t$, $x_t$, $a_{t-1}$, $r_t$, $d_t$, and $h_t$ respectively.\n * extra info `dict` **might** include `value` key with a `T x B` tensor of state value estimates $\n v_t(z_t) \\approx G_t = \\mathbb{E} \\sum_{j\\geq t} \\gamma^{j-t} r_{j+1}\n $.\n * MUST allocate new `hx` if the recurrent state is updated\n * MUST NOT change the inputs in-place\n\n\n\n```python\nfrom rlplay.engine import BaseActorModule\n\nhelp(BaseActorModule.reset)\n```\n\n\n```python\nhelp(BaseActorModule.step)\n```\n\n`BaseActorModule` is essentially a thin sub-class of `torch.nn.Module`, that implements\nthe API through `.forward(obs, act, rew, fin, *, hx, stepno)`, which should return three things:\n\n1. `actions` prescribed actions in the environment, with data of shape `n_steps x batch x ...`\n * can be a nested container of dicts, lists, and tuples\n\n\n2. `hx` data with shape `n_steps x batch x ...`\n * can be a nested container of dicts, lists, and tuples\n * **if an actor is not recurrent**, then must return an empty container, e.g. a tuple `()`\n\n\n3. `info` object, which might be a tensor or a nested object containing data in tensors\n`n_steps x batch x ...`. For example, one may communicate the following data:\n * `value` -- the state value estimates $v(z_t)$\n * `logits` -- the policy logits $\\log \\pi(\\cdot \\mid z_t)$\n * `q` -- $Q(z_t, \\cdot)$ values\n\nHere is an example actor, that wraps a simple MLP policy.\n\n\n```python\nfrom rlplay.utils.common import multinomial\n\nclass PolicyWrapper(BaseActorModule):\n \"\"\"A non-recurrent policy for a flat `Discrete(n)` action space.\"\"\"\n\n def __init__(self, policy):\n super().__init__()\n self.policy = policy\n\n # for updating the exploration epsilon in the clones\n # self.register_buffer('epsilon', torch.tensor(epsilon))\n\n def forward(self, obs, act=None, rew=None, fin=None,\n *, hx=None, stepno=None, virtual=False):\n # Everything is [T x B x ...]\n logits = self.policy(locals())\n\n actions = multinomial(logits.detach().exp())\n\n return actions, (), dict(logits=logits)\n```\n\n
\n\n### Manual rollout collection\n\nWe shall need the following procedures from the core of the engine:\n\n\n```python\nfrom rlplay.engine.core import prepare, startup, collect\n```\n\nManual collection requires an `actor` and a batch of environment instances `envs`.\n\nPrepare the run-time context for the specified `actor` and the environments\n```python\n# settings\nsticky = False # whether to stop interacting if an env resets mid-fragment\ndevice = None # specifies the device to put the actor's inputs and data onto\npinned = False # whether to keep the running context in non-resizable pinned\n # (non-paged) memory for faster host-device transfers\n\n# initialize a buffer for one rollout fragment\nbuffer = prepare(envs[0], actor, n_steps, len(envs),\n pinned=False, device=device)\n\n# the running context tor the actor and the envs (optionally pinned)\nctx, fragment = startup(envs, actor, buffer, pinned=pinned)\n\nwhile not done:\n # collect the fragment\n collect(envs, actor, fragment, ctx, sticky=sticky, device=device)\n\n # fragment.pyt -- torch tensors, fragment.npy -- numpy arrays (aliased on-host)\n do_stuff(actor, fragment.pyt)\n```\n\n
\n\n### Rollout collection (same-process)\n\nCollect rollouts within the current process\n\n\n```python\nfrom rlplay.engine.rollout import same\n```\n\nThe parameters have the following meaning\n```python\nit = same.rollout(\n envs, # the batch of environment instances\n actor, # the actor which interacts with the batch\n n_steps=51, # the length of the rollout fragment\n sticky=False, # whether to stop interacting if an env resets mid-fragment\n device=None, # specifies the device to put the actor's inputs onto\n)\n```\n\n`rollout()` returns an iterator, which has, roughly, the same logic,\nas the manual collection above.\n\nInside the infinite loop it copies `fragment.pyt` onto `device`, before\nyielding it to the user. It also does not spawn its own batch of environments,\nunlike parallel variants.\n\nThe user has to manually limit the number of iterations using, for example,\n\n```python\nit = same.rollout(...)\n\nfor b, batch in zip(range(100), it):\n # train on batch\n pass\n\nit.close()\n```\n\n
\n\n### Rollout collection (single-process)\n\nSingle-actor rollout sampler running in a parallel process (double-buffered).\n\n\n```python\nfrom rlplay.engine.rollout import single\n```\n\nUnder the hood the functions creates **two** rollout fragment buffers, maintains\na reference to the specified `actor`, makes a shared copy of it (on the host), and\nthen spawns one worker process.\n\nThe worker, in turn, makes its own local copy of the actor on the specified device,\ninitializes the environments and the running context. During collection it alternates\nbetween the buffers, into which it records the rollout fragments it collects. Except\nfor double buffering, the logic is identical to `rollout`.\n\nThe local copies of the actor are **automatically updated** from the maintained reference.\n\n```python\nit = single.rollout(\n factory, # the environment factory\n actor, # the actor reference, used to update the local actors\n\n n_steps, # the duration of a rollout fragment\n n_envs, # the number of independent environments in the batch\n\n sticky=False, # do we freeze terminated environments until the end of the rollout?\n # required if we wish to leverage cudnn's fast RNN implementations,\n # instead of manually stepping through the RNN core.\n\n clone=True, # should the worker use a local clone of the reference actor\n\n close=True, # should we `.close()` the environments when cleaning up?\n # some envs are very particular about this, e.g. nle\n\n start_method='fork', # `fork` in notebooks, `spawn` in linux/macos and if we interchange\n # cuda tensors between processes (we DO NOT do that: we exchange indices\n # to host-shapred tensors)\n\n device=None, # the device on which to collect rollouts (the local actor is moved\n # onto this device)\n)\n\n# ...\n\nit.close()\n```\n\n
\n\n### Rollout collection (multi-process)\n\nA more load-balanced multi-actor milti-process sampler\n\n\n```python\nfrom rlplay.engine.rollout import multi\n```\n\nThis version of the rollout collector allocates several buffers and spawns\nmany parallel workers. Each worker creates it own local copy of the actor,\ninstantiates `n_envs` local environments and allocates a running context for\nall of them. The rollout collection in each worker is **hardcoded to run on\nthe host device**.\n\n```python\nit = multi.rollout(\n factory, # the environment factory\n actor, # the actor reference, used to update the local actors\n\n n_steps, # the duration of each rollout fragment\n\n n_actors, # the number of parallel actors\n n_per_actor, # the number of independent environments run in each actor\n n_buffers, # the size of the pool of buffers, into which rollout\n # fragments are collected. Should not be less than `n_actors`.\n n_per_batch, # the number of fragments collated into a batch\n\n sticky=False, # do we freeze terminated environments until the end of the rollout?\n # required if we wish to leverage cudnn's fast RNN implementations,\n # instead of manually stepping through the RNN core.\n\n pinned=False,\n\n clone=True, # should the parallel actors use a local clone of the reference actor\n\n close=True, # should we `.close()` the environments when cleaning up?\n # some envs are very particular about this, e.g. nle\n\n device=None, # the device onto which to move the rollout batches\n\n start_method='fork', # `fork` in notebooks, `spawn` in linux/macos and if we interchange\n # cuda tensors between processes (we DO NOT do that: we exchange indices\n # to host-shared tensors)\n)\n\n# ...\n\nit.close()\n```\n\n
\n\n### Evaluation (same-process)\n\nIn order to evaluate an actor in a batch of environments, one can use `evaluate`.\n\n\n```python\nfrom rlplay.engine import core\n\n# help(core.evaluate)\n```\n\nThe function *does not* collect the rollout data, except for the rewards.\nBelow is the intended use case.\n* **NB** this is run in the same process, hence blocks until completion, which\nmight take considerable time (esp. if `n_steps` is unbounded)\n\n\n```python\n# same process\ndef same_evaluate(\n factory, actor, n_envs=4,\n *, n_steps=None, close=True, render=False, device=None\n):\n # spawn a batch of environments\n envs = [factory() for _ in range(n_envs)]\n\n try:\n while True:\n rewards, _ = core.evaluate(\n envs, actor, n_steps=n_steps,\n render=render, device=device)\n\n # get the accumulated rewards (gamma=1)\n yield sum(rewards)\n\n finally:\n if close:\n for e in envs:\n e.close()\n```\n\n
\n\n### Evaluation (parallel process)\n\nLike rollout collection, evaluation can (and probably should) be performed in\na parallel process, so that it does not burden the main thread with computations\nnot related to training.\n\n\n```python\nfrom rlplay.engine.rollout.evaluate import evaluate\n```\n\n
\n\n## CartPole with REINFORCE\n\n### the CartPole Environment\n\n\n```python\nimport gym\n\n# hotfix for gym's unresponsive viz (spawns gl threads!)\nimport rlplay.utils.integration.gym\n```\n\nThe environment factory\n\n\n```python\nclass FP32Observation(gym.ObservationWrapper):\n def observation(self, observation):\n return observation.astype(numpy.float32)\n# obs[0] = 0. # mask the position info\n# return obs # observation.astype(numpy.float32)\n\ndef factory(seed=None):\n return FP32Observation(gym.make(\"CartPole-v0\").unwrapped)\n```\n\n
\n\n### the algorithms\n\nService functions for the algorithms\n\n\n```python\nfrom plyr import apply, suply, xgetitem\n\n\ndef timeshift(state, *, shift=1):\n \"\"\"Get current and shfited slices of nested objects.\"\"\"\n # use xgetitem to lett None through\n # XXX `curr[t]` = (x_t, a_{t-1}, r_t, d_t), t=0..T-H\n curr = suply(xgetitem, state, index=slice(None, -shift))\n\n # XXX `next[t]` = (x_{t+H}, a_{t+H-1}, r_{t+H}, d_{t+H}), t=0..T-H\n next = suply(xgetitem, state, index=slice(shift, None))\n\n return curr, next\n```\n\nThe reinforce PG algo\n\n\n```python\nfrom rlplay.algo.returns import pyt_returns\n\n# @torch.enable_grad()\ndef reinforce(fragment, module, *, gamma=0.99, C_entropy=1e-2):\n r\"\"\"The REINFORCE algorithm.\n\n The basic policy-gradient algorithm with a baseline $b_t$:\n $$\n \\nabla_\\theta J(s_t)\n = \\mathbb{E}_{a \\sim \\beta(a\\mid s_t)}\n \\frac{\\pi(a\\mid s_t)}{\\beta(a\\mid s_t)}\n \\bigl( r_{t+1} + \\gamma G_{t+1} - b_t \\bigr)\n \\nabla_\\theta \\log \\pi(a\\mid s_t)\n \\,. $$\n \n Details\n -------\n It turns out that applying on-policy algo in off-policy setting\n and expecting it to produce acceptable results was a sure sign of\n stupidity on part of the author of this notebook. Oh, well...\n \"\"\"\n \n # get `.state[t]` and `.state[t+1]`\n state, state_next = timeshift(fragment.state)\n\n # REACT: (state[t], h_t) \\to (\\hat{a}_t, h_{t+1}, \\hat{A}_t)\n _, _, info = module(\n state.obs, state.act, state.rew, state.fin,\n hx=fragment.hx, stepno=state.stepno)\n\n # Get the returns-to-go -- the present value of the future rewards\n # following `state[t]`: G_t = r_{t+1} + \\gamma G_{t+1}\n # XXX bootstrap with the perpetual last reward?\n # bootstrap = state_next.rew[-1] # torch.tensor(0.)\n # bootstrap = state_next.rew.mean(dim=0) # .div_(1 - gamma)\n ret = pyt_returns(state_next.rew, state_next.fin,\n gamma=gamma, bootstrap=torch.tensor(0.))\n\n # `.state_next[t].act` is the action taken in response to `.state[t]`\n # We assume it is unstructured and categorical.\n act = state_next.act.unsqueeze(-1)\n\n # the policy surrogate score (max)\n # \\frac1T \\sum_t (G_t - b_t) \\log \\pi(a_t \\mid s_t)\n # ret.sub_(ret.mean(dim=0)) # .div_(ret.std(dim=0))\n log_pi = info['logits'] # the current policy\n log_pi_a = log_pi.gather(-1, act).squeeze(-1)\n reinfscore = log_pi_a.mul(ret).mean() # the log-likelihood\n\n # the policy neg-entropy score (min)\n # - H(\\pi(\\cdot \\mid s)) = - (-1) \\sum_a \\pi(a\\mid s) \\log \\pi(a\\mid s)\n f_min = torch.finfo(log_pi.dtype).min\n negentropy = log_pi.exp().mul(log_pi.clamp(min=f_min)).sum(dim=-1).mean()\n\n # maximize the entropy and the reinforce score\n # \\ell := - \\frac1T \\sum_t G_t \\log \\pi(a_t \\mid s_t)\n # - C \\mathbb{H} \\pi(\\cdot \\mid s_t)\n loss = C_entropy * negentropy - reinfscore\n return loss.mean(), dict(\n entropy=-float(negentropy),\n policy_score=float(reinfscore),\n )\n```\n\n
\n\n### the Actor\n\nA procedure and a layer, which converts the input integer data into its\nlittle-endian binary representation as float $\\{0, 1\\}^m$ vectors.\n\n\n```python\ndef onehotbits(input, n_bits=63, dtype=torch.float):\n \"\"\"Encode integers to fixed-width binary floating point vectors\"\"\"\n assert not input.dtype.is_floating_point\n assert 0 < n_bits < 64 # torch.int64 is signed, so 64-1 bits max\n\n # n_bits = {torch.int64: 63, torch.int32: 31, torch.int16: 15, torch.int8 : 7}\n\n # get mask of set bits\n pow2 = torch.tensor([1 << j for j in range(n_bits)]).to(input.device)\n x = input.unsqueeze(-1).bitwise_and(pow2).to(bool)\n\n # upcast bool to float to get one-hot\n return x.to(dtype)\n\n\nclass OneHotBits(torch.nn.Module):\n def __init__(self, n_bits=63, dtype=torch.float):\n assert 1 <= n_bits < 64\n super().__init__()\n self.n_bits, self.dtype = n_bits, dtype\n\n def forward(self, input):\n return onehotbits(input, n_bits=self.n_bits, dtype=self.dtype)\n```\n\nA special module dictionary, which applies itself to the input dict of tensors\n\n\n```python\nfrom typing import Optional, Mapping\nfrom torch.nn import Module, ModuleDict as BaseModuleDict\n\n\nclass ModuleDict(BaseModuleDict):\n \"\"\"The ModuleDict, that applies itself to the input dicts.\"\"\"\n def __init__(\n self,\n modules: Optional[Mapping[str, Module]] = None,\n dim: Optional[int]=-1\n ) -> None:\n super().__init__(modules)\n self.dim = dim\n\n def forward(self, input):\n # enforce concatenation in the order of the declaration in __init__\n return torch.cat([\n m(input[k]) for k, m in self.items()\n ], dim=self.dim)\n```\n\nA policy which uses many inputs.\n\n\n```python\nfrom torch.nn import Sequential\nfrom torch.nn import Embedding, Linear, Identity\nfrom torch.nn import ReLU, LogSoftmax\n\ndef policy():\n return Sequential(\n ModuleDict(dict(\n# stepno=Sequential(\n# OneHotBits(), Linear(63, 4, bias=False)\n# ),\n obs=Identity(),\n act=Embedding(2, 2),\n )),\n Linear(0 + 4 + 2, 32),\n ReLU(),\n Linear(32, 2),\n LogSoftmax(dim=-1),\n )\n```\n\nThe discount factor\n\n\n```python\ngamma = 0.99\nC_entropy = 0.1\n```\n\nInitialize the learner and the factories\n\n\n```python\nfrom functools import partial\n\nfactory_eval = partial(factory)\n\nlearner, sticky = PolicyWrapper(policy()), False\n\nlearner.train()\ndevice_ = torch.device('cpu') # torch.device('cuda:0')\nlearner.to(device=device_)\n\n# prepare the optimizer for the learner\noptim = torch.optim.Adam(learner.parameters(), lr=1e-3)\n```\n\nPick one collector\n* the `fork` method is friendlier towards notebooks, but some environments, like the NetHack environment, do not like it\n* unlike `fork`, the `spawn` method is `torch.cuda` compatible in that it allows moving on-device tensors between processes. It is not notebook friendly, however :(\n * essentially it is better to prototype in notebook with `same.rollout`, then write a submodule non-interactive script with `multi.rollout`\n\n`REINFORCE` and `A2C` methods do not work ~~well~~ in off-policy setting, so we use\nthe same-process collector, which guarantees on-policy trajectory data.\n\n\n```python\nT, B = 120, 8\n```\n\nInitialize the sampler\n\n\n```python\n# generator of rollout batches\nbatchit = same.rollout(\n [factory() for _ in range(B)],\n learner,\n n_steps=T,\n sticky=sticky,\n device=device_,\n)\n```\nfrom rlplay.engine.rollout import episodic\n\n# generator of rollout batches\nbatchit = episodic.rollout(\n [factory() for _ in range(B)],\n learner,\n batch_size=8,\n device=device_,\n)# generator of rollout batches\nbatchit = single.rollout(\n factory,\n learner,\n n_steps=T,\n n_envs=B,\n sticky=sticky, # so that we can leverage cudnn's fast RNN implementations\n clone=False,\n close=False,\n device=device_,\n start_method='fork', # fork in notebook for macos, spawn in linux\n)# generator of rollout batches\nbatchit = multi.rollout(\n factory,\n learner,\n n_steps=T,\n n_actors=16,\n n_per_actor=B,\n n_buffers=24,\n n_per_batch=2,\n sticky=sticky, # so that we can leverage cudnn's fast RNN implementations\n pinned=False,\n clone=True,\n close=False,\n device=device_,\n start_method='fork', # fork in notebook for macos, spawn in linux\n)\nGenerator of evaluation rewards:\n* we're perfectly OK with evaluating in a parallel process\n\n\n```python\n# test_it = test(factory_eval, learner, n_envs=4, n_steps=500, device=device_)\ntest_it = evaluate(factory_eval, learner, n_envs=4, n_steps=500,\n clone=False, device=device_, start_method='fork')\n```\n\nImplement your favorite training method\ntorch.autograd.set_detect_anomaly(True)\n\n```python\nimport tqdm\n# from math import log, exp\nfrom torch.nn.utils import clip_grad_norm_\n\n# pytoch loves to hog all threads on some linux systems \ntorch.set_num_threads(1)\n\n# the training loop\nlosses, rewards, samples = [], [], []\n# decay = -log(2) / 25 # exploration epsilon half-life\nfor epoch in tqdm.tqdm(range(100)):\n for j, batch in zip(range(40), batchit):\n loss, info = reinforce(batch, learner, gamma=gamma,\n C_entropy=C_entropy)\n\n optim.zero_grad()\n loss.backward()\n grad_norm = clip_grad_norm_(learner.parameters(), max_norm=1.0)\n optim.step()\n \n losses.append(dict(\n loss=float(loss),\n grad=float(grad_norm),\n **info\n ))\n\n # This is an example of how to save a batch: we need to clone,\n # because the fragment buffer is static, and will be overwritten!\n samples.append(suply(torch.clone, batch))\n\n # fetch the evaluation results (lag by one inner loop!)\n rewards.append(next(test_it))\n\n # learner.epsilon.mul_(exp(decay)).clip_(0.1, 1.0)\n```\n\n\n```python\n# stack all samples\nsamples = tuply(torch.stack, *samples)\n\n# close the generators\nbatchit.close()\ntest_it.close()\n```\nimport pdb; pdb.pm()\n
\n\n\n```python\ndata = {k: numpy.array(v) for k, v in collate(losses).items()}\n```\n\n\n```python\nif 'loss' in data:\n plt.plot(data['loss'])\n```\n\n\n```python\nif 'entropy' in data:\n plt.plot(data['entropy'])\n```\n\n\n```python\nif 'policy_score' in data:\n plt.plot(data['policy_score'])\n```\n\n\n```python\nplt.semilogy(data['grad'])\n```\n\n\n```python\nrewards = numpy.stack(rewards, axis=0)\n```\n\n\n```python\nrewards\n```\n\n\n```python\nm, s = numpy.median(rewards, axis=-1), rewards.std(axis=-1)\n```\n\n\n```python\nfi, ax = plt.subplots(1, 1, figsize=(4, 2), dpi=300)\n\nax.plot(numpy.mean(rewards, axis=-1))\nax.plot(numpy.median(rewards, axis=-1))\nax.plot(numpy.min(rewards, axis=-1))\nax.plot(numpy.std(rewards, axis=-1))\n# ax.plot(m+s * 1.96)\n# ax.plot(m-s * 1.96)\n\nplt.show()\n```\n\n
\n\nThe ultimate evaluation run\n\n\n```python\nwith factory_eval() as env:\n learner.eval()\n eval_rewards, info = core.evaluate([\n env\n ], learner, render=True, n_steps=1e4, device=device_)\n\nprint(sum(eval_rewards))\n```\nimport pdb; pdb.pm()\n\n```python\nplt.hist(numpy.exp(info['logits']).argmax(-1))\n```\n\n
\n\nLet's analyze the performance\n\n\n```python\nimport math\nfrom scipy.special import softmax, expit, entr\n\n*head, n_actions = info['logits'].shape\nproba = softmax(info['logits'], axis=-1)\n\nfig, ax = plt.subplots(1, 1, figsize=(4, 2), dpi=300)\nax.plot(entr(proba).sum(-1)[:, 0])\nax.axhline(math.log(n_actions), c='k', alpha=0.5, lw=1);\n```\n\n\n```python\nfig, ax = plt.subplots(1, 1, figsize=(4, 2), dpi=300)\nax.hist(info['logits'][..., 1] - info['logits'][..., 0], bins=51); # log-ratio\n```\n\n
\n\n\n```python\nassert False\n```\nimport pdb; pdb.pm()\n
\n\n\n```python\n# stepno = batch.state.stepno\nstepno = torch.arange(8192)\n```\n\n\n```python\nwith torch.no_grad():\n out = learner.policy[0]['stepno'](stepno)\n```\n\n\n```python\nfig, axes = plt.subplots(2, 2, figsize=(8, 8), dpi=200,\n sharex=True, sharey=True)\n\nfor j, ax in zip(range(out.shape[1]), axes.flat):\n ax.plot(out[:, j], lw=1)\n\nfig.tight_layout(pad=0, h_pad=0, w_pad=0)\n```\n\n\n```python\nwith torch.no_grad():\n plt.imshow(abs(learner.policy[4].weight) @ abs(learner.policy[1].weight))\n```\n\n\n```python\nwith torch.no_grad():\n plt.imshow(abs(learner.policy[0]['stepno'][-1].weight)[:, :16].T)\n```\n\n\n```python\nassert False\n```\n\n
\n", "meta": {"hexsha": "defaffec50296a71477ca4717dea0db872cbdbb4", "size": 54611, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "stage/example.ipynb", "max_stars_repo_name": "ivannz/rlplay", "max_stars_repo_head_hexsha": "eeca796e6501d6077c4fbfde4cdb41567768a492", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-04-11T13:38:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-23T09:37:05.000Z", "max_issues_repo_path": "stage/example.ipynb", "max_issues_repo_name": "ivannz/rlplay", "max_issues_repo_head_hexsha": "eeca796e6501d6077c4fbfde4cdb41567768a492", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-12-23T09:22:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-23T11:39:22.000Z", "max_forks_repo_path": "stage/example.ipynb", "max_forks_repo_name": "ivannz/rlplay", "max_forks_repo_head_hexsha": "eeca796e6501d6077c4fbfde4cdb41567768a492", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4432291667, "max_line_length": 176, "alphanum_fraction": 0.5190712494, "converted": true, "num_tokens": 8635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.2132065903854601}} {"text": "[Sascha Spors](https://orcid.org/0000-0001-7225-9992),\nProfessorship Signal Theory and Digital Signal Processing,\n[Institute of Communications Engineering (INT)](https://www.int.uni-rostock.de/),\nFaculty of Computer Science and Electrical Engineering (IEF),\n[University of Rostock, Germany](https://www.uni-rostock.de/en/)\n\n# Tutorial Signals and Systems (Signal- und Systemtheorie)\n\nSummer Semester 2021 (Bachelor Course #24015)\n\n- lecture: https://github.com/spatialaudio/signals-and-systems-lecture\n- tutorial: https://github.com/spatialaudio/signals-and-systems-exercises\n\nWIP...\nThe project is currently under heavy development while adding new material for the summer semester 2021\n\nFeel free to contact lecturer [frank.schultz@uni-rostock.de](https://orcid.org/0000-0002-3010-0294)\n\n## Region of Convergence for Right-Sided Signals\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\n```\n\n\n```python\ndef plotpzmap_neg(s0):\n fig,(ax1, ax2) = plt.subplots(1, 2)\n fig.set_size_inches(6, 3)\n ax1.plot((-2, 2),(0, 0), lw=1, color='k')\n ax1.plot((0, 0),(-2, 2), lw=1, color='k')\n ax1.plot(-s0, 0, 'x', color='C0', markersize=10)\n p = matplotlib.patches.Rectangle((-s0,-2), 4, 4, color='gray', alpha=0.15)\n ax1.add_patch(p)\n ax1.axis('Square')\n ax1.set_xlim(-2,2)\n ax1.set_ylim(-2,2)\n ax1.set_xlabel(\"$\\Re(s)$\")\n ax1.set_ylabel(\"$\\Im(s)$\")\n ax1.set_title(\"exp(\"+str(s0)+\"t) $\\epsilon$(t)\")\n ax1.text(1,-1,'ROC')\n \n t = np.arange(0,5,0.1)\n x = np.exp(-s0*t)\n ax2.plot(t,x)\n ax2.set_xlabel('t')\n ax2.set_ylabel('x(t)') \n ax2.axis('Square')\n \ndef plotpzmap_pos(s0):\n fig,(ax1, ax2) = plt.subplots(1, 2)\n fig.set_size_inches(6, 3)\n ax1.plot((-2, 2),(0, 0), lw=1, color='k')\n ax1.plot((0, 0),(-2, 2), lw=1, color='k')\n ax1.plot(s0, 0, 'x', color='C0', markersize=10)\n p = matplotlib.patches.Rectangle((s0,-2), 4, 4, color='gray', alpha=0.15)\n ax1.add_patch(p)\n ax1.axis('Square')\n ax1.set_xlim(-2,2)\n ax1.set_ylim(-2,2)\n ax1.set_xlabel(\"$\\Re(s)$\")\n ax1.set_ylabel(\"$\\Im(s)$\")\n ax1.set_title(\"exp(\"+str(s0)+\"t) $\\epsilon$(t)\")\n ax1.text(1,-1,'ROC')\n \n t = np.arange(0,5,0.1)\n x = np.exp(+s0*t)\n ax2.plot(t,x)\n ax2.set_xlabel('t')\n ax2.set_ylabel('x(t)') \n ax2.axis('Square') \n```\n\n\\begin{equation}\n\\mathcal{L}\\{\\mathrm{e}^{-s_0 t} \\epsilon(t)\\} = \\frac{1}{s+s_0}\\quad \\text{ROC}: \\Re(s) > \\Re(-s_0)\n\\end{equation}\n\n\n```python\ns0 = 1\nplotpzmap_neg(s0)\n```\n\n\\begin{equation}\n\\mathcal{L}\\{\\mathrm{e}^{+s_0 t} \\epsilon(t)\\} = \\frac{1}{s-s_0}\\quad \\text{ROC}: \\Re(s) > \\Re(+s_0)\n\\end{equation}\n\n\n```python\ns0 = -1\nplotpzmap_pos(s0)\n```\n\n## Copyright\n\nThis tutorial is provided as Open Educational Resource (OER), to be found at\nhttps://github.com/spatialaudio/signals-and-systems-exercises\naccompanying the OER lecture\nhttps://github.com/spatialaudio/signals-and-systems-lecture.\nBoth are licensed under a) the Creative Commons Attribution 4.0 International\nLicense for text and graphics and b) the MIT License for source code.\nPlease attribute material from the tutorial as *Frank Schultz,\nContinuous- and Discrete-Time Signals and Systems - A Tutorial Featuring\nComputational Examples, University of Rostock* with\n``main file, github URL, commit number and/or version tag, year``.\n", "meta": {"hexsha": "c1568c4afe6d2b0b031f5e12887c86f2ee511f84", "size": 6343, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "laplace_transform/region_of_convergence.ipynb", "max_stars_repo_name": "spatialaudio/signals-and-systems-exercises", "max_stars_repo_head_hexsha": "d1dbeb5bce74abbd211f6888186556cbe46869f2", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-05-20T10:01:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T17:48:25.000Z", "max_issues_repo_path": "laplace_transform/region_of_convergence.ipynb", "max_issues_repo_name": "spatialaudio/signals-and-systems-exercises", "max_issues_repo_head_hexsha": "d1dbeb5bce74abbd211f6888186556cbe46869f2", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2021-06-23T19:36:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-03T15:39:48.000Z", "max_forks_repo_path": "laplace_transform/region_of_convergence.ipynb", "max_forks_repo_name": "spatialaudio/signals-and-systems-exercises", "max_forks_repo_head_hexsha": "d1dbeb5bce74abbd211f6888186556cbe46869f2", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8743718593, "max_line_length": 119, "alphanum_fraction": 0.5505281413, "converted": true, "num_tokens": 1105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.21125231740709413}} {"text": "\n\n# Lambda School Data Science Module 143\n\n## Introduction to Bayesian Inference\n\n!['Detector! What would the Bayesian statistician say if I asked him whether the--' [roll] 'I AM A NEUTRINO DETECTOR, NOT A LABYRINTH GUARD. SERIOUSLY, DID YOUR BRAIN FALL OUT?' [roll] '... yes.'](https://imgs.xkcd.com/comics/frequentists_vs_bayesians.png)\n\n*[XKCD 1132](https://www.xkcd.com/1132/)*\n\n\n## Prepare - Bayes' Theorem and the Bayesian mindset\n\nBayes' theorem possesses a near-mythical quality - a bit of math that somehow magically evaluates a situation. But this mythicalness has more to do with its reputation and advanced applications than the actual core of it - deriving it is actually remarkably straightforward.\n\n### The Law of Total Probability\n\nBy definition, the total probability of all outcomes (events) if some variable (event space) $A$ is 1. That is:\n\n$$P(A) = \\sum_n P(A_n) = 1$$\n\nThe law of total probability takes this further, considering two variables ($A$ and $B$) and relating their marginal probabilities (their likelihoods considered independently, without reference to one another) and their conditional probabilities (their likelihoods considered jointly). A marginal probability is simply notated as e.g. $P(A)$, while a conditional probability is notated $P(A|B)$, which reads \"probability of $A$ *given* $B$\".\n\nThe law of total probability states:\n\n$$P(A) = \\sum_n P(A | B_n) P(B_n)$$\n\nIn words - the total probability of $A$ is equal to the sum of the conditional probability of $A$ on any given event $B_n$ times the probability of that event $B_n$, and summed over all possible events in $B$.\n\n### The Law of Conditional Probability\n\nWhat's the probability of something conditioned on something else? To determine this we have to go back to set theory and think about the intersection of sets:\n\nThe formula for actual calculation:\n\n$$P(A|B) = \\frac{P(A \\cap B)}{P(B)}$$\n\n\n\nThink of the overall rectangle as the whole probability space, $A$ as the left circle, $B$ as the right circle, and their intersection as the red area. Try to visualize the ratio being described in the above formula, and how it is different from just the $P(A)$ (not conditioned on $B$).\n\nWe can see how this relates back to the law of total probability - multiply both sides by $P(B)$ and you get $P(A|B)P(B) = P(A \\cap B)$ - replaced back into the law of total probability we get $P(A) = \\sum_n P(A \\cap B_n)$.\n\nThis may not seem like an improvement at first, but try to relate it back to the above picture - if you think of sets as physical objects, we're saying that the total probability of $A$ given $B$ is all the little pieces of it intersected with $B$, added together. The conditional probability is then just that again, but divided by the probability of $B$ itself happening in the first place.\n\n### Bayes Theorem\n\n\n\nHere is is, the seemingly magic tool:\n\n$$P(A|B) = \\frac{P(B|A)P(A)}{P(B)}$$\n\nIn words - the probability of $A$ conditioned on $B$ is the probability of $B$ conditioned on $A$, times the probability of $A$ and divided by the probability of $B$. These unconditioned probabilities are referred to as \"prior beliefs\", and the conditioned probabilities as \"updated.\"\n\nWhy is this important? Scroll back up to the XKCD example - the Bayesian statistician draws a less absurd conclusion because their prior belief in the likelihood that the sun will go nova is extremely low. So, even when updated based on evidence from a detector that is $35/36 = 0.972$ accurate, the prior belief doesn't shift enough to change their overall opinion.\n\nThere's many examples of Bayes' theorem - one less absurd example is to apply to [breathalyzer tests](https://www.bayestheorem.net/breathalyzer-example/). You may think that a breathalyzer test that is 100% accurate for true positives (detecting somebody who is drunk) is pretty good, but what if it also has 8% false positives (indicating somebody is drunk when they're not)? And furthermore, the rate of drunk driving (and thus our prior belief) is 1/1000.\n\nWhat is the likelihood somebody really is drunk if they test positive? Some may guess it's 92% - the difference between the true positives and the false positives. But we have a prior belief of the background/true rate of drunk driving. Sounds like a job for Bayes' theorem!\n\n$$\n\\begin{aligned}\nP(Drunk | Positive) &= \\frac{P(Positive | Drunk)P(Drunk)}{P(Positive)} \\\\\n&= \\frac{1 \\times 0.001}{0.08} \\\\\n&= 0.0125\n\\end{aligned}\n$$\n\nIn other words, the likelihood that somebody is drunk given they tested positive with a breathalyzer in this situation is only 1.25% - probably much lower than you'd guess. This is why, in practice, it's important to have a repeated test to confirm (the probability of two false positives in a row is $0.08 * 0.08 = 0.0064$, much lower), and Bayes' theorem has been relevant in court cases where proper consideration of evidence was important.\n\n## Derive Baye's Rule\n\n\\begin{align}\nP(A|B) &= \\frac{P(A \\cap B)}{P(B)}\\\\\n\\Rightarrow P(A|B)P(B) &= P(A \\cap B)\\\\\nP(B|A) &= \\frac{P(B \\cap A)}{P(A)}\\\\\n\\Rightarrow P(B|A)P(A) &= P(B \\cap A)\\\\\n\\Rightarrow P(A|B)P(B) &= P(B|A)P(A) \\\\\nP(A \\cap B) &= P(B \\cap A)\\\\\nP(A|B) &= \\frac{P(B|A) \\times P(A)}{P(B)}\n\\end{align}\n\n## Live Lecture - Deriving Bayes' Theorem, Calculating Bayesian Confidence\n\nNotice that $P(A|B)$ appears in the above laws - in Bayesian terms, this is the belief in $A$ updated for the evidence $B$. So all we need to do is solve for this term to derive Bayes' theorem. Let's do it together!\n\n\n```\n# Activity 2 - Use SciPy to calculate Bayesian confidence intervals\n# https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.bayes_mvs.html#scipy.stats.bayes_mvs\n\nfrom scipy import stats\nimport numpy as np\n\nnp.random.seed(seed=42)\n\ncoinflips = np.random.binomial(n=1, p=.5, size=100)\nprint(coinflips)\n```\n\n [0 1 1 1 0 0 0 1 1 1 0 1 1 0 0 0 0 1 0 0 1 0 0 0 0 1 0 1 1 0 1 0 0 1 1 1 0\n 0 1 0 0 0 0 1 0 1 0 1 1 0 1 1 1 1 1 1 0 0 0 0 0 0 1 0 0 1 0 1 0 1 1 0 0 1\n 1 1 1 0 0 0 1 1 0 0 0 0 1 1 1 0 0 1 1 1 1 0 1 0 0 0]\n\n\n\n```\ndef confidence_interval(data, confidence=.95):\n n = len(data)\n mean = sum(data)/n\n data = np.array(data)\n stderr = stats.sem(data)\n interval = stderr * stats.t.ppf((1 + confidence) / 2.0, n-1)\n return (mean , mean-interval, mean+interval)\n```\n\n\n```\nconfidence_interval(coinflips)\n```\n\n\n\n\n (0.47, 0.3704689875017368, 0.5695310124982632)\n\n\n\n\n```\nhelp(stats.bayes_mvs)\n```\n\n Help on function bayes_mvs in module scipy.stats.morestats:\n \n bayes_mvs(data, alpha=0.9)\n Bayesian confidence intervals for the mean, var, and std.\n \n Parameters\n ----------\n data : array_like\n Input data, if multi-dimensional it is flattened to 1-D by `bayes_mvs`.\n Requires 2 or more data points.\n alpha : float, optional\n Probability that the returned confidence interval contains\n the true parameter.\n \n Returns\n -------\n mean_cntr, var_cntr, std_cntr : tuple\n The three results are for the mean, variance and standard deviation,\n respectively. Each result is a tuple of the form::\n \n (center, (lower, upper))\n \n with `center` the mean of the conditional pdf of the value given the\n data, and `(lower, upper)` a confidence interval, centered on the\n median, containing the estimate to a probability ``alpha``.\n \n See Also\n --------\n mvsdist\n \n Notes\n -----\n Each tuple of mean, variance, and standard deviation estimates represent\n the (center, (lower, upper)) with center the mean of the conditional pdf\n of the value given the data and (lower, upper) is a confidence interval\n centered on the median, containing the estimate to a probability\n ``alpha``.\n \n Converts data to 1-D and assumes all data has the same mean and variance.\n Uses Jeffrey's prior for variance and std.\n \n Equivalent to ``tuple((x.mean(), x.interval(alpha)) for x in mvsdist(dat))``\n \n References\n ----------\n T.E. Oliphant, \"A Bayesian perspective on estimating mean, variance, and\n standard-deviation from data\", http://scholarsarchive.byu.edu/facpub/278,\n 2006.\n \n Examples\n --------\n First a basic example to demonstrate the outputs:\n \n >>> from scipy import stats\n >>> data = [6, 9, 12, 7, 8, 8, 13]\n >>> mean, var, std = stats.bayes_mvs(data)\n >>> mean\n Mean(statistic=9.0, minmax=(7.103650222612533, 10.896349777387467))\n >>> var\n Variance(statistic=10.0, minmax=(3.176724206..., 24.45910382...))\n >>> std\n Std_dev(statistic=2.9724954732045084, minmax=(1.7823367265645143, 4.945614605014631))\n \n Now we generate some normally distributed random data, and get estimates of\n mean and standard deviation with 95% confidence intervals for those\n estimates:\n \n >>> n_samples = 100000\n >>> data = stats.norm.rvs(size=n_samples)\n >>> res_mean, res_var, res_std = stats.bayes_mvs(data, alpha=0.95)\n \n >>> import matplotlib.pyplot as plt\n >>> fig = plt.figure()\n >>> ax = fig.add_subplot(111)\n >>> ax.hist(data, bins=100, density=True, label='Histogram of data')\n >>> ax.vlines(res_mean.statistic, 0, 0.5, colors='r', label='Estimated mean')\n >>> ax.axvspan(res_mean.minmax[0],res_mean.minmax[1], facecolor='r',\n ... alpha=0.2, label=r'Estimated mean (95% limits)')\n >>> ax.vlines(res_std.statistic, 0, 0.5, colors='g', label='Estimated scale')\n >>> ax.axvspan(res_std.minmax[0],res_std.minmax[1], facecolor='g', alpha=0.2,\n ... label=r'Estimated scale (95% limits)')\n \n >>> ax.legend(fontsize=10)\n >>> ax.set_xlim([-4, 4])\n >>> ax.set_ylim([0, 0.5])\n >>> plt.show()\n \n\n\n\n```\n#0.37046898750173674\n#0.3704689875017368\n\nstats.bayes_mvs(coinflips, alpha=.95)\n```\n\n\n\n\n (Mean(statistic=0.47, minmax=(0.37046898750173674, 0.5695310124982632)),\n Variance(statistic=0.25680412371134015, minmax=(0.1939698977025208, 0.3395533426586547)),\n Std_dev(statistic=0.5054540733507159, minmax=(0.44042013771229943, 0.5827120581030176)))\n\n\n\n\n```\ncoinflips_mean_dist, _, _ = stats.mvsdist(coinflips)\ncoinflips_mean_dist\n```\n\n\n\n\n \n\n\n\n\n```\nhelp(coinflips_mean_dist)\n```\n\n Help on rv_frozen in module scipy.stats._distn_infrastructure object:\n \n class rv_frozen(builtins.object)\n | # Frozen RV class\n | \n | Methods defined here:\n | \n | __init__(self, dist, *args, **kwds)\n | Initialize self. See help(type(self)) for accurate signature.\n | \n | cdf(self, x)\n | \n | entropy(self)\n | \n | expect(self, func=None, lb=None, ub=None, conditional=False, **kwds)\n | \n | interval(self, alpha)\n | \n | isf(self, q)\n | \n | logcdf(self, x)\n | \n | logpdf(self, x)\n | \n | logpmf(self, k)\n | \n | logsf(self, x)\n | \n | mean(self)\n | \n | median(self)\n | \n | moment(self, n)\n | \n | pdf(self, x)\n | \n | pmf(self, k)\n | \n | ppf(self, q)\n | \n | rvs(self, size=None, random_state=None)\n | \n | sf(self, x)\n | \n | stats(self, moments='mv')\n | \n | std(self)\n | \n | var(self)\n | \n | ----------------------------------------------------------------------\n | Data descriptors defined here:\n | \n | __dict__\n | dictionary for instance variables (if defined)\n | \n | __weakref__\n | list of weak references to the object (if defined)\n | \n | random_state\n \n\n\n\n```\ncoinflips_mean_dist.rvs(100)\n```\n\n\n\n\n array([0.47447628, 0.51541425, 0.54722018, 0.4589882 , 0.51501386,\n 0.53819192, 0.43382292, 0.53546659, 0.47026173, 0.44967562,\n 0.4621107 , 0.42691904, 0.37324325, 0.47531437, 0.46052277,\n 0.48711257, 0.52456771, 0.43332181, 0.49545882, 0.44671454,\n 0.47520117, 0.47047251, 0.41828918, 0.50159477, 0.42965501,\n 0.45273383, 0.48045849, 0.45342529, 0.48238344, 0.53966291,\n 0.48230241, 0.48073422, 0.48553525, 0.47962228, 0.41274185,\n 0.42892633, 0.5170948 , 0.42678096, 0.42249309, 0.51499109,\n 0.47059199, 0.39903942, 0.41790336, 0.46406817, 0.42232382,\n 0.42163269, 0.47848227, 0.48232842, 0.4731858 , 0.51077244,\n 0.3957508 , 0.48504646, 0.49014295, 0.53252732, 0.45495376,\n 0.47883978, 0.60393033, 0.4492549 , 0.44797902, 0.54782121,\n 0.43380002, 0.5760073 , 0.36941266, 0.44467418, 0.4939245 ,\n 0.45278835, 0.55635162, 0.48695459, 0.39080983, 0.45948606,\n 0.2941779 , 0.35950718, 0.44805696, 0.4725126 , 0.42218381,\n 0.45985418, 0.47545393, 0.44317753, 0.46267013, 0.4458753 ,\n 0.44204707, 0.51334913, 0.50914181, 0.49923748, 0.46895674,\n 0.43892798, 0.45984946, 0.44984632, 0.53560791, 0.45865723,\n 0.48646824, 0.55937503, 0.41464303, 0.50701457, 0.46934196,\n 0.37681534, 0.42748113, 0.49812825, 0.48278895, 0.4964763 ])\n\n\n\n\n```\nimport pandas as pd\npd.DataFrame(coinflips).describe()\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
0
count100.000000
mean0.470000
std0.501614
min0.000000
25%0.000000
50%0.000000
75%1.000000
max1.000000
\n
\n\n\n\n## Assignment - Code it up!\n\nMost of the above was pure math - now write Python code to reproduce the results! This is purposefully open ended - you'll have to think about how you should represent probabilities and events. You can and should look things up, and as a stretch goal - refactor your code into helpful reusable functions!\n\nSpecific goals/targets:\n\n1. Write a function `def prob_drunk_given_positive(prob_drunk_prior, prob_positive, prob_positive_drunk)` that reproduces the example from lecture, and use it to calculate and visualize a range of situations\n2. Explore `scipy.stats.bayes_mvs` - read its documentation, and experiment with it on data you've tested in other ways earlier this week\n3. Create a visualization comparing the results of a Bayesian approach to a traditional/frequentist approach\n4. In your own words, summarize the difference between Bayesian and Frequentist statistics\n\nIf you're unsure where to start, check out [this blog post of Bayes theorem with Python](https://dataconomy.com/2015/02/introduction-to-bayes-theorem-with-python/) - you could and should create something similar!\n\nStretch goals:\n\n- Apply a Bayesian technique to a problem you previously worked (in an assignment or project work) on from a frequentist (standard) perspective\n- Check out [PyMC3](https://docs.pymc.io/) (note this goes beyond hypothesis tests into modeling) - read the guides and work through some examples\n- Take PyMC3 further - see if you can build something with it!\n\n\n```\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\ndef prob_drunk_given_positive(prob_drunk_prior, prob_positive, prob_positive_drunk):\n return (prob_positive_drunk*prob_drunk_prior)/prob_positive\n\nprob_drunk_given_positive(1/1000, 0.08, 1)\n \n \n```\n\n\n\n\n 0.0125\n\n\n\n\n```\nfrom google.colab import files\nuploaded = files.upload()\n```\n\n\n\n\n\n Upload widget is only available when the cell has been executed in the\n current browser session. Please rerun this cell to enable.\n \n \n\n\n Saving house-votes-84.csv to house-votes-84.csv\n\n\n\n```\ndf = pd.read_csv(\"house-votes-84.csv\", header=None)\ndf = df.replace({\"n\": 0, \"y\": 1, \"?\": np.nan})\ndf = df.dropna()\n```\n\n\n```\ndf[1].head(1)\n```\n\n\n\n\n 5 0.0\n Name: 1, dtype: float64\n\n\n\n\n```\n#computing confidence intervals for the frequentist perspective \ndef confidence_interval(data, confidence=.95):\n n = len(data)\n mean = sum(data)/n\n data = np.array(data)\n stderr = stats.sem(data)\n interval = stderr * stats.t.ppf((1 + confidence) / 2.0, n-1)\n return (mean , mean-interval, mean+interval)\n\n```\n\n\n```\nfrequentist = confidence_interval(df[1], confidence=.95)\nfrequentist\n```\n\n\n\n\n (0.41379310344827586, 0.34994610096505746, 0.47764010593149425)\n\n\n\n\n```\n#plotting a simple histogram and showing the CI with the 2 vertical lines plotted below\ndf[1].hist();\nplt.axvline(x=0.3499);\nplt.axvline(x=0.4776);\n```\n\n\n```\n#Bayesian confidene intervals \nbayesian = stats.bayes_mvs(df[1], alpha = 0.95)\nbayesian\n```\n\n\n\n\n (Mean(statistic=0.41379310344827586, minmax=(0.34994610096505746, 0.47764010593149425)),\n Variance(statistic=0.2457461225719019, minmax=(0.20464767977302759, 0.29495113297095016)),\n Std_dev(statistic=0.4951869808760229, minmax=(0.4523800169912765, 0.5430940369502782)))\n\n\n\n\n```\n#plotting our histogram for the voting category corresponding to our first df column\n#it is interesting to note that the values are identical\n#since we are using the same data for both CI computations\n#we would need to gather more data and compute the CI's again for our Bayesian CI to change\ndf[1].hist();\nplt.axvline(x=0.3499);\nplt.axvline(x=0.4776);\nplt.axvline(x=0.3499);\nplt.axvline(x=0.4776);\n\n```\n\nFrequentists calculate probabilities by using all available data on a specific issue while Bayesians update their probability calculations with new data gathered and iterate upon their findings. In other words, a frequentist's world view is static while a Bayesians' one isn't. \n\n## Resources\n\n- [Worked example of Bayes rule calculation](https://en.wikipedia.org/wiki/Bayes'_theorem#Examples) (helpful as it fully breaks out the denominator)\n- [Source code for mvsdist in scipy](https://github.com/scipy/scipy/blob/90534919e139d2a81c24bf08341734ff41a3db12/scipy/stats/morestats.py#L139)\n", "meta": {"hexsha": "f67caf57f5af7df2bfaf05af26e62f2d94ce937d", "size": 58464, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Copy_of_LS_DS3_143_Introduction_to_Bayesian_Inference.ipynb", "max_stars_repo_name": "tomfox1/DS-Unit-1-Sprint-4-Statistical-Tests-and-Experiments", "max_stars_repo_head_hexsha": "5ed3e7f99a5c15e86799b9bd7a8691dabb9b3967", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Copy_of_LS_DS3_143_Introduction_to_Bayesian_Inference.ipynb", "max_issues_repo_name": "tomfox1/DS-Unit-1-Sprint-4-Statistical-Tests-and-Experiments", "max_issues_repo_head_hexsha": "5ed3e7f99a5c15e86799b9bd7a8691dabb9b3967", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Copy_of_LS_DS3_143_Introduction_to_Bayesian_Inference.ipynb", "max_forks_repo_name": "tomfox1/DS-Unit-1-Sprint-4-Statistical-Tests-and-Experiments", "max_forks_repo_head_hexsha": "5ed3e7f99a5c15e86799b9bd7a8691dabb9b3967", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 57.7707509881, "max_line_length": 7349, "alphanum_fraction": 0.6549671593, "converted": true, "num_tokens": 5733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814501625211, "lm_q2_score": 0.4843800842769843, "lm_q1q2_score": 0.21021197140436984}} {"text": "# Sentiment Analysis with TreeLSTMs in TensorFlow Fold\n\nThe [Stanford Sentiment Treebank](http://nlp.stanford.edu/sentiment/treebank.html) is a corpus of ~10K one-sentence movie reviews from Rotten Tomatoes. The sentences have been parsed into binary trees with words at the leaves; every sub-tree has a label ranging from 0 (highly negative) to 4 (highly positive); 2 means neutral.\n\nFor example, `(4 (2 Spiderman) (3 ROCKS))` is sentence with two words, corresponding a binary tree with three nodes. The label at the root, for the entire sentence, is `4` (highly positive). The label for the left child, a leaf corresponding to the word `Spiderman`, is `2` (neutral). The label for the right child, a leaf corresponding to the word `ROCKS` is `3` (moderately positive).\n\nThis notebook shows how to use TensorFlow Fold train a model on the treebank using binary TreeLSTMs and [GloVe](http://nlp.stanford.edu/projects/glove/) word embedding vectors, as described in the paper [Improved Semantic Representations From Tree-Structured Long Short-Term Memory Networks](http://arxiv.org/pdf/1503.00075.pdf) by Tai et al. The original [Torch](http://torch.ch) source code for the model, provided by the authors, is available [here](https://github.com/stanfordnlp/treelstm).\n\nThe model illustrates three of the more advanced features of Fold, namely:\n1. [Compositions](https://github.com/tensorflow/fold/blob/master/tensorflow_fold/g3doc/blocks.md#wiring-things-together-in-more-complicated-ways) to wire up blocks to form arbitrary directed acyclic graphs\n2. [Forward Declarations](https://github.com/tensorflow/fold/blob/master/tensorflow_fold/g3doc/blocks.md#recursion-and-forward-declarations) to create recursive blocks\n3. [Metrics](https://github.com/tensorflow/fold/blob/master/tensorflow_fold/g3doc/py/td.md#class-tdmetric) to create models where the size of the output is not fixed, but varies as a function of the input data.\n\n\n```python\n# boilerplate\nimport codecs\nimport functools\nimport os\nimport tempfile\nimport zipfile\n\nfrom nltk.tokenize import sexpr\nimport numpy as np\nfrom six.moves import urllib\nimport tensorflow as tf\nsess = tf.InteractiveSession()\nimport tensorflow_fold as td\n```\n\n## Get the data\n\nBegin by fetching the word embedding vectors and treebank sentences.\n\n\n```python\ndata_dir = tempfile.mkdtemp()\nprint('saving files to %s' % data_dir)\n```\n\n saving files to /tmp/tmpPhKqpj\n\n\n\n```python\ndef download_and_unzip(url_base, zip_name, *file_names):\n zip_path = os.path.join(data_dir, zip_name)\n url = url_base + zip_name\n print('downloading %s to %s' % (url, zip_path))\n urllib.request.urlretrieve(url, zip_path)\n out_paths = []\n with zipfile.ZipFile(zip_path, 'r') as f:\n for file_name in file_names:\n print('extracting %s' % file_name)\n out_paths.append(f.extract(file_name, path=data_dir))\n return out_paths\n \n```\n\n\n```python\nfull_glove_path, = download_and_unzip(\n 'http://nlp.stanford.edu/data/', 'glove.840B.300d.zip',\n 'glove.840B.300d.txt')\n```\n\n downloading http://nlp.stanford.edu/data/glove.840B.300d.zip to /tmp/tmpPhKqpj/glove.840B.300d.zip\n extracting glove.840B.300d.txt\n\n\n\n```python\ntrain_path, dev_path, test_path = download_and_unzip(\n 'http://nlp.stanford.edu/sentiment/', 'trainDevTestTrees_PTB.zip', \n 'trees/train.txt', 'trees/dev.txt', 'trees/test.txt')\n```\n\n downloading http://nlp.stanford.edu/sentiment/trainDevTestTrees_PTB.zip to /tmp/tmpPhKqpj/trainDevTestTrees_PTB.zip\n extracting trees/train.txt\n extracting trees/dev.txt\n extracting trees/test.txt\n\n\nFilter out words that don't appear in the dataset, since the full dataset is a bit large (5GB). This is purely a performance optimization and has no effect on the final results.\n\n\n```python\nfiltered_glove_path = os.path.join(data_dir, 'filtered_glove.txt')\n```\n\n\n```python\ndef filter_glove():\n vocab = set()\n # Download the full set of unlabeled sentences separated by '|'.\n sentence_path, = download_and_unzip(\n 'http://nlp.stanford.edu/~socherr/', 'stanfordSentimentTreebank.zip', \n 'stanfordSentimentTreebank/SOStr.txt')\n with codecs.open(sentence_path, encoding='utf-8') as f:\n for line in f:\n # Drop the trailing newline and strip backslashes. Split into words.\n vocab.update(line.strip().replace('\\\\', '').split('|'))\n nread = 0\n nwrote = 0\n with codecs.open(full_glove_path, encoding='utf-8') as f:\n with codecs.open(filtered_glove_path, 'w', encoding='utf-8') as out:\n for line in f:\n nread += 1\n line = line.strip()\n if not line: continue\n if line.split(u' ', 1)[0] in vocab:\n out.write(line + '\\n')\n nwrote += 1\n print('read %s lines, wrote %s' % (nread, nwrote))\n```\n\n\n```python\nfilter_glove()\n```\n\n downloading http://nlp.stanford.edu/~socherr/stanfordSentimentTreebank.zip to /tmp/tmpPhKqpj/stanfordSentimentTreebank.zip\n extracting stanfordSentimentTreebank/SOStr.txt\n read 2196018 lines, wrote 20725\n\n\nLoad the filtered word embeddings into a matrix and build an dict from words to indices into the matrix. Add a random embedding vector for out-of-vocabulary words.\n\n\n```python\ndef load_embeddings(embedding_path):\n \"\"\"Loads embedings, returns weight matrix and dict from words to indices.\"\"\"\n print('loading word embeddings from %s' % embedding_path)\n weight_vectors = []\n word_idx = {}\n with codecs.open(embedding_path, encoding='utf-8') as f:\n for line in f:\n word, vec = line.split(u' ', 1)\n word_idx[word] = len(weight_vectors)\n weight_vectors.append(np.array(vec.split(), dtype=np.float32))\n # Annoying implementation detail; '(' and ')' are replaced by '-LRB-' and\n # '-RRB-' respectively in the parse-trees.\n word_idx[u'-LRB-'] = word_idx.pop(u'(')\n word_idx[u'-RRB-'] = word_idx.pop(u')')\n # Random embedding vector for unknown words.\n weight_vectors.append(np.random.uniform(\n -0.05, 0.05, weight_vectors[0].shape).astype(np.float32))\n return np.stack(weight_vectors), word_idx\n```\n\n\n```python\nweight_matrix, word_idx = load_embeddings(filtered_glove_path)\n```\n\n loading word embeddings from /tmp/tmpPhKqpj/filtered_glove.txt\n\n\nFinally, load the treebank data.\n\n\n```python\ndef load_trees(filename):\n with codecs.open(filename, encoding='utf-8') as f:\n # Drop the trailing newline and strip \\s.\n trees = [line.strip().replace('\\\\', '') for line in f]\n print('loaded %s trees from %s' % (len(trees), filename))\n return trees\n```\n\n\n```python\ntrain_trees = load_trees(train_path)\ndev_trees = load_trees(dev_path)\ntest_trees = load_trees(test_path)\n```\n\n loaded 8544 trees from /tmp/tmpPhKqpj/trees/train.txt\n loaded 1101 trees from /tmp/tmpPhKqpj/trees/dev.txt\n loaded 2210 trees from /tmp/tmpPhKqpj/trees/test.txt\n\n\n## Build the model\n\nWe want to compute a hidden state vector $h$ for every node in the tree. The hidden state is the input to a linear layer with softmax output for predicting the sentiment label. \n\nAt the leaves of the tree, words are mapped to word-embedding vectors which serve as the input to a binary tree-LSTM with $0$ for the previous states. At the internal nodes, the LSTM takes $0$ as input, and previous states from its two children. More formally,\n\n\\begin{align}\nh_{word} &= TreeLSTM(Embedding(word), 0, 0) \\\\\nh_{left, right} &= TreeLSTM(0, h_{left}, h_{right})\n\\end{align}\n\nwhere $TreeLSTM(x, h_{left}, h_{right})$ is a special kind of LSTM cell that takes two hidden states as inputs, and has a separate forget gate for each of them. Specifically, it is [Tai et al.](http://arxiv.org/pdf/1503.00075.pdf) eqs. 9-14 with $N=2$. One modification here from Tai et al. is that instead of L2 weight regularization, we use recurrent droupout as described in the paper [Recurrent Dropout without Memory Loss](http://arxiv.org/pdf/1603.05118.pdf).\n\nWe can implement $TreeLSTM$ by subclassing the TensorFlow [`BasicLSTMCell`](https://www.tensorflow.org/versions/r1.0/api_docs/python/contrib.rnn/rnn_cells_for_use_with_tensorflow_s_core_rnn_methods#BasicLSTMCell).\n\n\n\n```python\nclass BinaryTreeLSTMCell(tf.contrib.rnn.BasicLSTMCell):\n \"\"\"LSTM with two state inputs.\n\n This is the model described in section 3.2 of 'Improved Semantic\n Representations From Tree-Structured Long Short-Term Memory\n Networks' , with recurrent\n dropout as described in 'Recurrent Dropout without Memory Loss'\n .\n \"\"\"\n\n def __init__(self, num_units, keep_prob=1.0):\n \"\"\"Initialize the cell.\n\n Args:\n num_units: int, The number of units in the LSTM cell.\n keep_prob: Keep probability for recurrent dropout.\n \"\"\"\n super(BinaryTreeLSTMCell, self).__init__(num_units)\n self._keep_prob = keep_prob\n\n def __call__(self, inputs, state, scope=None):\n with tf.variable_scope(scope or type(self).__name__):\n lhs, rhs = state\n c0, h0 = lhs\n c1, h1 = rhs\n concat = tf.contrib.layers.linear(\n tf.concat([inputs, h0, h1], 1), 5 * self._num_units)\n\n # i = input_gate, j = new_input, f = forget_gate, o = output_gate\n i, j, f0, f1, o = tf.split(value=concat, num_or_size_splits=5, axis=1)\n\n j = self._activation(j)\n if not isinstance(self._keep_prob, float) or self._keep_prob < 1:\n j = tf.nn.dropout(j, self._keep_prob)\n\n new_c = (c0 * tf.sigmoid(f0 + self._forget_bias) +\n c1 * tf.sigmoid(f1 + self._forget_bias) +\n tf.sigmoid(i) * j)\n new_h = self._activation(new_c) * tf.sigmoid(o)\n\n new_state = tf.contrib.rnn.LSTMStateTuple(new_c, new_h)\n\n return new_h, new_state\n```\n\nUse a placeholder for the dropout keep probability, with a default of 1 (for eval).\n\n\n```python\nkeep_prob_ph = tf.placeholder_with_default(1.0, [])\n```\n\nCreate the LSTM cell for our model. In addition to recurrent dropout, apply dropout to inputs and outputs, using TF's build-in dropout wrapper. Put the LSTM cell inside of a [`td.ScopedLayer`](https://github.com/tensorflow/fold/blob/master/tensorflow_fold/g3doc/py/td.md#class-tdscopedlayer) in order to manage variable scoping. This ensures that our LSTM's variables are encapsulated from the rest of the graph and get created exactly once.\n\n\n\n```python\nlstm_num_units = 300 # Tai et al. used 150, but our regularization strategy is more effective\ntree_lstm = td.ScopedLayer(\n tf.contrib.rnn.DropoutWrapper(\n BinaryTreeLSTMCell(lstm_num_units, keep_prob=keep_prob_ph),\n input_keep_prob=keep_prob_ph, output_keep_prob=keep_prob_ph),\n name_or_scope='tree_lstm')\n```\n\nCreate the output layer using [`td.FC`](https://github.com/tensorflow/fold/blob/master/tensorflow_fold/g3doc/py/td.md#class-tdfc).\n\n\n```python\nNUM_CLASSES = 5 # number of distinct sentiment labels\noutput_layer = td.FC(NUM_CLASSES, activation=None, name='output_layer')\n```\n\nCreate the word embedding using [`td.Embedding`](https://github.com/tensorflow/fold/blob/master/tensorflow_fold/g3doc/py/td.md#class-tdembedding). Note that the built-in Fold layers like `Embedding` and `FC` manage variable scoping automatically, so there is no need to put them inside scoped layers.\n\n\n```python\nword_embedding = td.Embedding(\n *weight_matrix.shape, initializer=weight_matrix, name='word_embedding')\n```\n\nWe now have layers that encapsulate all of the trainable variables for our model. The next step is to create the Fold blocks that define how inputs (s-expressions encoded as strings) get processed and used to make predictions. Naturally this requires a recursive model, which we handle in Fold using a [forward declaration](https://github.com/tensorflow/fold/blob/master/tensorflow_fold/g3doc/blocks.md#recursion-and-forward-declarations). The recursive step is to take a subtree (represented as a string) and convert it into a hidden state vector (the LSTM state), thus embedding it in a $n$-dimensional space (where here $n=300$).\n\n\n```python\nembed_subtree = td.ForwardDeclaration(name='embed_subtree')\n```\n\nThe core the model is a block that takes as input a list of tokens. The tokens will be either:\n\n* `[word]` - a leaf with a single word, the base-case for the recursion, or\n* `[lhs, rhs]` - an internal node consisting of a pair of sub-expressions\n\nThe outputs of the block will be a pair consisting of logits (the prediction) and the LSTM state.\n\n\n```python\ndef logits_and_state():\n \"\"\"Creates a block that goes from tokens to (logits, state) tuples.\"\"\"\n unknown_idx = len(word_idx)\n lookup_word = lambda word: word_idx.get(word, unknown_idx)\n \n word2vec = (td.GetItem(0) >> td.InputTransform(lookup_word) >>\n td.Scalar('int32') >> word_embedding)\n\n pair2vec = (embed_subtree(), embed_subtree())\n\n # Trees are binary, so the tree layer takes two states as its input_state.\n zero_state = td.Zeros((tree_lstm.state_size,) * 2)\n # Input is a word vector.\n zero_inp = td.Zeros(word_embedding.output_type.shape[0])\n\n word_case = td.AllOf(word2vec, zero_state)\n pair_case = td.AllOf(zero_inp, pair2vec)\n\n tree2vec = td.OneOf(len, [(1, word_case), (2, pair_case)])\n\n return tree2vec >> tree_lstm >> (output_layer, td.Identity())\n```\n\nNote that we use the call operator `()` to create blocks that reference the `embed_subtree` forward declaration, for the recursive case.\n\nDefine a per-node loss function for training.\n\n\n```python\ndef tf_node_loss(logits, labels):\n return tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=labels)\n```\n\nAdditionally calculate fine-grained and binary hits (i.e. un-normalized accuracy) for evals. Fine-grained accuracy is defined over all five class labels and will be calculated for all labels, whereas binary accuracy is defined of negative vs. positive classification and will not be calcluated for neutral labels.\n\n\n```python\ndef tf_fine_grained_hits(logits, labels):\n predictions = tf.cast(tf.argmax(logits, 1), tf.int32)\n return tf.cast(tf.equal(predictions, labels), tf.float64)\n```\n\n\n```python\ndef tf_binary_hits(logits, labels):\n softmax = tf.nn.softmax(logits)\n binary_predictions = (softmax[:, 3] + softmax[:, 4]) > (softmax[:, 0] + softmax[:, 1])\n binary_labels = labels > 2\n return tf.cast(tf.equal(binary_predictions, binary_labels), tf.float64)\n```\n\nThe [`td.Metric`](https://github.com/tensorflow/fold/blob/master/tensorflow_fold/g3doc/py/td.md#class-tdmetric) block provides a mechaism for accumulating results across sequential and recursive computations without having the thread them through explictly as return values. Metrics are wired up here inside of a [`td.Composition`](https://github.com/tensorflow/fold/blob/master/tensorflow_fold/g3doc/blocks.md#wiring-things-together-in-more-complicated-ways) block, which allows us to explicitly specify the inputs of sub-blocks with calls to `Block.reads()` inside of a [`Composition.scope()`](https://github.com/tensorflow/fold/blob/master/tensorflow_fold/g3doc/py/td.md#tdcompositionscope) context manager.\n\nFor training, we will sum the loss over all nodes. But for evals, we would like to separately calcluate accuracies for the root (i.e. entire sentences) to match the numbers presented in the literature. We also need to distinguish between neutral and non-neutral sentiment labels, because binary sentiment doesn't get calculated for neutral nodes.\n\nThis is easy to do by putting our block creation code for calculating metrics inside of a function and passing it indicators. Note that this needs to be done in Python-land, because we can't inspect the contents of a tensor inside of Fold (since it hasn't been run yet).\n\n\n```python\ndef add_metrics(is_root, is_neutral):\n \"\"\"A block that adds metrics for loss and hits; output is the LSTM state.\"\"\"\n c = td.Composition(\n name='predict(is_root=%s, is_neutral=%s)' % (is_root, is_neutral))\n with c.scope():\n # destructure the input; (labels, (logits, state))\n labels = c.input[0]\n logits = td.GetItem(0).reads(c.input[1])\n state = td.GetItem(1).reads(c.input[1])\n\n # calculate loss\n loss = td.Function(tf_node_loss)\n td.Metric('all_loss').reads(loss.reads(logits, labels))\n if is_root: td.Metric('root_loss').reads(loss)\n\n # calculate fine-grained hits\n hits = td.Function(tf_fine_grained_hits)\n td.Metric('all_hits').reads(hits.reads(logits, labels))\n if is_root: td.Metric('root_hits').reads(hits)\n\n # calculate binary hits, if the label is not neutral\n if not is_neutral:\n binary_hits = td.Function(tf_binary_hits).reads(logits, labels)\n td.Metric('all_binary_hits').reads(binary_hits)\n if is_root: td.Metric('root_binary_hits').reads(binary_hits)\n\n # output the state, which will be read by our by parent's LSTM cell\n c.output.reads(state)\n return c\n```\n\nUse [NLTK](http://www.nltk.org/) to define a `tokenize` function to split S-exprs into left and right parts. We need this to run our `logits_and_state()` block since it expects to be passed a list of tokens and our raw input is strings.\n\n\n```python\ndef tokenize(s):\n label, phrase = s[1:-1].split(None, 1)\n return label, sexpr.sexpr_tokenize(phrase)\n```\n\nTry it out.\n\n\n```python\ntokenize('(X Y)')\n```\n\n\n\n\n ('X', ['Y'])\n\n\n\n\n```python\ntokenize('(X Y Z)')\n```\n\n\n\n\n ('X', ['Y Z'])\n\n\n\nEmbed trees (represented as strings) by tokenizing and piping (`>>`) to `label_and_logits`, distinguishing between neutral and non-neutral labels. We don't know here whether or not we are the root node (since this is a recursive computation), so that gets threaded through as an indicator.\n\n\n```python\ndef embed_tree(logits_and_state, is_root):\n \"\"\"Creates a block that embeds trees; output is tree LSTM state.\"\"\"\n return td.InputTransform(tokenize) >> td.OneOf(\n key_fn=lambda pair: pair[0] == '2', # label 2 means neutral\n case_blocks=(add_metrics(is_root, is_neutral=False),\n add_metrics(is_root, is_neutral=True)),\n pre_block=(td.Scalar('int32'), logits_and_state))\n```\n\nPut everything together and create our top-level (i.e. root) model. It is rather simple.\n\n\n```python\nmodel = embed_tree(logits_and_state(), is_root=True)\n```\n\nResolve the forward declaration for embedding subtrees (the non-root case) with a second call to `embed_tree`.\n\n\n```python\nembed_subtree.resolve_to(embed_tree(logits_and_state(), is_root=False))\n```\n\n[Compile](https://github.com/tensorflow/fold/blob/master/tensorflow_fold/g3doc/running.md#batching-inputs) the model.\n\n\n```python\ncompiler = td.Compiler.create(model)\nprint('input type: %s' % model.input_type)\nprint('output type: %s' % model.output_type)\n```\n\n input type: PyObjectType()\n output type: TupleType(TensorType((300,), 'float32'), TensorType((300,), 'float32'))\n\n\n## Setup for training\n\nCalculate means by summing the raw metrics.\n\n\n```python\nmetrics = {k: tf.reduce_mean(v) for k, v in compiler.metric_tensors.items()}\n```\n\nMagic numbers.\n\n\n```python\nLEARNING_RATE = 0.05\nKEEP_PROB = 0.75\nBATCH_SIZE = 100\nEPOCHS = 20\nEMBEDDING_LEARNING_RATE_FACTOR = 0.1\n```\n\nTraining with [Adagrad](https://www.tensorflow.org/versions/master/api_docs/python/train/optimizers#AdagradOptimizer).\n\n\n```python\ntrain_feed_dict = {keep_prob_ph: KEEP_PROB}\nloss = tf.reduce_sum(compiler.metric_tensors['all_loss'])\nopt = tf.train.AdagradOptimizer(LEARNING_RATE)\n```\n\nImportant detail from section 5.3 of [Tai et al.]((http://arxiv.org/pdf/1503.00075.pdf); downscale the gradients for the word embedding vectors 10x otherwise we overfit horribly.\n\n\n\n```python\ngrads_and_vars = opt.compute_gradients(loss)\nfound = 0\nfor i, (grad, var) in enumerate(grads_and_vars):\n if var == word_embedding.weights:\n found += 1\n grad = tf.scalar_mul(EMBEDDING_LEARNING_RATE_FACTOR, grad)\n grads_and_vars[i] = (grad, var)\nassert found == 1 # internal consistency check\ntrain = opt.apply_gradients(grads_and_vars)\nsaver = tf.train.Saver()\n```\n\n /usr/local/google/home/madscience/nuke/v3/local/lib/python2.7/site-packages/tensorflow/python/ops/gradients_impl.py:91: UserWarning: Converting sparse IndexedSlices to a dense Tensor of unknown shape. This may consume a large amount of memory.\n \"Converting sparse IndexedSlices to a dense Tensor of unknown shape. \"\n\n\nThe TF graph is now complete; initialize the variables.\n\n\n```python\nsess.run(tf.global_variables_initializer())\n```\n\n## Train the model\n\nStart by defining a function that does a single step of training on a batch and returns the loss.\n\n\n```python\ndef train_step(batch):\n train_feed_dict[compiler.loom_input_tensor] = batch\n _, batch_loss = sess.run([train, loss], train_feed_dict)\n return batch_loss\n```\n\nNow similarly for an entire epoch of training.\n\n\n```python\ndef train_epoch(train_set):\n return sum(train_step(batch) for batch in td.group_by_batches(train_set, BATCH_SIZE))\n\n```\n\nUse [`Compiler.build_loom_inputs()`](https://github.com/tensorflow/fold/blob/master/tensorflow_fold/g3doc/py/td.md#tdcompilerbuild_loom_inputsexamples-metric_labelsfalse-chunk_size100-orderedfalse) to transform `train_trees` into individual loom inputs (i.e. wiring diagrams) that we can use to actually run the model.\n\n\n```python\ntrain_set = compiler.build_loom_inputs(train_trees)\n```\n\nUse [`Compiler.build_feed_dict()`](https://github.com/tensorflow/fold/blob/master/tensorflow_fold/g3doc/py/td.md#tdcompilerbuild_feed_dictexamples-batch_sizenone-metric_labelsfalse-orderedfalse) to build a feed dictionary for validation on the dev set. This is marginally faster and more convenient than calling `build_loom_inputs`. We used `build_loom_inputs` on the train set so that we can shuffle the individual wiring diagrams into different batches for each epoch.\n\n\n```python\ndev_feed_dict = compiler.build_feed_dict(dev_trees)\n```\n\nDefine a function to do an eval on the dev set and pretty-print some stats, returning accuracy on the dev set.\n\n\n```python\ndef dev_eval(epoch, train_loss):\n dev_metrics = sess.run(metrics, dev_feed_dict)\n dev_loss = dev_metrics['all_loss']\n dev_accuracy = ['%s: %.2f' % (k, v * 100) for k, v in\n sorted(dev_metrics.items()) if k.endswith('hits')]\n print('epoch:%4d, train_loss: %.3e, dev_loss_avg: %.3e, dev_accuracy:\\n [%s]'\n % (epoch, train_loss, dev_loss, ' '.join(dev_accuracy)))\n return dev_metrics['root_hits']\n```\n\nRun the main training loop, saving the model after each epoch if it has the best accuracy on the dev set. Use the [`td.epochs`](https://github.com/tensorflow/fold/blob/master/tensorflow_fold/g3doc/py/td.md#tdepochsitems-nnone-shuffletrue-prngnone) utility function to memoize the loom inputs and shuffle them after every epoch of training.\n\n\n```python\nbest_accuracy = 0.0\nsave_path = os.path.join(data_dir, 'sentiment_model')\nfor epoch, shuffled in enumerate(td.epochs(train_set, EPOCHS), 1):\n train_loss = train_epoch(shuffled)\n accuracy = dev_eval(epoch, train_loss)\n if accuracy > best_accuracy:\n best_accuracy = accuracy\n checkpoint_path = saver.save(sess, save_path, global_step=epoch)\n print('model saved in file: %s' % checkpoint_path)\n```\n\n epoch: 1, train_loss: 2.262e+05, dev_loss_avg: 5.253e-01, dev_accuracy:\n [all_binary_hits: 88.94 all_hits: 78.30 root_binary_hits: 82.00 root_hits: 40.51]\n model saved in file: /tmp/tmpPhKqpj/sentiment_model-1\n epoch: 2, train_loss: 1.590e+05, dev_loss_avg: 4.602e-01, dev_accuracy:\n [all_binary_hits: 90.41 all_hits: 81.00 root_binary_hits: 83.60 root_hits: 46.59]\n model saved in file: /tmp/tmpPhKqpj/sentiment_model-2\n epoch: 3, train_loss: 1.443e+05, dev_loss_avg: 4.371e-01, dev_accuracy:\n [all_binary_hits: 91.17 all_hits: 82.02 root_binary_hits: 85.21 root_hits: 48.68]\n model saved in file: /tmp/tmpPhKqpj/sentiment_model-3\n epoch: 4, train_loss: 1.357e+05, dev_loss_avg: 4.242e-01, dev_accuracy:\n [all_binary_hits: 91.63 all_hits: 82.45 root_binary_hits: 87.04 root_hits: 49.86]\n model saved in file: /tmp/tmpPhKqpj/sentiment_model-4\n epoch: 5, train_loss: 1.297e+05, dev_loss_avg: 4.190e-01, dev_accuracy:\n [all_binary_hits: 92.07 all_hits: 82.64 root_binary_hits: 88.19 root_hits: 51.50]\n model saved in file: /tmp/tmpPhKqpj/sentiment_model-5\n epoch: 6, train_loss: 1.246e+05, dev_loss_avg: 4.175e-01, dev_accuracy:\n [all_binary_hits: 91.77 all_hits: 82.52 root_binary_hits: 86.81 root_hits: 49.41]\n epoch: 7, train_loss: 1.209e+05, dev_loss_avg: 4.164e-01, dev_accuracy:\n [all_binary_hits: 92.08 all_hits: 82.81 root_binary_hits: 87.61 root_hits: 50.41]\n epoch: 8, train_loss: 1.172e+05, dev_loss_avg: 4.177e-01, dev_accuracy:\n [all_binary_hits: 91.92 all_hits: 82.88 root_binary_hits: 87.50 root_hits: 50.14]\n epoch: 9, train_loss: 1.143e+05, dev_loss_avg: 4.158e-01, dev_accuracy:\n [all_binary_hits: 92.16 all_hits: 82.84 root_binary_hits: 87.73 root_hits: 49.86]\n epoch: 10, train_loss: 1.120e+05, dev_loss_avg: 4.152e-01, dev_accuracy:\n [all_binary_hits: 92.27 all_hits: 82.91 root_binary_hits: 87.50 root_hits: 50.77]\n epoch: 11, train_loss: 1.094e+05, dev_loss_avg: 4.179e-01, dev_accuracy:\n [all_binary_hits: 92.35 all_hits: 82.98 root_binary_hits: 88.76 root_hits: 50.14]\n epoch: 12, train_loss: 1.074e+05, dev_loss_avg: 4.221e-01, dev_accuracy:\n [all_binary_hits: 91.96 all_hits: 83.03 root_binary_hits: 87.16 root_hits: 50.05]\n epoch: 13, train_loss: 1.055e+05, dev_loss_avg: 4.224e-01, dev_accuracy:\n [all_binary_hits: 92.04 all_hits: 83.05 root_binary_hits: 87.50 root_hits: 50.05]\n epoch: 14, train_loss: 1.039e+05, dev_loss_avg: 4.204e-01, dev_accuracy:\n [all_binary_hits: 92.38 all_hits: 83.01 root_binary_hits: 88.76 root_hits: 51.32]\n epoch: 15, train_loss: 1.017e+05, dev_loss_avg: 4.229e-01, dev_accuracy:\n [all_binary_hits: 92.52 all_hits: 82.92 root_binary_hits: 88.53 root_hits: 49.68]\n epoch: 16, train_loss: 1.004e+05, dev_loss_avg: 4.278e-01, dev_accuracy:\n [all_binary_hits: 92.57 all_hits: 83.00 root_binary_hits: 88.42 root_hits: 52.13]\n model saved in file: /tmp/tmpPhKqpj/sentiment_model-16\n epoch: 17, train_loss: 9.887e+04, dev_loss_avg: 4.316e-01, dev_accuracy:\n [all_binary_hits: 92.31 all_hits: 82.87 root_binary_hits: 87.73 root_hits: 51.04]\n epoch: 18, train_loss: 9.742e+04, dev_loss_avg: 4.328e-01, dev_accuracy:\n [all_binary_hits: 92.28 all_hits: 82.90 root_binary_hits: 88.42 root_hits: 51.59]\n epoch: 19, train_loss: 9.633e+04, dev_loss_avg: 4.338e-01, dev_accuracy:\n [all_binary_hits: 92.41 all_hits: 82.86 root_binary_hits: 88.53 root_hits: 51.68]\n epoch: 20, train_loss: 9.474e+04, dev_loss_avg: 4.368e-01, dev_accuracy:\n [all_binary_hits: 92.23 all_hits: 82.90 root_binary_hits: 87.96 root_hits: 50.14]\n\n\nThe model starts to overfit pretty quickly even with dropout, as the LSTM begins to memorize the training set (which is rather small).\n\n## Evaluate the model\n\nRestore the model from the last checkpoint, where we saw the best accuracy on the dev set.\n\n\n```python\nsaver.restore(sess, checkpoint_path)\n```\n\nSee how we did.\n\n\n```python\ntest_results = sorted(sess.run(metrics, compiler.build_feed_dict(test_trees)).items())\nprint(' loss: [%s]' % ' '.join(\n '%s: %.3e' % (name.rsplit('_', 1)[0], v)\n for name, v in test_results if name.endswith('_loss')))\nprint('accuracy: [%s]' % ' '.join(\n '%s: %.2f' % (name.rsplit('_', 1)[0], v * 100)\n for name, v in test_results if name.endswith('_hits')))\n```\n\n loss: [all: 4.276e-01 root: 1.121e+00]\n accuracy: [all_binary: 92.37 all: 83.13 root_binary: 89.29 root: 51.90]\n\n\nNot bad! See section 3.5.1 of [our paper](https://openreview.net/pdf?id=ryrGawqex) for discussion and a comparison of these results to the state of the art.\n", "meta": {"hexsha": "3bc53af9116c38ad3ec7ff9ef13b0a239a88e7d3", "size": 40883, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tensorflow_fold/g3doc/sentiment.ipynb", "max_stars_repo_name": "BioGeek/fold", "max_stars_repo_head_hexsha": "a1e1ab3625f7624ed3ae90d08a4ea11cfd296294", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-21T16:34:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-21T16:34:33.000Z", "max_issues_repo_path": "tensorflow_fold/g3doc/sentiment.ipynb", "max_issues_repo_name": "samjabrahams/fold", "max_issues_repo_head_hexsha": "a1e1ab3625f7624ed3ae90d08a4ea11cfd296294", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tensorflow_fold/g3doc/sentiment.ipynb", "max_forks_repo_name": "samjabrahams/fold", "max_forks_repo_head_hexsha": "a1e1ab3625f7624ed3ae90d08a4ea11cfd296294", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-14T00:44:37.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-14T00:44:37.000Z", "avg_line_length": 34.3843566022, "max_line_length": 719, "alphanum_fraction": 0.6084191473, "converted": true, "num_tokens": 7612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.20907008854238526}} {"text": "+ This notebook is part of lecture 19 *Determinant formulas and cofactors* in the OCW MIT course 18.06 by Prof Gilbert Strang [1]\n+ Created by me, Dr Juan H Klopper\n + Head of Acute Care Surgery\n + Groote Schuur Hospital\n + University Cape Town\n + Email me with your thoughts, comments, suggestions and corrections \n
Linear Algebra OCW MIT18.06 IPython notebook [2] study notes by Dr Juan H Klopper is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.\n\n+ [1] OCW MIT 18.06\n+ [2] Fernando Pérez, Brian E. Granger, IPython: A System for Interactive Scientific Computing, Computing in Science and Engineering, vol. 9, no. 3, pp. 21-29, May/June 2007, doi:10.1109/MCSE.2007.53. URL: http://ipython.org\n\n\n```python\nfrom IPython.core.display import HTML, Image\ncss_file = 'style.css'\nHTML(open(css_file, 'r').read())\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n```python\nfrom sympy import init_printing, symbols, Matrix\nfrom warnings import filterwarnings\n```\n\n\n```python\ninit_printing(use_latex = 'mathjax')\nfilterwarnings('ignore')\n```\n\n\n```python\nx, y = symbols('x y')\n```\n\n# Determinant formulas and cofactors\n# Tridiagonal matrices\n\n## Creating an equation for the determinant of a 2×2 matrix\n\n* Using just the three main properties from the previous lecture and knowing that the determinant of a matrix with a column of zero's is zero we have the following\n$$ \\begin{vmatrix} a & b \\\\ c & d \\end{vmatrix}=\\begin{vmatrix} a & 0 \\\\ c & d \\end{vmatrix}+\\begin{vmatrix} 0 & b \\\\ c & d \\end{vmatrix}\\\\ =\\begin{vmatrix} a & 0 \\\\ c & 0 \\end{vmatrix}+\\begin{vmatrix} a & 0 \\\\ 0 & d \\end{vmatrix}+\\begin{vmatrix} 0 & b \\\\ c & 0 \\end{vmatrix}+\\begin{vmatrix} 0 & b \\\\ 0 & d \\end{vmatrix}\\\\ \\because \\quad \\begin{vmatrix} a & 0 \\\\ c & 0 \\end{vmatrix}=\\begin{vmatrix} 0 & b \\\\ 0 & d \\end{vmatrix}=0\\\\ \\begin{vmatrix} a & 0 \\\\ 0 & d \\end{vmatrix}+\\begin{vmatrix} 0 & b \\\\ c & 0 \\end{vmatrix}\\\\ =\\begin{vmatrix} a & 0 \\\\ 0 & d \\end{vmatrix}-\\begin{vmatrix} c & 0 \\\\ 0 & b \\end{vmatrix}\\\\ =ad-bc $$\n\n## Creating an equation for the determinant of a 3×3 matrix\n\n* By the method above, this will create a lot of matrices\n* We need to figure out which ones remain, i.e. do not have columns of zeros\n* Note carefully that we just keep those with at least one element from each row and column\n$$ \\begin{vmatrix} { a }_{ 11 } & { a }_{ 12 } & { a }_{ 13 } \\\\ { a }_{ 21 } & { a }_{ 22 } & { a }_{ 23 } \\\\ { a }_{ 31 } & { a }_{ 32 } & { a }_{ 33 } \\end{vmatrix} \\\\ =\\begin{vmatrix} { a }_{ 11 } & 0 & 0 \\\\ 0 & { a }_{ 22 } & 0 \\\\ 0 & 0 & { a }_{ 33 } \\end{vmatrix}+\\begin{vmatrix} { a }_{ 11 } & 0 & 0 \\\\ 0 & 0 & { a }_{ 23 } \\\\ 0 & { a }_{ 32 } & 0 \\end{vmatrix}+\\begin{vmatrix} 0 & { a }_{ 12 } & 0 \\\\ { a }_{ 21 } & 0 & 0 \\\\ 0 & 0 & { a }_{ 33 } \\end{vmatrix}+\\begin{vmatrix} 0 & { a }_{ 12 } & 0 \\\\ 0 & 0 & { a }_{ 23 } \\\\ { a }_{ 31 } & 0 & 0 \\end{vmatrix}+\\begin{vmatrix} 0 & 0 & { a }_{ 13 } \\\\ { a }_{ 21 } & 0 & 0 \\\\ 0 & { a }_{ 32 } & 0 \\end{vmatrix}+\\begin{vmatrix} 0 & 0 & { a }_{ 13 } \\\\ 0 & { a }_{ 22 } & 0 \\\\ { a }_{ 31 } & 0 & 0 \\end{vmatrix}\\\\ ={ a }_{ 11 }{ a }_{ 22 }{ a }_{ 33 }-{ a }_{ 11 }{ a }_{ 23 }{ a }_{ 32 }-{ a }_{ 12 }{ a }_{ 21 }{ a }_{ 33 }+{ a }_{ 12 }{ a }_{ 23 }{ a }_{ 31 }+{ a }_{ 13 }{ a }_{ 21 }{ a }_{ 32 }-{ a }_{ 13 }{ a }_{ 22 }{ a }_{ 31 } $$\n\n## Creating an equation for the determinant of a *n* × *n* matrix\n\n* We will have *n*! terms, half of which is positive and the other half negative\n* We have *n* because for the first row we have *n* positions to choose from, the for the second lot we have *n*-1 and so on\n$$ \\left| A \\right| =\\sum { \\pm { a }_{ 1\\alpha }{ a }_{ 2\\beta }{ a }_{ 3\\gamma }...{ a }_{ n\\omega } } $$\n* This holds for permuations of the columns (each used only once)\n$$ \\left( \\alpha ,\\beta ,\\gamma ,\\delta ,\\dots ,\\omega \\right) =\\left( 1,2,3,4,\\dots ,n \\right) $$\n\n* Consider this example\n$$ \\begin{bmatrix} 0 & 0 & 1 & 1 \\\\ 0 & 1 & 1 & 0 \\\\ 1 & 1 & 0 & 0 \\\\ 1 & 0 & 0 & 1 \\end{bmatrix} $$\n\n* Successively choosing a single element from each column (using column numbers for the Greek symbols above), we get the following permutations (note their sign as we interchange the numbers to follow in order 1 2 3 4\n * (4,3,2,1) = (1,2,3,4) Two *swaps*\n * (3,2,1,4) = -(1,2,3,4) One *swap*\n * That is it!\n * So we have 1 - 1 = 0\n* Note that in this example of a 4×4 matrix a lot of the permutations would have a zero in the, so we won't end up with 4! = 24 permutations\n\n\n```python\nA = Matrix([[0, 0, 1, 1], [0, 1, 1, 0], [1, 1, 0, 0], [1, 0, 0, 1]])\nA\n```\n\n\n\n\n$$\\left[\\begin{matrix}0 & 0 & 1 & 1\\\\0 & 1 & 1 & 0\\\\1 & 1 & 0 & 0\\\\1 & 0 & 0 & 1\\end{matrix}\\right]$$\n\n\n\n\n```python\nA.det()\n```\n\n\n\n\n$$0$$\n\n\n\n* We could have seen that this matrix is singular by noting that some combination of rows give identical rows and then by subtraction, a row of zero\n\n\n```python\nA.rref()\n```\n\n\n\n\n$$\\begin{pmatrix}\\left[\\begin{matrix}1 & 0 & 0 & 1\\\\0 & 1 & 0 & -1\\\\0 & 0 & 1 & 1\\\\0 & 0 & 0 & 0\\end{matrix}\\right], & \\begin{bmatrix}0, & 1, & 2\\end{bmatrix}\\end{pmatrix}$$\n\n\n\n## Cofactors of a 3×3 matrix\n\n* Start with the equation above\n$$ { a }_{ 11 }{ a }_{ 22 }{ a }_{ 33 }-{ a }_{ 11 }{ a }_{ 23 }{ a }_{ 32 }-{ a }_{ 12 }{ a }_{ 21 }{ a }_{ 33 }+{ a }_{ 12 }{ a }_{ 23 }{ a }_{ 31 }+{ a }_{ 13 }{ a }_{ 21 }{ a }_{ 32 }-{ a }_{ 13 }{ a }_{ 22 }{ a }_{ 31 } \\\\ ={ a }_{ 11 }\\left( { a }_{ 22 }{ a }_{ 33 }-{ a }_{ 23 }{ a }_{ 32 } \\right) +{ a }_{ 12 }\\left( -{ a }_{ 21 }{ a }_{ 33 }+{ a }_{ 23 }{ a }_{ 31 } \\right) +{ a }_{ 13 }\\left( { a }_{ 21 }{ a }_{ 32 }-{ a }_{ 22 }{ a }_{ 31 } \\right) $$\n* The cofactors are in parentheses and are the 2×2 submatrix determinants\n* They signify the determinant of a smaller (*n*-1) matrix with some sign problems, i.e. some are positive the determinant and some are negative the determinant\n* We are especially interested here in row one, but any row (or even column) will do\n* So for any *a*ij the cofactor is the ± determinant of the *n*-1 matrix with its *i* row and *j* column erased\n* For the sign, if *i* + *j* is even, the sign is positive and if it is odd, then the sign is negative\n* So the cofactor of *a*ij = Cij\n\n* For rows we have\n$$ { \\left| A \\right| }_{ i }=\\sum _{ k=1 }^{ n }{ { a }_{ ik }{ C }_{ ik } } $$\n\n## Diagonal matrices\n\n* Calculate\n$$ \\left| { A }_{ 1 } \\right| $$\n\n\n```python\nA = Matrix([1])\nA\n```\n\n\n\n\n$$\\left[\\begin{matrix}1\\end{matrix}\\right]$$\n\n\n\n\n```python\nA.det()\n```\n\n\n\n\n$$1$$\n\n\n\n* Calculate\n$$ \\left| { A }_{ 2 } \\right| $$\n\n\n```python\nA = Matrix([[1, 1], [1, 1]])\nA\n```\n\n\n\n\n$$\\left[\\begin{matrix}1 & 1\\\\1 & 1\\end{matrix}\\right]$$\n\n\n\n\n```python\nA.det()\n```\n\n\n\n\n$$0$$\n\n\n\n* Calculate\n$$ \\left| { A }_{ 3 } \\right| $$\n\n\n```python\nA = Matrix([[1, 1, 0], [1, 1, 1], [0, 1, 1]])\nA\n```\n\n\n\n\n$$\\left[\\begin{matrix}1 & 1 & 0\\\\1 & 1 & 1\\\\0 & 1 & 1\\end{matrix}\\right]$$\n\n\n\n* By the cofactor equation above\n$$ { \\left| A \\right| }_{ i }=\\sum _{ k=1 }^{ n }{ { a }_{ ik }{ C }_{ ik } } \\\\ { \\left| A \\right| }_{ 1 }={ a }_{ 11 }{ C }_{ 11 }+{ a }_{ 12 }{ C }_{ 12 }+{ a }_{ 13 }{ C }_{ 13 }\\\\ { C }_{ ij }\\rightarrow +;\\left( i+j \\right) \\in 2n\\\\ { C }_{ ij }\\rightarrow -;\\left( i+j \\right) \\in 2n+1\\\\ { \\left| A \\right| }_{ 1 }=1\\left( 0 \\right) -1\\left( 1 \\right) +0\\left( 1 \\right) =-1 $$\n\n\n```python\nA.det()\n```\n\n\n\n\n$$-1$$\n\n\n\n* Calculate\n$$ \\left| { A }_{ 4 } \\right| $$\n\n\n```python\nA = Matrix([[1, 1, 0, 0], [1, 1, 1, 0], [0, 1, 1, 1], [0, 0, 1, 1]])\nA\n```\n\n\n\n\n$$\\left[\\begin{matrix}1 & 1 & 0 & 0\\\\1 & 1 & 1 & 0\\\\0 & 1 & 1 & 1\\\\0 & 0 & 1 & 1\\end{matrix}\\right]$$\n\n\n\n\n```python\nA.det()\n```\n\n\n\n\n$$-1$$\n\n\n\n* Continuing on this path of tridiagonal matrices we have\n$$ \\left| { A }_{ n } \\right| =\\left| { A }_{ n-1 } \\right| -\\left| { A }_{ n-2 } \\right| $$\n\n* We would thus have\n$$ \\left| { A }_{ 5 } \\right| =\\left| { A }_{ 4 } \\right| -\\left| { A }_{ 3 } \\right| \\\\ \\left| { A }_{ 5 } \\right| =-1-\\left( -1 \\right) =0 \\\\ \\left| { A }_{ 6 } \\right| =\\left| { A }_{ 5 } \\right| -\\left| { A }_{ 4 } \\right| \\\\ \\left| { A }_{ 6 } \\right| =0-\\left( -1 \\right) =1 $$\n* We note that A7 starts the sequence all over again\n* Tridiagonal matrices have determinants of period 6\n\n## Example problems\n\n### Example problem 1\n\n* Calculate the determinant of the following matrix\n\n\n```python\nA = Matrix([[x, y, 0, 0, 0,], [0, x, y ,0 ,0 ], [0, 0, x, y, 0], [0, 0, 0, x, y], [y, 0, 0, 0, x]])\nA\n```\n\n\n\n\n$$\\left[\\begin{matrix}x & y & 0 & 0 & 0\\\\0 & x & y & 0 & 0\\\\0 & 0 & x & y & 0\\\\0 & 0 & 0 & x & y\\\\y & 0 & 0 & 0 & x\\end{matrix}\\right]$$\n\n\n\n\n```python\nA.det()\n```\n\n\n\n\n$$x^{5} + y^{5}$$\n\n\n\n#### Solution\n\n* Note how first selecting row 1's *x* and the *y* leaves triangular matrices in the remaining (*n*-1)×(*n*-1) matrix\n* These form cofactors and their determinant are simply the product of the entries along the main diagonal\n* We simply have to remember the sign rule, which well be (-1)(5+1)\n$$ \\left| { A } \\right| =x\\left( { x }^{ 4 } \\right) +y\\left( { y }^{ 4 } \\right) ={ x }^{ 5 }+{ y }^{ 5 } $$\n\n### Example problem 2\n\n\n```python\nA = Matrix([[x, y, y, y, y], [y, x, y, y, y], [y, y, x, y, y], [y, y, y, x, y], [y, y, y, y, x]])\nA\n```\n\n\n\n\n$$\\left[\\begin{matrix}x & y & y & y & y\\\\y & x & y & y & y\\\\y & y & x & y & y\\\\y & y & y & x & y\\\\y & y & y & y & x\\end{matrix}\\right]$$\n\n\n\n#### Solution\n\n\n```python\nA.det()\n```\n\n\n\n\n$$x^{5} - 10 x^{3} y^{2} + 20 x^{2} y^{3} - 15 x y^{4} + 4 y^{5}$$\n\n\n\n\n```python\n(A.det()).factor()\n```\n\n\n\n\n$$\\left(x - y\\right)^{4} \\left(x + 4 y\\right)$$\n\n\n\n* Note that we can introduce many zero entry by the elementary row operation of subtracting one row from another\n* Let's subtract row 4 from row 5\n$$ \\begin{bmatrix} x & y & y & y & y \\\\ y & x & y & y & y \\\\ y & y & x & y & y \\\\ y & y & y & x & y \\\\ 0 & 0 & 0 & y-x & x - y \\end{bmatrix} $$\n\n* Now subtract row 3 from 4\n$$ \\begin{bmatrix} x & y & y & y & y \\\\ y & x & y & y & y \\\\ y & y & x & y & y \\\\ 0 & 0 & y-x & x-y & 0 \\\\ 0 & 0 & 0 & y-x & x - y \\end{bmatrix} $$\n\n* Subtract 2 from 3\n$$ \\begin{bmatrix} x & y & y & y & y \\\\ y & x & y & y & y \\\\ 0 & y-x & x-y & 0 & 0 \\\\ 0 & 0 & y-x & x-y & 0 \\\\ 0 & 0 & 0 & y-x & x - y \\end{bmatrix} $$\n* ... and 1 from 2\n$$ \\begin{bmatrix} x & y & y & y & y \\\\ y-x & x-y & 0 & 0 & 0 \\\\ 0 & y-x & x-y & 0 & 0 \\\\ 0 & 0 & y-x & x-y & 0 \\\\ 0 & 0 & 0 & y-x & x - y \\end{bmatrix} $$\n\n* Now consider some column operations, adding the 5th column to the fourth column and then 4th to 3rd etc...\n* This will introduce new non-zero entries, though\n* These can be changed back to a zero by adding the 5/th column and the 4th to the 3rd\n* Then columns 5, 4, 3 to 2, etc...\n$$ \\begin{bmatrix} x+4y & 4y & 3y & 2y & y \\\\ 0 & x-y & 0 & 0 & 0 \\\\ 0 & 0 & x-y & 0 & 0 \\\\ 0 & 0 & & x-y & 0 \\\\ 0 & 0 & 0 & 0 & x - y \\end{bmatrix} $$\n\n* This is upper triangular and the determinant is the product of the entries on the main diagonal\n\n\n```python\n(x + 4 * y) * (x - y) ** 4 \n```\n\n\n\n\n$$\\left(x - y\\right)^{4} \\left(x + 4 y\\right)$$\n\n\n\n\n```python\n((x + 4 * y) * (x - y) ** 4).expand()\n```\n\n\n\n\n$$x^{5} - 10 x^{3} y^{2} + 20 x^{2} y^{3} - 15 x y^{4} + 4 y^{5}$$\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "9ec971c987187e2ef91c3aa7796cd4586aaf833a", "size": 27431, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "forks/MIT_OCW_Linear_Algebra_18_06-master/II_06_Determinant_formulas_and_cofactors.ipynb", "max_stars_repo_name": "solomonxie/jupyter-notebooks", "max_stars_repo_head_hexsha": "65999f179e037242138de72f512dda4bf00c7379", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-02-13T05:52:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T09:52:35.000Z", "max_issues_repo_path": "forks/MIT_OCW_Linear_Algebra_18_06-master/II_06_Determinant_formulas_and_cofactors.ipynb", "max_issues_repo_name": "solomonxie/jupyter-notebooks", "max_issues_repo_head_hexsha": "65999f179e037242138de72f512dda4bf00c7379", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "forks/MIT_OCW_Linear_Algebra_18_06-master/II_06_Determinant_formulas_and_cofactors.ipynb", "max_forks_repo_name": "solomonxie/jupyter-notebooks", "max_forks_repo_head_hexsha": "65999f179e037242138de72f512dda4bf00c7379", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1343589744, "max_line_length": 1045, "alphanum_fraction": 0.4485800736, "converted": true, "num_tokens": 5344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.208657770435324}} {"text": "Osnabrück University - Computer Vision (Winter Term 2020/21) - Prof. Dr.-Ing. G. Heidemann, Ulf Krumnack, Axel Schaffland\n\n# Exercise Sheet 03: Morphological Operations¶\n\n## Introduction\n\nThis week's sheet should be solved and handed in before the end of **Saturday, November 21, 2020**. If you need help (and Google and other resources were not enough), feel free to contact your groups' designated tutor or whomever of us you run into first. Please upload your results to your group's Stud.IP folder.\n\n## Assignment 0: Math recap (complex numbers) [0 Points]\n\nThis exercise is supposed to be very easy, does not give any points, and is voluntary. There will be a similar exercise on every sheet. It is intended to revise some basic mathematical notions that are assumed throughout this class and to allow you to check if you are comfortable with them. Usually you should have no problem to answer these questions offhand, but if you feel unsure, this is a good time to look them up again. You are always welcome to discuss questions with the tutors or in the practice session. Also, if you have a (math) topic you would like to recap, please let us know.\n\n**a)** What is a *complex number*, what is the *complex plane*, how are complex numbers usually denoted?\n\nYOUR ANSWER HERE\n\n**b)** What is the *real* and the *imaginary* part of a complex number? What is the *absolute value* of a complex number? What is the *complex conjugate*?\n\nYOUR ANSWER HERE\n\n**c)** What are polar coordinates? What are their advantages? Can you convert between cartesian and polar coordinates? Can you write down $i=\\sqrt{-1}$ in polar coordinates? What about $\\sqrt{i}$?\n\nYOUR ANSWER HERE\n\n**d)** Python, and also numpy, support calculations with complex numbers. Consult the documentation to find out details. Notice that $i$ is substituted by $j$ in Python.\n\n\n```python\n# YOUR CODE HERE\n```\n\n## Assignment 1: Properties of morphological operators [5 Points]\n\nThis exercise will elaborate on the basic morphological operators of *erosion* and *dilation* (cf. CV-05 slides 4-14).\n\n### a) Duality\n\nProof that *erosion* and *dilation* are *dual* operators, i.e.\n\n$ g^{\\ast}\\oplus S = (g\\ominus S)^{\\ast}\\qquad\\text{and}\\qquad\ng^{\\ast}\\ominus S = (g\\oplus S)^{\\ast}$\n\nhere $g^{\\ast}$ denotes the inverted binary image, i.e. $g^{\\ast}(x,y) = 1 - g(x,y) = \\neg g(x,y)$, i.e. 1-pixel become 0 and 0-pixel become 1.\n\n$(g^{\\ast}\\oplus S)(x, y) = \\bigvee_{k \\in [-m, m]} \\bigvee_{l \\in [-n, n]} S(k+m, l+n) \\land g^*(x+k, y+l)$ \n$\\quad\\quad\\quad\\quad\\quad\\quad = \\bigvee_{k \\in [-m, m]} \\bigvee_{l \\in [-n, n]} S(k+m, l+n) \\land \\lnot g(x+k, y+l)$ \n$\\quad\\quad\\quad\\quad\\quad\\quad = \\bigvee_{k \\in [-m, m]} \\bigvee_{l \\in [-n, n]} \\lnot (\\lnot S(k+m, l+n) \\lor g(x+k, y+l)$ \n$\\quad\\quad\\quad\\quad\\quad\\quad = \\lnot \\bigwedge_{k \\in [-m, m]} \\bigwedge_{l \\in [-n, n]} (\\lnot S(k+m, l+n) \\lor g(x+k, y+l)$ \n$\\quad\\quad\\quad\\quad\\quad\\quad = \\lnot \\bigwedge_{k \\in [-m, m]} \\bigwedge_{l \\in [-n, n]} (S(k+m, l+n) \\rightarrow g(x+k, y+l)$ \n$\\quad\\quad\\quad\\quad\\quad\\quad = \\lnot (g\\ominus S)(x, y)$ \n$\\quad\\quad\\quad\\quad\\quad\\quad = (g\\ominus S)^{\\ast}(x, y)$ \n\n$(g^{\\ast}\\ominus S)(x, y) = \\bigwedge_{k \\in [-m, m]} \\bigwedge_{l \\in [-n, n]} (S(k+m, l+n) \\rightarrow g^*(x+k, y+l))$ \n$\\quad\\quad\\quad\\quad\\quad\\quad = \\bigwedge_{k \\in [-m, m]} \\bigwedge_{l \\in [-n, n]} (S(k+m, l+n) \\rightarrow \\lnot g(x+k, y+l))$ \n$\\quad\\quad\\quad\\quad\\quad\\quad = \\bigwedge_{k \\in [-m, m]} \\bigwedge_{l \\in [-n, n]} (\\lnot S(k+m, l+n) \\lor \\lnot g(x+k, y+l))$ \n$\\quad\\quad\\quad\\quad\\quad\\quad = \\bigwedge_{k \\in [-m, m]} \\bigwedge_{l \\in [-n, n]} \\lnot(S(k+m, l+n) \\land g(x+k, y+l))$ \n$\\quad\\quad\\quad\\quad\\quad\\quad = \\lnot \\bigvee_{k \\in [-m, m]} \\bigvee_{l \\in [-n, n]} (S(k+m, l+n) \\land g(x+k, y+l))$ \n$\\quad\\quad\\quad\\quad\\quad\\quad = \\lnot (g\\oplus S)(x, y)$ \n$\\quad\\quad\\quad\\quad\\quad\\quad = (g\\oplus S)^{\\ast}(x, y)$ \n\n### b) Superposition\n\nAs *erosion* and *dilation* have been introduced for binary images, the notion of *linearity* is not really appropriate here. However, some weaker version, called *superposition* can be defined: instead of forming linear combination, one takes the logical disjunction:\n\n$$(g_1\\lor g_2)(x,y) := g_1(x,y)\\lor g_2(x,y)$$\n\nCheck for both operations if *erosion* and *dilation* are \"compatible\" with superposition, i.e. if first *eroding* (or *dilating*) two images and superposing the result is the same as first superposing the images and then *eroding* (or *dilating*) the result.\n\n**Dilation** \n\n$((g_1 \\lor g_2) \\oplus S)(x, y) = \\bigvee_{k \\in [-m, m]} \\bigvee_{l \\in [-n, n]} S(k+m, l+n) \\land (g_1 \\lor g_2)(x+k, y+l)$ \n$\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad = \\bigvee_{k \\in [-m, m]} \\bigvee_{l \\in [-n, n]} S(k+m, l+n) \\land (g_1(x+k, y+l) \\lor g_2(x+k, y+l))$ \n$\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad = (\\bigvee_{k \\in [-m, m]} \\bigvee_{l \\in [-n, n]} S(k+m, l+n) \\land g_1(x+k, y+l)) \\lor (\\bigvee_{k \\in [-m, m]} \\bigvee_{l \\in [-n, n]} S(k+m, l+n) \\land g_2(x+k, y+l))$ \n$\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad = (g_1 \\oplus S)(x, y) \\lor (g_2 \\oplus S)(x, y)$\n\n$\\rightarrow$ dilation is compatible with superposition \n\n**Erosion** \n\n$((g_1 \\lor g_2) \\ominus S)(x, y) = \\bigwedge_{k \\in [-m, m]} \\bigwedge_{l \\in [-n, n]} S(k+m, l+n) \\rightarrow (g_1 \\lor g_2)(x+k, y+l)$ \n$\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad = \\bigwedge_{k \\in [-m, m]} \\bigwedge_{l \\in [-n, n]} S(k+m, l+n) \\rightarrow (g_1(x+k, y+l) \\lor g_2(x+k, y+l))$ \n$\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad = \\bigwedge_{k \\in [-m, m]} \\bigwedge_{l \\in [-n, n]} \\lnot S(k+m, l+n) \\lor g_1(x+k, y+l) \\lor g_2(x+k, y+l)$ \n$\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad \\neq (\\bigwedge_{k \\in [-m, m]} \\bigwedge_{l \\in [-n, n]} \\lnot S(k+m, l+n) \\lor g_1(x+k, y+l)) \\lor (\\bigwedge_{k \\in [-m, m]} \\bigwedge_{l \\in [-n, n]} \\lnot S(k+m, l+n) \\lor g_2(x+k, y+l))$ \n\n### c) Chaining\n\nShow that *dilation* and *erosion* have the following properties: given two structering elements $S_1$ and $S_2$, it holds\n\n\\begin{align}\n (g\\oplus S_1)\\oplus S_2 & & = & g\\oplus (S_1\\oplus S_2) && = (g\\oplus S_2)\\oplus S_1 \\\\\n (g\\ominus S_1)\\ominus S_2 & & = & g\\ominus (S_1\\ominus S_2) && = (g\\ominus S_2)\\ominus S_1 \\\\ \n\\end{align}\n\nWhat are the practical consequences?\n\n**Dilation** \n\n$((g \\oplus S_1) \\oplus S_2)(x, y) = \\bigvee_{k \\in [-m_2, m_2]} \\bigvee_{l \\in [-n_2, n_2]} S_2(k+m_2, l+n_2) \\land (g \\oplus S_1)(x+k, y+l)$ \n$\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad = \\bigvee_{k \\in [-m_2, m_2]} \\bigvee_{l \\in [-n_2, n_2]} S_2(k+m_2, l+n_2) \\land (\\bigvee_{i \\in [-m_1, m_1]} \\bigvee_{j \\in [-n_1, n_1]} S_1(i+m_1, j+n_1) \\land g(x+i+k, y+j+l))$ \n$\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad = \\bigvee_{i \\in [-m_1, m_1]} \\bigvee_{j \\in [-n_1, n_1]} \\bigvee_{k \\in [-m_2, m_2]} \\bigvee_{l \\in [-n_2, n_2]} S_1(i+m_1, j+n_1) \\land S_2(k+m_2, l+n_2) \\land g(x+i+k, y+j+l)$ \n$\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad = ((g\\oplus S_2)\\oplus S_1)(x,y)$ \n\n$\\rightarrow$ the order doesn't matter \n\n$g\\oplus (S_1\\oplus S_2)$ holds as well, we're just changing the order in which the indices are added and addition is commutative.\n\n**Erosion** \n\nThe proof for the erosion operation works basically the same (cf. task 1a).\n\n## Assignment 2: Application [5 Points]\n\n\n### a) Boundary extraction\n\nExtract the boundary of a shape using opening or closing. You may use `binary_dilation` or `binary_erosion` from `scipy.ndimage.morphology`. Can you achieve a thicker boundary?\n\n\n```python\n%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nplt.rcParams['image.cmap'] = 'gray'\nimport scipy.ndimage.morphology as morph\nfrom imageio import imread\n\ndef my_boundary(img, structuring_elem=[]):\n \"\"\"\n Compute boundary of binary image.\n\n Parameters\n ----------\n img : ndarray of bools\n A binary image.\n structuring_elem: array_like, optional\n Structuring element used for the erosion.\n \n Returns\n -------\n boundary : ndarray of bools\n The boundary as a binary image.\n \"\"\"\n \n boundary = np.zeros(img.shape,np.bool)\n # YOUR CODE HERE\n if len(structuring_elem) > 0:\n erosion = morph.binary_erosion(img, structuring_elem)\n else:\n erosion = morph.binary_erosion(img)\n boundary = np.logical_xor(erosion, img)\n \n return boundary\n \nfig = plt.figure(figsize=(15,7))\n\nimg = imread(\"images/engelstrompete.png\") > 0\n\nfig.add_subplot(1,3,1)\nplt.imshow(img, cmap = 'gray')\nplt.title('image')\n\nfig.add_subplot(1,3,2)\nplt.imshow(my_boundary(img), cmap = 'gray')\nplt.title('boundary')\n\nfig.add_subplot(1,3,3)\n# larger structuring element\nplt.imshow(my_boundary(img, np.ones((10, 10))), cmap = 'gray')\nplt.title('thicker boundary')\n\nplt.show()\n```\n\n### b) Distance transform\n\nImplement distance transform according to the ideas of (CV-05 slides 34ff). Discuss the effect of different structuring elements.\n\n\n```python\n%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.ndimage import morphology as morph, generate_binary_structure\nfrom imageio import imread\n\ndef my_distance_transform(img):\n \"\"\"Distance transform of binary image.\n\n Args:\n img (ndarray of bools): A binary image.\n \n Returns:\n dt (ndarray of ints): The distance transform of the input image.\n \"\"\"\n \n dt = np.zeros(img.shape,np.int32)\n # YOUR CODE HERE\n lvl = 1\n # erode until nothing is left\n while np.any(img):\n boundary = my_boundary(img)\n # pixels with manhattan distance lvl to the boundary\n dt[boundary] = lvl\n # object without boundary\n img = morph.binary_erosion(img)\n lvl += 1\n\n return dt\n\nimg = imread(\"images/engelstrompete.png\") > 0\nfig = plt.figure(figsize=(10,10))\n\nfig.add_subplot(1,2,1)\nplt.imshow(img, cmap = 'gray')\nplt.title('image')\n\nfig.add_subplot(1,2,2)\nplt.imshow(my_distance_transform(img) + 50 * img)\nplt.title('distance transform')\n\nplt.show()\n```\n\nDifferent structuring elements implement different metrics, e.g.:\n- manhattan distance\n- chessboard distance\n\n### c) Morphing\n\nWrite a function `my_morph` that implements morphing according to (CV-05 slide 41). You may use your function `my_distance_transform` from part b), or the function `distance_transform_edt` from `scipy.ndimage.morphology`.\n\n\n```python\n%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.ndimage.morphology as morph\nfrom imageio import imread\n\n\ndef my_morph(A,B,ratio):\n \"\"\"Morphing from binary image A to image B.\n\n Args:\n A (ndarray of bools): A binary image (start).\n B (ndarray of bools): A binary image (target), same shape as A.\n ratio (float from 0.0 to 1.0): The ratio of image A and image B.\n 0.0=only image A, 1.0=only image B.\n \n Returns:\n morph (ndarray of bools): A binary intermediate image between A and B.\n \n \"\"\"\n\n result = np.zeros(A.shape,np.bool)\n # YOUR CODE HERE\n D_a = my_distance_transform(A) - my_distance_transform(np.invert(A))\n D_b = my_distance_transform(B) - my_distance_transform(np.invert(B))\n result = (ratio * D_b + (1 - ratio) * D_a)\n # element-wise applied\n return result > 0\n\nimg1 = imread(\"images/kreis.png\") > 0\nimg2 = imread(\"images/engelstrompete.png\") > 0\n\nplt.gray()\nplt.figure(figsize=(10,10))\nfor i, ratio in enumerate(np.linspace(0, 1, 6), 1):\n plt.subplot(2, 3, i)\n plt.imshow(my_morph(img1, img2, ratio))\n plt.title('ratio:' + str(round(ratio, 2)))\n plt.axis('off')\nplt.show()\n```\n\n\n```python\n# If you want to see your morph as an animation, run this cell. \n# Close the output (press the blue \"Stop interaction\" button) once you are done!\n\n# Due to some matplotlib problem you may have to restart your kernel!\n%matplotlib inline\nimport matplotlib.animation as animation\nfig = plt.figure()\n\nims = []\nfor i, ratio in enumerate(np.linspace(0, 1, 24), 1):\n plt.axis('off')\n im = plt.imshow(my_morph(img1, img2, ratio), cmap='gray', animated=True)\n ims.append([im]) \n \nani = animation.ArtistAnimation(fig, ims + list(reversed(ims)), interval=100, blit=True)\n\nplt.show()\n```\n\n## Assignment 3: Implementation: Skeletonization [5 Points]\n\n### a) Skeletonization with hit-or-miss\n\nExplain in your own words, how the hit-or-miss operator can be used for skeletonization (cf CV-05 slide 49). \n\nIf we want to extract a particular kind of pattern from an image, we can use the hit-or-miss operation. \nSo, if we know exactly what we are looking for, this is highly efficient.\n3 steps:\n- **hit:** find candidate locations (where the pattern might be in the image) \n - removes everything that is too small by erosion (what remains are candidates)\n- **miss:** removes everything that is too large\n- **intersection:** intersect the two previous results\n\nNow we can combine distance transform and hit-or-miss to do skeletonization. \nA skeleton provides a meaningful and concise description of a binary shape, e.g. for classification. \nTo compute the skeleton of some binary segment, we would have to find all the bi-tangent circles. We can get this quite easily using the \ndistance transform. \nThe ridges are already the skeleton, we just need to find the ridges using the hit-or-miss operation. \n\nThe shape of the ridges is a priori unknown. We'd just remove iteratively all pixels from the distance transform where we know that they are not ridges. This can be done using the $8$ operators (left, right, up, down, and the four diagonals) which are designed to detect structures that stay connected after removing the central pixel. \n\nThose operators are applied iteratively until only the skeleton remains.\n\n### b) Implementation of skeletonization\n\nNow use this method to implement your own skeletonization function. It is ok to use\n`scipy.ndimage.morphology.binary_hit_or_miss` here (but of course *not* `skimage.morphology.skeletonize` or similar functions). Compare your result with (CV-05 slide 50). Note that computing the skeleton using this method may take some time ...\n\n\n```python\n%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.ndimage.morphology as morph\nfrom imageio import imread\n\ndef my_skeletonize(img):\n \"\"\"\n Compute the skeleton of a binary image using hit_or_miss operator.\n \n Parameters\n ----------\n img : ndarray of bools\n Binary image to be skeletonized.\n \n Returns\n -------\n skeleton : ndarray of bools\n The skeleton of the input image.\n \"\"\"\n # YOUR CODE HERE\n\n # based on 2 ideas:\n # - ridges of the distance transform are the skeleton\n # - find ridges using the hit-or-miss operation\n\n # 'X' is always 0 and the other elements are inverted for this miss structuring elements\n\n # hit structuring elements\n l = np.array([[0,0,1], [0,1,1], [0,0,1]])\n r = np.array([[1,0,0], [1,1,0], [1,0,0]])\n o = np.array([[0,0,0], [0,1,0], [1,1,1]]) \n u = np.array([[1,1,1], [0,1,0], [0,0,0]])\n lu = np.array([[0,1,1], [0,1,1], [0,0,0]])\n lo = np.array([[0,0,0], [0,1,1], [0,1,1]])\n ru = np.array([[1,1,0], [1,1,0], [0,0,0]])\n ro = np.array([[0,0,0], [1,1,0], [1,1,0]])\n \n # miss structuring elements\n l_m = np.array([[1,0,0], [1,0,0], [1,0,0]])\n r_m = np.array([[0,0,1], [0,0,1], [0,0,1]])\n o_m = np.array([[1,1,1], [0,0,0], [0,0,0]]) \n u_m = np.array([[0,0,0], [0,0,0], [1,1,1]])\n lu_m = np.array([[0,0,0], [1,0,0], [1,1,0]])\n lo_m = np.array([[1,1,0], [1,0,0], [0,0,0]])\n ru_m = np.array([[0,0,0], [0,0,1], [0,1,1]])\n ro_m = np.array([[0,1,1], [0,0,1], [0,0,0]])\n\n hit_structs = [l, r, o, u, lu, lo, ru, ro]\n miss_structs = [l_m, r_m, o_m, u_m, lu_m, lo_m, ru_m, ro_m]\n\n distance_transform = my_distance_transform(img)\n skeleton = img.copy()\n prev = np.zeros(skeleton.shape)\n\n while not(np.array_equal(skeleton, prev)):\n prev = skeleton.copy()\n for hit, miss in zip(hit_structs, miss_structs):\n hit_or_miss_transform = morph.binary_hit_or_miss(distance_transform, structure1=hit, structure2=miss)\n skeleton[hit_or_miss_transform] = 0\n distance_transform[hit_or_miss_transform] = 0\n\n return skeleton\n\nimg = imread(\"images/engelstrompete.png\") > 0\nskel = my_skeletonize(img)\nresult = morph.distance_transform_cdt(img, metric='taxicab') + (50 * img)\nresult[morph.binary_dilation(skel)] = 0\nplt.figure(figsize=(10,10))\nplt.gray()\nplt.imshow(result)\nplt.show()\n```\n\n## Assignment 4: Custom Structuring Element [5 points]\n\nLandsat 7 is a satelite mission for acquisition of satellite imagery of Earth. Unfortunately the Scan Line Corrector failed, resulting in black stripes on the aquired images. More information: https://landsat.usgs.gov/slc-products-background\n\n\n### a) A first fix\n\nA rather crude fix is to apply a custom structuring element for dilation and erosion (see CV-05, 24ff). Complement the code below (in part (b)) in the following way:\n* Rotate the image such that the gaps are horizontal.\n* Dilate the rotated image with a vertical structuring element. I.e. take the maximum of an area of size $7 \\times1$ and assign it to the center pixel. Repeat for all pixels.\n* Erode the dilated image.\n* Rotate the result back.\n\nRemark: this exercise applies morphological operator to color images. This extends the idea of generalizing morphological operators to gray value images (CV-05, slide 51). \n\n### b) Improving the solution\nYou may get better results by thresholding and applying the morphological operations only to pixels below a threshold, i.e. gap pixels. Compliment your solution from a). \n\n\n```python\n%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.ndimage.morphology as morph\nimport scipy.ndimage as ndimg\nfrom skimage import color\nfrom skimage.transform import rescale as rescale\nfrom skimage.transform import rotate as rotate\nfrom imageio import imread\n\nangle = 15\nthresh = .4\nstruc_elem = np.ones((7,1), dtype=np.bool)\n\nimg = imread(\"images/landsat_stack2.png\")\nimg2 = img.copy()\nimg3 = img.copy()\n\n# YOUR CODE HERE\n# rotate image\nimg2 = rotate(img2, angle, resize=True)\n\n# from [0.0, 1.0] to [0, 255]\nimg2 = (img2 * 255).astype(np.uint8)\n\n# dilation for each color channel\nimg2[:,:,0] = morph.grey_dilation(img2[:,:,0], structure=struc_elem)\nimg2[:,:,1] = morph.grey_dilation(img2[:,:,1], structure=struc_elem)\nimg2[:,:,2] = morph.grey_dilation(img2[:,:,2], structure=struc_elem)\n\n# erosion for each color channel\nimg2[:,:,0] = morph.grey_erosion(img2[:,:,0], structure=struc_elem)\nimg2[:,:,1] = morph.grey_erosion(img2[:,:,1], structure=struc_elem)\nimg2[:,:,2] = morph.grey_erosion(img2[:,:,2], structure=struc_elem)\n\n# rotate back\nimg2 = rotate(img2, -angle, resize=True)\n\n# rotate returns again values from [0.0, 1.0]\n\n# get a copy of the original image that is of the same size as the rotated image\noriginal = img.copy()\noriginal = rotate(original, angle, resize=True)\noriginal = rotate(original, -angle, resize=True)\n\nimg3 = img2.copy()\nfor x in range(original.shape[0]):\n for y in range(original.shape[1]):\n for i in range(3):\n # use original value above threshold\n if original[x][y][i] >= thresh:\n img3[x][y][i] = original[x][y][i]\n\nimg = (img - np.min(img)) / np.ptp(img)\nimg2 = (img2 - np.min(img2)) / np.ptp(img2)\nimg3 = (img3 - np.min(img3)) / np.ptp(img3)\n\nplt.figure(figsize=(30,90))\nplt.subplot(1,3,1); plt.title('original'); plt.imshow(img); plt.axis('off')\nplt.subplot(1,3,2); plt.title('first fix'); plt.imshow(img2); plt.axis('off')\nplt.subplot(1,3,3); plt.title('thresh fix'); plt.imshow(img3); plt.axis('off')\nplt.show()\n\n```\n\n### c) Bonus\nCan you think of other ways to add the missing data? \n\n\n- fill up missing information with information from other satellites\n- use image destriping algorithms (e.g. Fourier filtering)\n", "meta": {"hexsha": "d8741df13224f1b3154bb6d67df208af79dd2fa6", "size": 40131, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "s3/sheet03.ipynb", "max_stars_repo_name": "tbohne/CV2020", "max_stars_repo_head_hexsha": "84a056a28ead6f8e8a40b6540fe13cda56cf0e9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "s3/sheet03.ipynb", "max_issues_repo_name": "tbohne/CV2020", "max_issues_repo_head_hexsha": "84a056a28ead6f8e8a40b6540fe13cda56cf0e9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "s3/sheet03.ipynb", "max_forks_repo_name": "tbohne/CV2020", "max_forks_repo_head_hexsha": "84a056a28ead6f8e8a40b6540fe13cda56cf0e9d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4421988682, "max_line_length": 600, "alphanum_fraction": 0.556851312, "converted": true, "num_tokens": 6266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713670203584295, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2072026263604251}} {"text": "# Just Euler's method\n\n\n```python\nfrom IPython.core.display import HTML\ncss_file = 'https://raw.githubusercontent.com/ngcm/training-public/master/ipython_notebook_styles/ngcmstyle.css'\nHTML(url=css_file)\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n$$\n\\newcommand{\\dt}{\\Delta t}\n\\newcommand{\\udt}[1]{u^{({#1})}(T)}\n\\newcommand{\\Edt}[1]{E^{({#1})}}\n\\newcommand{\\uone}[1]{u_{1}^{({#1})}}\n$$\n\nIn the previous cases we've focused on the *behaviour* of the algorithm: whether it will give the correct answer in the limit, or whether it converges as expected. This is really what you want to do: you're trying to do science, to get an answer, and so implementing the precise algorithm should be secondary. If you are trying to implement a precise algorithm, it should be because of its (expected) behaviour, and so you should be testing for that!\n\nHowever, let's put that aside and see if we can work out how to test whether we've implemented exactly the algorithm we want: Euler's method. Checking convergence alone is not enough: the [Backwards Euler method](http://en.wikipedia.org/wiki/Backward_Euler_method) has identical convergence behaviour, as do whole families of other methods. We need a check that characterizes the method uniquely.\n\nThe *local truncation error* $\\Edt{\\dt}$ would be exactly such a check. This is the error produced by a single step from exact data, eg\n\n$$\n\\begin{equation}\n \\Edt{\\dt} = u_1 - u(\\dt).\n\\end{equation}\n$$\n\nFor Euler's method we have\n\n$$\n\\begin{equation}\n u_{n+1} = u_n + \\dt f(t_n, u_n)\n\\end{equation}\n$$\n\nand so\n\n$$\n\\begin{equation}\n \\Edt{\\dt} = \\left| u_0 + \\dt f(0, u_0) - u(\\dt) \\right| = \\left| \\frac{\\dt^2}{2} \\left. u''\\right|_{t=0} \\right| + {\\cal O}(\\dt^3).\n\\end{equation}\n$$\n\n\nThis is all well and good, but we don't know the exact solution (in principle) at any point other than $t=0$, so cannot compute $u(\\dt)$, so cannot compute $\\Edt{\\dt}$. We only know $\\uone{\\dt}$ for whichever values of $\\dt$ we wish to compute.\n\nWe can use repeated Richardson extrapolation to get the solution $u(\\dt)$ to sufficient accuracy, however. On the *assumption* that the algorithm is first order (we can use the previous techniques to check this), we can use Richardson extrapolation to repeatedly remove the highest order error terms. We can thus find the local truncation errors.\n\n\n```python\nfrom math import sin, cos, log, ceil\nimport numpy\nfrom matplotlib import pyplot\n%matplotlib inline\nfrom matplotlib import rcParams\nrcParams['font.family'] = 'serif'\nrcParams['font.size'] = 16\n```\n\n\n```python\n# model parameters:\ng = 9.8 # gravity in m s^{-2}\nv_t = 30.0 # trim velocity in m s^{-1} \nC_D = 1/40. # drag coefficient --- or D/L if C_L=1\nC_L = 1.0 # for convenience, use C_L = 1\n\n### set initial conditions ###\nv0 = v_t # start at the trim velocity (or add a delta)\ntheta0 = 0.0 # initial angle of trajectory\nx0 = 0.0 # horizotal position is arbitrary\ny0 = 1000.0 # initial altitude\n```\n\n\n```python\ndef f(u):\n \"\"\"Returns the right-hand side of the phugoid system of equations.\n \n Parameters\n ----------\n u : array of float\n array containing the solution at time n.\n \n Returns\n -------\n dudt : array of float\n array containing the RHS given u.\n \"\"\"\n \n v = u[0]\n theta = u[1]\n x = u[2]\n y = u[3]\n return numpy.array([-g*sin(theta) - C_D/C_L*g/v_t**2*v**2,\n -g*cos(theta)/v + g/v_t**2*v,\n v*cos(theta),\n v*sin(theta)])\n```\n\n\n```python\ndef euler_step(u, f, dt):\n \"\"\"Returns the solution at the next time-step using Euler's method.\n \n Parameters\n ----------\n u : array of float\n solution at the previous time-step.\n f : function\n function to compute the right hand-side of the system of equation.\n dt : float\n time-increment.\n \n Returns\n -------\n u_n_plus_1 : array of float\n approximate solution at the next time step.\n \"\"\"\n \n return u + dt * f(u)\n```\n\n\n```python\nT_values = numpy.array([0.001*2**(i) for i in range(10)])\nlte_values = numpy.zeros_like(T_values)\nfor j, T in enumerate(T_values):\n dt_values = numpy.array([T*2**(i-8) for i in range(8)])\n v_values = numpy.zeros_like(dt_values)\n for i, dt in enumerate(dt_values):\n N = int(T/dt)+1\n t = numpy.linspace(0.0, T, N)\n u = numpy.empty((N, 4))\n u[0] = numpy.array([v0, theta0, x0, y0])\n for n in range(N-1):\n u[n+1] = euler_step(u[n], f, dt)\n v_values[i] = u[-1,0]\n v_next = v_values\n for s in range(1, len(v_values-1)):\n v_next = (2**s*v_next[1:]-v_next[0:-1])/(2**s-1)\n lte_values[j] = abs(v_values[0]-v_next)\n```\n\n\n```python\nlte_values\n```\n\n\n\n\n array([ 1.99954897e-09, 8.05573563e-09, 3.26825287e-08,\n 1.34407252e-07, 5.67045063e-07, 2.50349015e-06,\n 1.18961299e-05, 6.26360623e-05, 3.70836832e-04,\n 2.44291651e-03])\n\n\n\nWe now have four values for the local truncation error. We can thus compute the convergence rate of the local truncation error itself (which should be two), and check that it is close enough to the expected value using the previous techniques:\n\n\n```python\ns_m = numpy.zeros(2)\nfor i in range(2):\n s_m[i] = log(abs((lte_values[2+i]-lte_values[1+i])/\n (lte_values[1+i]-lte_values[0+i]))) / log(2.0)\n print(\"Measured convergence rate (base dt {}) is {:.6g} (error is {:.4g}).\".format(\n T_values[i], s_m[i], abs(s_m[i]-2)))\nprint(\"Convergence error has reduced by factor {:.4g}.\".format(\n abs(s_m[0]-2)/abs(s_m[1]-2)))\n```\n\n Measured convergence rate (base dt 0.001) is 2.02375 (error is 0.02375).\n Measured convergence rate (base dt 0.002) is 2.04637 (error is 0.04637).\n Convergence error has reduced by factor 0.5121.\n\n\nSo the error has gone down considerably, and certainly $0.51 < 2/3$, so the convergence rate of the local truncation error is close enough to 2.\n\nHowever, that alone isn't enough to determine that this really is Euler's method: as noted above, the convergence rate of the local truncation error isn't the key point: the key point is that we can predict its *actual value* as\n\n$$\n\\begin{equation}\n \\Edt{\\dt} = \\frac{\\dt^2}{2} \\left| \\left. u''\\right|_{t=0} \\right| + {\\cal O}(\\dt^3) = \\frac{\\dt^2}{2} \\left| \\left( \\left. \\frac{\\partial f}{\\partial t} \\right|_{t=0} + f(0, u_0) \\left. \\frac{\\partial f}{\\partial u} \\right|_{t=0, u=u_0} \\right) \\right|.\n\\end{equation}\n$$\n\nFor the specific problem considered here we have\n\n$$\n\\begin{equation}\n u = \\begin{pmatrix} v \\\\ \\theta \\\\ x \\\\ y \\end{pmatrix}, \\quad f = \\begin{pmatrix} -g\\sin \\theta - \\frac{C_D}{C_L} \\frac{g}{v_t^2} v^2 \\\\ -\\frac{g}{v}\\cos \\theta + \\frac{g}{v_t^2} v \\\\ v \\cos \\theta \\\\ v \\sin \\theta \\end{pmatrix}.\n\\end{equation}\n$$\n\nWe note that $f$ does not explicitly depend on $t$ (so $\\partial f / \\partial t \\equiv 0$), and that the values of the parameters $g, C_D, C_L$ and $v_t$ are given above, along with the initial data $u_0 = (v_0, \\theta_0, x_0, y_0)$.\n\nSo, let's find what the local truncation error should be.\n\n\n```python\nimport sympy\nsympy.init_printing()\nv, theta, x, y, g, CD, CL, vt, dt = sympy.symbols('v, theta, x, y, g, C_D, C_L, v_t, {\\Delta}t')\nu = sympy.Matrix([v, theta, x, y])\nf = sympy.Matrix([-g*sympy.sin(theta)-CD/CL*g/vt**2*v**2, \n -g/v*sympy.cos(theta)+g/vt**2*v, \n v*sympy.cos(theta), \n v*sympy.sin(theta)])\ndfdu = f.jacobian(u)\nlte=dt**2/2*dfdu*f\n```\n\n\n```python\nlte_0=lte.subs([(g,9.8),(vt,30.0),(CD,1.0/40.0),(CL,1.0),(v,30.0),(theta,0.0),(x,0.0),(y,1000.0)])\nlte_0\n```\n\nSo let us check the local truncation error values, which are computed for `v`:\n\n\n```python\nlte_exact = float(lte_0[0]/dt**2)\nlte_values/T_values**2\n```\n\n\n\n\n array([ 0.00199955, 0.00201393, 0.00204266, 0.00210011, 0.00221502,\n 0.00244481, 0.00290433, 0.003823 , 0.00565852, 0.00931899])\n\n\n\nThese are indeed converging towards $0.002 \\dt^2$ as they should. To check this quantitatively, we use that our model is\n\n$$\n\\begin{equation}\n \\Edt{\\dt} = \\alpha \\dt^2 + {\\cal O}(\\dt^3),\n\\end{equation}\n$$\n\nwith the exact value $\\alpha_e \\simeq 0.002$. So we can use our usual Richardson extrapolation methods applied to $\\Edt{\\dt}/\\dt^2$, to get a measured value for $\\alpha$ with an error interval:\n\n$$\n\\begin{equation}\n \\alpha_m = \\frac{8\\Edt{\\dt} - \\Edt{2\\dt} \\pm \\left| \\Edt{\\dt} - \\Edt{2\\dt} \\right|}{4\\dt^2}.\n\\end{equation}\n$$\n\n\n```python\nfor i in range(len(lte_values)-1):\n Edt = lte_values[i]\n E2dt = lte_values[i+1]\n dt = T_values[i]\n err1 = abs(Edt - E2dt)\n a_lo = (8.0*Edt - E2dt - err1)/(4.0*dt**2)\n a_hi = (8.0*Edt - E2dt + err1)/(4.0*dt**2)\n print(\"Base dt={:.4g}: the measured alpha is in [{:.5g}, {:.5g}]\".format(\n dt, a_lo, a_hi))\n print(\"Does this contain the exact value? {}\".format(\n a_lo <= lte_exact <= a_hi))\n```\n\n Base dt=0.001: the measured alpha is in [0.00047112, 0.0034992]\n Does this contain the exact value? True\n Base dt=0.002: the measured alpha is in [0.00044604, 0.0035244]\n Does this contain the exact value? True\n Base dt=0.004: the measured alpha is in [0.00039575, 0.0035747]\n Does this contain the exact value? True\n Base dt=0.008: the measured alpha is in [0.00029522, 0.0036752]\n Does this contain the exact value? True\n Base dt=0.016: the measured alpha is in [9.4165e-05, 0.0038763]\n Does this contain the exact value? True\n Base dt=0.032: the measured alpha is in [-0.00030782, 0.0042784]\n Does this contain the exact value? True\n Base dt=0.064: the measured alpha is in [-0.0011113, 0.0050826]\n Does this contain the exact value? True\n Base dt=0.128: the measured alpha is in [-0.0027153, 0.0066903]\n Does this contain the exact value? True\n Base dt=0.256: the measured alpha is in [-0.0059063, 0.0099024]\n Does this contain the exact value? True\n\n\nSo, to the limits that we can measure the local truncation error, we have implemented Euler's method.\n", "meta": {"hexsha": "10227083088ac0c7dc07d9bc4052090f2ebdc8da", "size": 25578, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "03-Close-Enough-Just-Euler.ipynb", "max_stars_repo_name": "IanHawke/close-enough-balloons", "max_stars_repo_head_hexsha": "6b7c27d90e8c012b1f95c2daa4ff2e84849a2c52", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-03-10T23:49:33.000Z", "max_stars_repo_stars_event_max_datetime": "2016-06-01T23:53:24.000Z", "max_issues_repo_path": "03-Close-Enough-Just-Euler.ipynb", "max_issues_repo_name": "IanHawke/close-enough-balloons", "max_issues_repo_head_hexsha": "6b7c27d90e8c012b1f95c2daa4ff2e84849a2c52", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "03-Close-Enough-Just-Euler.ipynb", "max_forks_repo_name": "IanHawke/close-enough-balloons", "max_forks_repo_head_hexsha": "6b7c27d90e8c012b1f95c2daa4ff2e84849a2c52", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.015918958, "max_line_length": 461, "alphanum_fraction": 0.5455078583, "converted": true, "num_tokens": 4188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. YES", "lm_q1_score": 0.34510527095787247, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.20712816634825396}} {"text": "\n# PHY321: Classical Mechanics 1\n\n \n**Solution Homework 9, due Monday April 5**\n\nDate: **Apr 11, 2021**\n\n### Introduction to homework 9\n\nThis week's exercises focus on solving\ntwo-body problems with central forces. It is based on what you did in hw7 and hw8, see also their respective solutions.\n\n### Exercise 1: Attractive Potential (10pt)\n\nConsider a particle in an attractive potential\n\n$$\nU(r)=-\\alpha/r.\n$$\n\nThe quantity $r$ is the absolute value of the relative position. We\nwill use the reduced mass $\\mu$ and the angular momentum $L$, as\ndiscussed during the lectures. With the transformation of a two-body\nproblem to the center-of-mass frame, the actual equations look like an\n*effective* one-body problem. The energy of the system is $E$ and the\nminimum of the effective potential is $r_{\\rm min}$.\n\n\nThe analytical solution to the radial equation of motion is\n\n$$\nr(\\phi) = \\frac{1}{\\frac{\\mu\\alpha}{L^2}+A\\cos{(\\phi)}}.\n$$\n\nFind the value of $A$. Hint: Use the fact that at $r_{\\rm min}$\nthere is no radial kinetic energy and $E=-\\alpha/r_{\\rm min}+L^2/2mr_{\\rm min}^2$.\n\nAt $r_{\\mathrm{min}}$ and $r_{\\mathrm{max}}$ , all the kinetic energy is stored in the velocity in the direction perpendicular to $r$ since the radial velocity is set to zero . We can calculate using angular momentum and from there, find 𝐴 in terms of the energy $E$ which is constant. But first, we need to find $r_{\\mathrm{min}}$ from the conservation of energy (noting that the radial velocity $\\ddot{r}$ at the mininum is zero):\n\n$$\nE = U(r) + \\frac{1}{2} \\mu(\\ddot{r}^2 + (r\\ddot{\\phi})^2)\n\\\\\nE = \\frac{-\\alpha}{r_{\\min}} + \\frac{1}{2} \\mu\\left( \\frac{L}{\\mu r_{\\min}}\\right) ^2\n\\\\\nE r_{\\min}^2 - \\frac{1}{2}\\mu\\left( \\frac{L}{\\mu}\\right) ^2 + \\alpha r_{\\min} = 0\n\\\\\nr_{\\min}^2 + \\frac{\\alpha}{E} r_{\\min} - \\frac{L^2}{2E\\mu} = 0\n\\\\\nr_{\\min} = - \\frac{\\alpha}{2E} \\pm \\frac{1}{2} \\sqrt{\\frac{\\alpha^2}{E^2} + 2\\frac{L^2}{E\\mu}}\n$$\n\nSince we're looking for the minimum, the ± sign must be negative (then 𝑟min will not be negative since 𝐸<0 ). Therefore, we have\n\n$$\n\\frac{1}{\\frac{\\mu\\alpha}{L^2}+A} = -\\frac{\\alpha}{2E} - \\frac{1}{2} \\sqrt{\\frac{\\alpha^2}{E^2} + 2\\frac{L^2}{E\\mu}}\n\\\\\nA = - \\frac{\\mu\\alpha}{L^2} - \\frac{2E}{\\alpha + \\sqrt{\\alpha^2 + 2\\frac{L^2E}{\\mu}}}\n$$\n\n### Exercise 2 (20pt) Inverse-square force\n\nConsider again the same effective potential as in exercise 1. This leads to an attractive inverse-square-law force, $F=-\\alpha/r^2$. Consider a particle of mass $m$ with angular momentum $L$. Taylor sections 8.4-8.7 are relevant background material. See also the harmonic oscillator potential from hw8. The equation of motion for the radial degrees of freedom is (see also hw8) in the center-of-mass frame in two dimensions with $x=r\\cos{(\\phi)}$ and $y=r\\sin{(\\phi)}$ and\n$r\\in [0,\\infty)$, $\\phi\\in [0,2\\pi]$ and $r=\\sqrt{x^2+y^2}$ are given by\n\n$$\n\\ddot{r}=-\\frac{1}{m}\\frac{dV(r)}{dr}+r\\dot{\\phi}^2,\n$$\n\nand\n\n$$\n\\dot{\\phi}=\\frac{L}{m r^2}.\n$$\n\nHere $V(r)$ is any central force which depends only on the relative coordinate.\n\n\n* 2a (5pt) Find the radius of a circular orbit by solving for the position of the minimum of the effective potential.\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{1}{m}\\frac{dV(r)}{dr} = r\\dot{\\phi}^2\n\\label{_auto1} \\tag{1}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} \\frac{1}{m}\\left( -\\frac{-\\alpha}{r^2}\\right) = r \\frac{L^2}{m^2r^4}\n\\label{_auto2} \\tag{2}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} \\frac{\\alpha}{mr^2} = \\frac{L^2}{m^2r^3}\n\\label{_auto3} \\tag{3}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} r = \\frac{L^2}{m\\alpha}\n\\label{_auto4} \\tag{4}\n\\end{equation}\n$$\n\n* 2b (5pt) At the minimum, the radial velocity is zero and it is only the [centripetal velocity](https://en.wikipedia.org/wiki/Centripetal_force) which is nonzero. This implies that $\\ddot{r}=0$. What is the angular frequency, $\\dot{\\theta}$, of the orbit? Solve this by setting $\\ddot{r}=0=F/m+\\dot{\\theta}^2r$.\n\n\n
\n\n$$\n\\begin{equation}\n\\dot{\\theta}^2 r = - \\frac{F}{m}\n\\label{_auto5} \\tag{5}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} \\dot{\\theta}^2 r = - \\frac{-\\frac{\\alpha}{r^2}}{m}\n\\label{_auto6} \\tag{6}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} \\dot{\\theta}^2 = \\frac{\\alpha}{mr^3}\n\\label{_auto7} \\tag{7}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} \\dot{\\theta} = \\pm \\sqrt{\\frac{\\alpha}{mr^3}}\n\\label{_auto8} \\tag{8}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} \\dot{\\theta} = \\pm \\sqrt{\\frac{\\alpha}{m\\frac{L^6}{m^3\\alpha^3}}}\n\\label{_auto9} \\tag{9}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} \\dot{\\theta} = \\pm \\sqrt{\\frac{\\alpha^4m^2}{L^6}}\n\\label{_auto10} \\tag{10}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} \\dot{\\theta} = \\pm \\frac{\\alpha^2m}{L^3}\n\\label{_auto11} \\tag{11}\n\\end{equation}\n$$\n\n* 2c (5pt) Find the effective spring constant for the particle at the minimum.\n\nWe have shown in class that from the taylor expansion, we have\n\n$$\nk = \\frac{d^2V_{\\text{eff}}}{dr^2}\n$$\n\nTherefore, all we have to do is find the second derivative of $V_{\\text{eff}}$ around the minimum point of $V_{\\text{eff}}$ where $\\dot{r} = \\ddot{r} = 0$.\n\n\n
\n\n$$\n\\begin{equation}\nk = \\frac{d^2V_{\\text{eff}}}{dr^2}\n\\label{_auto12} \\tag{12}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} = \\frac{d^2\\left( -\\frac{\\alpha}{r} + \\frac{1}{2} \\frac{L^2}{mr^2}\\right) }{dr^2}\n\\label{_auto13} \\tag{13}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} = -\\frac{2\\alpha}{r^3} + \\frac{3L^2}{mr^4}\n\\label{_auto14} \\tag{14}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} = -\\frac{2\\alpha}{\\frac{L^6}{m^3\\alpha^3}} + \\frac{3L^2}{m\\frac{L^8}{m^4\\alpha^4}}\n\\label{_auto15} \\tag{15}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} = -\\frac{2m^3\\alpha^4}{L^6} + \\frac{3m^3\\alpha^4}{L^6}\n\\label{_auto16} \\tag{16}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} = \\frac{m^3\\alpha^4}{L^6}\n\\label{_auto17} \\tag{17}\n\\end{equation}\n$$\n\n* 2d (5pt) What is the angular frequency for small vibrations about the minimum? How does this compare with the answer to (3b)?\n\nFor small deviations $\\delta r$ of $r$,\n\n$$\nm\\frac{d^2\\left( \\delta r \\right) }{dt^2} = -k \\delta r\n$$\n\nThe solution of this differential equation is of the form\n\n$$\n\\delta r = A \\cos(\\omega t + \\phi)\n$$\n\nwhere\n\n\n
\n\n$$\n\\begin{equation}\n\\omega = \\sqrt{\\frac{k}{m}}\n\\label{_auto18} \\tag{18}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} = \\sqrt{\\frac{m^2\\alpha^4}{L^6}} \n\\label{_auto19} \\tag{19}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} = \\frac{m\\alpha^2}{L^3}\n\\label{_auto20} \\tag{20}\n\\end{equation}\n$$\n\nThis is in fact equal to the expression for $\\dot{\\theta}$. This means that small perturbations oscillate in sync with the orbit and this traces out an ellipse with a very small eccentricity, a very nice physical result.\n\n\n### Exercise 3, Inverse-square force again (10pt)\n\nConsider again a particle of mass $m$ in the same attractive potential, $U(r)=-\\alpha/r$, with angular momentum $L$ with just the right energy so that\n\n$$\nA=m\\alpha/L^2\n$$\n\nwhere $A$ comes from the expression\n\n$$\nr=\\frac{1}{(m\\alpha/L^2)+A\\cos{(\\phi)}}.\n$$\n\nThe trajectory can then be rewritten as\n\n$$\nr=\\frac{2r_0}{1+\\cos\\theta},~~~r_0=\\frac{L^2}{2m\\alpha}.\n$$\n\n* 3a (5pt) Show that for this case the total energy $E$ approaches zero.\n\n\n
\n\n$$\n\\begin{equation}\nE = - \\frac{\\alpha}{r} + \\frac{1}{2} m \\left( (\\dot{\\theta}r)^2+\\dot{r}^2\\right) \n\\label{_auto21} \\tag{21}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} = - \\frac{\\alpha}{r} + \\frac{1}{2} m \\left[ \\left( \\frac{L}{mr^2}r\\right) ^2+\\left( \\frac{dr}{d\\theta}\\dot{\\theta}\\right) ^2\\right] \n\\label{_auto22} \\tag{22}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} = - \\frac{\\alpha}{2r_0}(1+\\cos\\theta) + \\frac{1}{2} m \\left[ \\left( \\frac{L(1+\\cos\\theta)}{2mr_0}\\right) ^2+\\left( 2r_0\\frac{-1}{(1+\\cos\\theta)^2}(-\\sin\\theta)\\frac{L}{mr^2}\\right) ^2\\right] \n\\label{_auto23} \\tag{23}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} = - \\frac{\\alpha}{2r_0}(1+\\cos\\theta) + \\frac{1}{2} m \\left[ \\left( \\frac{L(1+\\cos\\theta)}{2mr_0}\\right) ^2+\\left( 2r_0\\frac{-1}{(1+\\cos\\theta)^2}(-\\sin\\theta)\\frac{L(1+\\cos\\theta)^2}{4mr_0^2}\\right) ^2\\right] \n\\label{_auto24} \\tag{24}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} = - \\frac{\\alpha}{2r_0}(1+\\cos\\theta) + \n\\frac{1}{2} m \\left[ \\left( \\frac{L(1+\\cos\\theta)}{2mr_0}\\right) ^2+\\left( \\sin\\theta\\frac{L}{2mr_0}\\right) ^2\\right] \n\\label{_auto25} \\tag{25}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} = - \\frac{\\alpha}{2r_0}(1+\\cos\\theta) + \n\\frac{1}{2} m \\left[ \\left( \\frac{L(1+\\cos\\theta)}{2mr_0}\\right) ^2+\\left( \\sin\\theta\\frac{L}{2mr_0}\\right) ^2\\right] \n\\label{_auto26} \\tag{26}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} = - \\frac{\\alpha}{2r_0}(1+\\cos\\theta) + \n\\frac{1}{2} m \\frac{L^2}{4m^2r_0^2} \\left[ \\left( 1+\\cos\\theta\\right) ^2+\\left( \\sin\\theta\\right) ^2\\right] \n\\label{_auto27} \\tag{27}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} = - \\frac{\\alpha}{2r_0}(1+\\cos\\theta) + \n\\frac{1}{2} \\frac{L^2}{4mr_0^2} \\left( 1 + \\cos^2\\theta + 2\\cos \\theta + \\sin^2\\theta\\right) \n\\label{_auto28} \\tag{28}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} = - \\frac{\\alpha}{2r_0}(1+\\cos\\theta) + \n\\frac{1}{2} \\frac{L^2}{4mr_0^2} \\left( 2 + 2\\cos \\theta \\right) \n\\label{_auto29} \\tag{29}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} = (1+\\cos\\theta) \\left( - \\frac{\\alpha}{2r_0} + \\frac{L^2}{4mr_0^2}\\right) \n\\label{_auto30} \\tag{30}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} = (1+\\cos\\theta) \\left( - \\frac{\\alpha}{2\\frac{L^2}{2m\\alpha}} + \\frac{L^2}{4m\\frac{L^4}{4m^2\\alpha^2}}\\right) \n\\label{_auto31} \\tag{31}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} = (1+\\cos\\theta) \\left( - \\frac{m\\alpha^2}{L^2} + \\frac{m\\alpha^2}{L^2}\\right) \n\\label{_auto32} \\tag{32}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} = 0\n\\label{_auto33} \\tag{33}\n\\end{equation}\n$$\n\n* 3b (5pt) With zero energy $E=0$, write this trajectory in a more recognizable parabolic form, that is express $x_0$ and $R$ in terms of $r_0$ using\n\n$$\nx=x_0-\\frac{y^2}{R}.\n$$\n\nWe have that\n\n\n
\n\n$$\n\\begin{equation}\nx = r \\cos\\theta\n\\label{_auto34} \\tag{34}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} \ny = r \\sin \\theta.\n\\label{_auto35} \\tag{35}\n\\end{equation}\n$$\n\nUsing the general solution with eccintricity $\\epsilon=1$, we have\n\n$$\nr(\\theta)=\\frac{c}{1+\\cos\\theta},\n$$\n\nand multiplying both sides with $1+\\cos\\theta$ and using that $x=r\\cos\\theta$,\n\n$$\nr = c -x,\n$$\n\nand using that $r^2=x^2+y^2$, we square both sides\n\n$$\nr^2 = x^2+y^2=c^2 +x^2-2cx,\n$$\n\nleading to\n\n$$\ny^2=c^2-2cx,\n$$\n\nand using that we defined\n\n$$\nc=2r_0=\\frac{L^2}{m\\alpha},\n$$\n\nwe divide by $2c$ \nand we get the final answer\n\n$$\nx = r_0 - \\frac{y^2}{4r_0}\n$$\n\n### Exercise 4, parabolic and hyperbolic orbits (10pt)\n\nThe solution to the radial function for an inverse-square-law force, see for example Taylor equation (8.59) or the equation above, is\n\n$$\nr(\\phi) = \\frac{c}{1+\\epsilon\\cos{(\\phi)}}.\n$$\n\nFor $\\epsilon=1$ (or the energy $E=0$) the orbit reduces to a parabola as we saw in the previous exercise,\nwhile for $\\epsilon > 1$ (or energy positive) the orbit becomes a hyperbola. The equation for a hyperbola in Cartesian coordinates is\n\n$$\n\\frac{(x-\\delta)^2}{\\alpha^2}-\\frac{y^2}{\\beta^2}=1.\n$$\n\nFor a hyperbola, identify the constants $\\alpha$, $\\beta$ and $\\delta$ in terms of the constants $c$ and $\\epsilon$ for $r(\\phi)$.\n\n\n
\n\n$$\n\\begin{equation}\nx = r\\cos\\phi\n\\label{_auto36} \\tag{36}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} = \\frac{c\\cos\\phi}{1+\\epsilon\\cos\\phi}\n\\label{_auto37} \\tag{37}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation}\ny = r\\sin\\phi \n\\label{_auto38} \\tag{38}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} = \\frac{c\\sin\\phi}{1+\\epsilon\\cos\\phi}\n\\label{_auto39} \\tag{39}\n\\end{equation}\n$$\n\nHere $\\epsilon>1$. We use our equation for $r$, multiply with the denominator $1+\\epsilon\\cos\\phi$ on both sides and have\n\n$$\nr(1+\\epsilon\\cos\\phi)=c,\n$$\n\nuse $x=r\\cos\\phi$ and square and use that $r^2=x^2+y^2$ and we have\n\n$$\nr^2=x^2+y^2=c^2+\\epsilon^2x^2-2cx\\epsilon,\n$$\n\nand reorder\n\n$$\nx^2(\\epsilon^2-1)-y^2-2cx\\epsilon= -c^2.\n$$\n\nWe complete the square in $x$ by adding and subtracting on both sides $\\epsilon^2c^2/(\\epsilon^2-1)$\nand we obtain\n\n$$\n(\\epsilon^2-1)(x-\\delta)^2-y^2= -c^2+\\frac{\\epsilon^2c^2}{\\epsilon^2-1}.\n$$\n\nHere we have defined\n\n$$\n\\delta = \\frac{c\\epsilon}{\\epsilon^2-1},\n$$\n\nand introducing the constants\n\n$$\n\\alpha = \\frac{c}{\\epsilon^2-1},\n$$\n\nand\n\n$$\n\\beta = \\frac{c}{\\sqrt{\\epsilon^2-1}},\n$$\n\nwe can rewrite the above equation as\n\n$$\n\\frac{(x-\\delta)^2}{\\alpha^2}-\\frac{y^2}{\\beta^2}=1,\n$$\n\nwhich is nothing but the equation for a hyperbola.\n\n\n### Exercise 5, Testing orbit types (50 pt)\n\nIn this exercise we can use the program for $r(\\phi)$ we developed in hw8. We will use an inverse-square-law force as in exercises 1, 2, 3 and 4. The aim is to see that the orbits we get for $E<0$ become ellipses (or circles), parabola for $E=0$ and hyperbola for $E>0$. An example code is shown here.\n\nHere we have defined the constants $L=m=\\alpha=1$. Feel free to set new values. **You need also to set the initial conditions** in order to study the different types of orbits. It may be useful to plot the potential here and find the values for the initial conditions that fit $E<0$, $E=0$ and $E>0$.\n\n\n```python\n%matplotlib inline\n\n# Common imports\nimport numpy as np\nimport pandas as pd\nfrom math import *\nimport matplotlib.pyplot as plt\n# Simple Gravitational Force -alpha/r\n \nDeltaT = 0.01\n#set up arrays \ntfinal = 100.0\nn = ceil(tfinal/DeltaT)\n# set up arrays for t, v and r\nt = np.zeros(n)\nv = np.zeros(n)\nr = np.zeros(n)\n# Constants of the model, setting all variables to one for simplicity\nalpha = 1.0\nAngMom = 1.0 # The angular momentum\nm = 1.0 # scale mass to one\nc1 = AngMom*AngMom/(m*m)\nc2 = AngMom*AngMom/m\n# You need to specify the initial conditions\n# Here we have chosen the conditions which lead to circular orbit and thereby a constant r\nr0 = (AngMom*AngMom/m/alpha)\nv0 = 0.0\nr[0] = r0\nv[0] = v0\n# Start integrating using the Velocity-Verlet method\nfor i in range(n-1):\n # Set up acceleration\n a = -alpha/(r[i]**2)+c1/(r[i]**3)\n # update velocity, time and position using the Velocity-Verlet method\n r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a\n anew = -alpha/(r[i+1]**2)+c1/(r[i+1]**3)\n v[i+1] = v[i] + 0.5*DeltaT*(a+anew)\n t[i+1] = t[i] + DeltaT\n # Plot position as function of time\nfig, ax = plt.subplots(2,1)\nax[0].set_xlabel('time')\nax[0].set_ylabel('radius')\nax[0].plot(t,r)\nax[1].set_xlabel('time')\nax[1].set_ylabel('Velocity')\nax[1].plot(t,v)\n\nplt.show()\n```\n\nRun your code and study and discuss the situations where you have\nelliptical, parabolic and hyperbolic orbits. Discuss the physics of\nthese cases. The results from exercises 1, 2, 3 and 4 may be useful\nhere. In the code here we have chosen initial conditions which correspond to circular motion.\nThis corresponds to\n\n$$\nr_{\\mathrm{min}} = \\frac{L^2}{m\\alpha}.\n$$\n\nNote well that the velocity is now the radial velocity. If we want to study the angular velocity we would need to add the equations for this quantity. The solution to exercises 1-4 give you the minimum $r$ values needed to find the elliptical, parabolic and hyperbolic orbits. For elliptical orbits you should have $\\frac{L^2}{2m\\alpha} < r_{\\mathrm{min}} <\\frac{L^2}{m\\alpha}$. For parabolic orbits $r_{\\mathrm{min}} =\\frac{L^2}{m\\alpha}$ and for hyperbolic orbits we have $0. There you will also find examples on how to write a scientific article. \nBelow you can also find a description on how to gain extra credits by attending scientific talks.\n\n\nThis assignment allows you to gain extra credit points by practicing\nyour scientific writing. For each of the remaining homeworks you can\nsubmit the specified section of a scientific report (written about the\nnumerical aspect of the homework) for five extra credit points on the\nassignment. For the two midterms and the final, submitting a full\nscientific report covering the numerical analysis problem will be\nworth ten extra points. For credit the grader must be able to tell\nthat you put effort into the assignment (i.e. well written, well\nformatted, etc.). If you are unfamiliar with writing scientific\nreports, [see the information here](https://github.com/mhjensen/Physics321/blob/master/doc/Homeworks/ExtraCredits/IntroductionScientificWriting.md)\n\nThe following table explains what aspect of a scientific report is due\nwith which homework. You can submit the assignment in any format you\nlike, in the same document as your homework, or in a different one.\nRemember to cite any external references you use and include a\nreference list. There are no length requirements, but make sure what\nyou turn in is complete and through. If you have any questions,\nplease contact Julie Butler at butler@frib.msu.edu.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
HW/Project Due Date Extra Credit Assignment
HW 3 2-8 Abstract
HW 4 2-15 Introduction
HW 5 2-22 Methods
HW 6 3-1 Results and Discussion
**Midterm 1** **3-12** *Full Written Report*
HW 7 3-22 Abstract
HW 8 3-29 Introduction
HW 9 4-5 Results and Discussion
**Midterm 2** **4-16** *Full Written Report*
HW 10 4-26 Abstract
**Final** **4-30** *Full Written Report*
\n\nYou can also gain extra credits if you attend scientific talks.\nThis is described here.\n\n\n### Integrating Classwork With Research\n\nThis opportunity will allow you to earn up to 5 extra credit points on a Homework per week. These points can push you above 100% or help make up for missed exercises.\nIn order to earn all points you must:\n\n1. Attend an MSU research talk (recommended research oriented Clubs is provided below)\n\n2. Summarize the talk using at least 150 words\n\n3. Turn in the summary along with your Homework.\n\nApproved talks:\nTalks given by researchers through the following clubs:\n* Research and Idea Sharing Enterprise (RAISE)​: Meets Wednesday Nights Society for Physics Students (SPS)​: Meets Monday Nights\n\n* Astronomy Club​: Meets Monday Nights\n\n* Facility For Rare Isotope Beam (FRIB) Seminars: ​Occur multiple times a week\n\nIf you have any questions please consult Jeremy Rebenstock, rebensto@msu.edu.\n\nAll the material on extra credits is at .\n", "meta": {"hexsha": "d1be6da6cf113a36548271094b165692c68afc36", "size": 48302, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "doc/src/Homeworks/Solutions/solutionhw9.ipynb", "max_stars_repo_name": "mhjensen/Physics321", "max_stars_repo_head_hexsha": "f858db36328c9fc127ccb44f62934d8f8749dd9f", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2020-01-09T17:41:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T00:48:58.000Z", "max_issues_repo_path": "doc/src/Homeworks/Solutions/solutionhw9.ipynb", "max_issues_repo_name": "mhjensen/Physics321", "max_issues_repo_head_hexsha": "f858db36328c9fc127ccb44f62934d8f8749dd9f", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-01-08T03:47:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-15T15:02:57.000Z", "max_forks_repo_path": "doc/src/Homeworks/Solutions/solutionhw9.ipynb", "max_forks_repo_name": "mhjensen/Physics321", "max_forks_repo_head_hexsha": "f858db36328c9fc127ccb44f62934d8f8749dd9f", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 33, "max_forks_repo_forks_event_min_datetime": "2020-01-10T20:40:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T20:28:41.000Z", "avg_line_length": 35.3343087052, "max_line_length": 8636, "alphanum_fraction": 0.5952548549, "converted": true, "num_tokens": 7962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.4148988457967689, "lm_q1q2_score": 0.20258821712996927}} {"text": "\n\n# Tutorial 1: Learn how to use modern convnets\n**Week 2, Day 2: Modern Convnets**\n\n**By Neuromatch Academy**\n\n__Content creators:__ Laura Pede, Richard Vogg, Marissa Weis, Timo Lüddecke, Alexander Ecker (based on an initial version by Ben Heil)\n\n__Content reviewers:__ Arush Tagade, Polina Turishcheva, Yu-Fang Yang, Bettina Hein, Melvin Selim Atay\n\n__Content editors:__ Roberto Guidotti, Spiros Chavlis\n\n__Production editors:__ Anoop Kulkarni, Roberto Guidotti, Cary Murray, Spiros Chavlis\n\n**Our 2021 Sponsors, including Presenting Sponsor Facebook Reality Labs**\n\n

\n\n---\n# Tutorial Objectives\n\nIn this tutorial we are going to learn more about Convnets. More specifically, we will:\n\n1. Learn about modern CNNs and Transfer Learning.\n2. Understand how architectures incorporate ideas we have about the world.\n3. Understand the operating principles underlying the basic building blocks of modern CNNs.\n4. Understand the concept of transfer learning and learn to recognize opportunities for applying it.\n5. Understand the speed vs. accuracy trade-off.\n\n\n```python\n# @title Tutorial slides\n\n# @markdown These are the slides for the videos in all tutorials today\nfrom IPython.display import IFrame\nIFrame(src=f\"https://mfr.ca-1.osf.io/render?url=https://osf.io/tzfsn/?direct%26mode=render%26action=download%26mode=render\", width=854, height=480)\n```\n\n---\n# Setup\n\n\n```python\n# @title Install dependencies\nfrom IPython.display import clear_output\n!pip install pillow --quiet\nclear_output()\n```\n\n\n```python\n# Import libraries\nimport os\nimport time\nimport torch\nimport tqdm\nimport urllib\nimport IPython\nimport requests\nimport torchvision\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom torchvision.datasets import ImageFolder\nfrom torchvision.models import AlexNet\nfrom torchvision.utils import make_grid\nfrom torchvision import transforms\n\nfrom PIL import Image\nfrom io import BytesIO\n```\n\n\n```python\n# @title Figure settings\nimport ipywidgets as widgets # interactive display\n%config InlineBackend.figure_format = 'retina'\nplt.style.use(\"https://raw.githubusercontent.com/NeuromatchAcademy/content-creation/main/nma.mplstyle\")\n```\n\n\n```python\n# @title Set random seed\n\n# @markdown Executing `set_seed(seed=seed)` you are setting the seed\n\n# for DL its critical to set the random seed so that students can have a\n# baseline to compare their results to expected results.\n# Read more here: https://pytorch.org/docs/stable/notes/randomness.html\n\n# Call `set_seed` function in the exercises to ensure reproducibility.\nimport random\nimport torch\n\ndef set_seed(seed=None, seed_torch=True):\n if seed is None:\n seed = np.random.choice(2 ** 32)\n random.seed(seed)\n np.random.seed(seed)\n if seed_torch:\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n torch.cuda.manual_seed(seed)\n torch.backends.cudnn.benchmark = False\n torch.backends.cudnn.deterministic = True\n\n print(f'Random seed {seed} has been set.')\n\n\n# In case that `DataLoader` is used\ndef seed_worker(worker_id):\n worker_seed = torch.initial_seed() % 2**32\n np.random.seed(worker_seed)\n random.seed(worker_seed)\n```\n\n\n```python\n# @title Set device (GPU or CPU). Execute `set_device()`\n# especially if torch modules used.\n\n# inform the user if the notebook uses GPU or CPU.\n\ndef set_device():\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n if device != \"cuda\":\n print(\"WARNING: For this notebook to perform best, \"\n \"if possible, in the menu under `Runtime` -> \"\n \"`Change runtime type.` select `GPU` \")\n else:\n print(\"GPU is enabled in this notebook.\")\n\n return device\n```\n\n\n```python\nSEED = 2021\nset_seed(seed=SEED)\nDEVICE = set_device()\n```\n\n---\n# Section 1: Modern CNNs and Transfer Learning\n\n\n```python\n# @title Video 1: Modern CNNs and Transfer Learning\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1Wf4y157wE\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"mfOd2EKzscM\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\ndisplay(out)\n```\n\nImages are high dimensional. That is to say that `image_length` * `image_width` * `image_channels` is a big number, and multiplying that big number by a normal sized fully-connected layer leads to a ton of parameters to learn. Yesterday, we learned about convolutional neural networks, one way of working around high dimensionality in images and other domains. \n\nThe widget below (i.e., *Interactive Demo 1*) calculates the parameters required for a single convolutional or fully connected layer that operates on an image of a certain height and width.\n\nRecall that, the number of parameters of a convolutional layer $l$ are calculated as:\n\n\\begin{equation}\n\\text{num_of_params}_l = \\left[ \\left( H \\times W \\times K_{l-1} \\right) + 1 \\right] \\times K_l\n\\end{equation}\n\nwhere $H$ denotes the shape of the height of the filter, $W$ the shape of the width of the filter, and $K_l$ denotes the number of the filters in the $l$-th layer. The added $1$ is because of the bias term for each filter.\n\n\nWhile a fully connected layer contains:\n\n\\begin{equation}\n\\text{num_of_params}_l = \\left[ \\left( N_{l-1} \\times N_l \\right) + 1 \\times N_l \\right]\n\\end{equation}\n\nwhere $N_l$ denotes the number of nodes in the $l$-th layer.\n\n\nAdjust the sliders to gain an intuition for how different model and data characteristics affect the number of parameters your model need to fit.\n\nNote: these classes are designed to show parameter scaling in the first layer of a network, to be actually useful they would need more layers, an activation function, etc.\n\n\n```python\nclass FullyConnectedNet(nn.Module):\n def __init__(self):\n super(FullyConnectedNet, self).__init__()\n\n image_width = 128\n image_channels = 3\n self.input_size = image_channels * image_width ** 2\n\n self.fc1 = nn.Linear(self.input_size, 256)\n\n def forward(self, x):\n x = x.view(-1, self.input_size)\n return self.fc1(x)\n```\n\n\n```python\nclass ConvNet(nn.Module):\n def __init__(self):\n super(ConvNet, self).__init__()\n\n self.conv1 = nn.Conv2d(in_channels=3,\n out_channels=256,\n kernel_size=(3, 3),\n padding=1)\n\n def forward(self, x):\n return self.conv1(x)\n```\n\n## Coding Exercise 1: Calculate number of parameters in FCNN vs ConvNet \n\nWrite a function that calculates the number of parameters of a given network. Apply the function to the above defined fully-connected network and convolutional network and compare the parameter counts.\n\n**Hint:** `torch.numel`\n\n\n```python\ndef get_parameter_count(network):\n \"\"\"\n Calculate the number of parameters used by the fully connected network.\n Hint: Casting the result of network.parameters() to a list may make it\n easier to work with\n\n Args:\n network: Network to calculate the parameters of\n\n Returns:\n param_count: The number of parameters in the network\n \"\"\"\n\n ####################################################################\n # Fill in all missing code below (...),\n # then remove or comment the line below to test your function\n raise NotImplementedError(\"Convolution math\")\n ####################################################################\n # Get the network's parameters\n parameters = ...\n\n param_count = 0\n # Loop over all layers\n for layer in parameters:\n param_count += ...\n\n return param_count\n\n\n# Initialize networks\nfccnet = FullyConnectedNet()\nconvnet = ConvNet()\n# Apply above defined function to both networks\n## Uncomment to test your fuimction\n# print('FCCN parameter count: ' + str(get_parameter_count(fccnet)))\n# print('ConvNet parameter count: ' + str(get_parameter_count(convnet)))\n```\n\n\n```python\n# to_remove solution\ndef get_parameter_count(network):\n \"\"\"\n Calculate the number of parameters used by the fully connected network.\n Hint: Casting the result of network.parameters() to a list may make it\n easier to work with\n\n Args:\n network: Network to calculate the parameters of\n\n Returns:\n param_count: The number of parameters in the network\n \"\"\"\n\n # Get the network's parameters\n parameters = network.parameters()\n\n param_count = 0\n # Loop over all layers\n for layer in parameters:\n param_count += torch.numel(layer)\n\n return param_count\n\n\n# Initialize networks\nfccnet = FullyConnectedNet()\nconvnet = ConvNet()\n# Apply above defined function to both networks\n## Uncomment to test your fuimction\nprint('FCCN parameter count: ' + str(get_parameter_count(fccnet)))\nprint('ConvNet parameter count: ' + str(get_parameter_count(convnet)))\n```\n\n```\nFCCN parameter count: 12583168\nConvNet parameter count: 7168\n```\n\n## Interactive Demo 1: Check your results\nThe widget below calculates the number of parameters in a FCNN and CNN with the same architecture as our models above. Our models had an input image that was 128x128, and used 256 filters (or 256 nodes in the FCNN case). Check that the calculations you made above are correct.\n\nNote how few parameters the convolutional networks take, especially as you increase the input image size.\n\n\n```python\n# @title Parameter Calculator\n# @markdown ##### Run this cell to enable the widget!\n\ndef calculate_parameters(filter_count, image_width, fcnn_nodes):\n # Convnet math: Implement how parameters scale as a function of image size between convnets and FCNN\n\n filter_width = 3\n image_channels = 3\n\n # Assuming a square, RGB image\n image_area = image_width ** 2\n image_volume = image_area * image_channels\n\n # If we're using padding=same, the output of a convnet will be the same shape as the original\n # image, but with more features\n fcnn_parameters = image_volume * fcnn_nodes\n cnn_parameters = image_channels * filter_count * filter_width ** 2\n\n # Add bias\n fcnn_parameters += fcnn_nodes\n cnn_parameters += filter_count\n\n print('CNN parameters: {}'.format(cnn_parameters))\n print('Fully Connected parameters: {}'.format(fcnn_parameters))\n\n return None\n\n_ = widgets.interact(calculate_parameters,\n filter_count=(16, 512, 16),\n image_width=(16, 512, 16),\n fcnn_nodes=(16, 512, 16))\n```\n\n--- \n# Section 2: The History of Convnets\n\nConvolutional neural networks have been around for a long time. [The first CNN model](https://www.rctn.org/bruno/public/papers/Fukushima1980.pdf) was published in 1980, and was based on ideas in neuroscience that [predated it by decades](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC1359523/). Why is it then that [AlexNet](https://proceedings.neurips.cc/paper/2012/hash/c399862d3b9d6b76c8436e924a68c45b-Abstract.html), a CNN model published in 2012, is generally considered to mark the start of the deep learning revolution?\n\nWatch the video below to get a better idea of the role that hardware and the internet have played in progressing deep learning.\n\n\n```python\n# @title Video 2: History of convnets\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1364y167Qy\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"xtoLjKSPrUQ\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\ndisplay(out)\n```\n\n## Exercise 2: Challenges of improving CNNs\nAs we shall see today, the story of deep learning and CNNs has been one of scaling networks: making them bigger and deeper.\n\nBased on what you know so far from previous days, what challenges might researchers have faced when trying to scale up CNNs and applying them to different visual recognition tasks? Do you already have some ideas how these challenges might have been addressed?\n\nDiscuss this with your group for ~10 minutes.\n\n(Hint: labeled data, compute and memory are all finite)\n\n\n```python\n# to_remove explanation\n\n\"\"\"\nChallenge 1: limited data / overfitting. Limited amount of labeled data for many tasks beyond ImageNet.\nLabels are expensive, for many tasks we don't have enough of them. --> Large networks will overfit.\n[Solution: transfer learning: adapt networks trained on ImageNet to other tasks]\n\nChallenge 2: hardware limitations. Making networks bigger/deeper will increase\ncompute and memory requirements. --> There are physical limits what can be done, and completed in reasonable time.\n[Solution: more efficient architectures than standard convolutions]\n\nChallenge 3: training deep networks \"out-of-the-box\" is unstable / training diverges\n[Solution:.1 mechanisms like batch normalization and architectures like ResNets]\n\nNOTE: Students cannot know any of the solutions to the problems from the material.\nThe intention of the question is to have them discuss and think about the\nchallenges (primarily the first two). The solutions are just provided for completeness for the tutors.\n\"\"\"\n```\n\n---\n# Section 3: Big and Deep Convnets\n\n\n```python\n# @title Video 3: AlexNet & VGG\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV12U4y1n7q5\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"ZB87qC7yPiE\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\ndisplay(out)\n```\n\n## Section 3.1: Introduction to AlexNet\n\nAlexNet arguably marked the start of the current age of deep learning.\nIt incorporates a number of the defining characteristics of successful DL today: deep networks, GPU-powered paralellization, and building blocks encoding task-specific priors.\nIn this section you'll have the opportunity to play with AlexNet and see the world through its eyes.\n\n\n```python\n# @title Import Alexnet\n# @markdown ##### This cell gives you the `alexnet` model as well as the `input_image` and `input_batch` variables used below\n\nalexnet = AlexNet()\n\nstate_dict = torch.hub.load_state_dict_from_url(\"https://s3.amazonaws.com/pytorch/models/alexnet-owt-4df8aa71.pth\")\nalexnet.load_state_dict(state_dict=state_dict)\n\nurl, filename = (\"https://github.com/pytorch/hub/raw/master/images/dog.jpg\", \"dog.jpg\")\ntry: urllib.URLopener().retrieve(url, filename)\nexcept: urllib.request.urlretrieve(url, filename)\n\ninput_image = Image.open(filename)\npreprocess = transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225]),\n ])\ninput_tensor = preprocess(input_image)\ninput_batch = input_tensor.unsqueeze(0) # create a mini-batch as expected by the model\n\n# move the input and model to GPU for speed if available\nif torch.cuda.is_available():\n input_batch = input_batch.to(DEVICE)\n alexnet.to(DEVICE)\n```\n\n## Section 3.2: What does AlexNet learn?\nThis code visualizes the top-layer filters learned by AlexNet.\nWhat do these filters remind you of?\n\n\n```python\nwith torch.no_grad():\n params = list(alexnet.parameters())\n fig, axs = plt.subplots(8, 8, figsize=(8, 8))\n filters = []\n for filter_index in range(params[0].shape[0]):\n row_index = filter_index // 8\n col_index = filter_index % 8\n\n filter = params[0][filter_index,:,:,:]\n filter_image = filter.permute(1, 2, 0).cpu()\n scale = np.abs(filter_image).max()\n scaled_image = filter_image / (2 * scale) + 0.5\n filters.append(scaled_image.cpu())\n axs[row_index, col_index].imshow(scaled_image.cpu())\n axs[row_index, col_index].axis('off')\n plt.show()\n```\n\n### Exercise 3.2.1: Filter Similarity\n\nWhat do these filters remind you of?\n\n\n```python\n# to_remove explanation\n\"\"\"\nSome of the filters look like edge detectors, as they are color insensitive and consist of vertical or horizontal patterns.\n\"\"\"\n```\n\n### Interactive Demo 3.2: What does AlexNet see?\nOne way of visualizing CNNs is to look at the output of individual filters for a given image. Below is a widget that lets you examine the outputs of various filters used in AlexNet.\n\n\n```python\n# @title Image Widget Code\n# @markdown ##### Run this cell to enable the widget\n\ndef alexnet_intermediate_output(net, image):\n return F.relu(net.features[0](image))\n\n\ndef browse_images(input_batch, input_image):\n intermediate_output = alexnet_intermediate_output(alexnet, input_batch)\n n = intermediate_output.shape[1]\n\n def view_image(i):\n with torch.no_grad():\n channel = intermediate_output[0, i,:].squeeze()\n fig, ax = plt.subplots(1, 3, figsize=(18,6))\n ax[0].imshow(input_image)\n ax[1].imshow(filters[i])\n ax[1].set_xlim([-22, 33])\n ax[2].imshow(channel.cpu())\n ax[0].set_title('Input image')\n ax[1].set_title('Filter {}'.format(i))\n ax[2].set_title('Filter {} on input image'.format(i))\n [axi.set_axis_off() for axi in ax.ravel()]\n\n widgets.interact(view_image, i=(0, n-1))\n\n\nbrowse_images(input_batch, input_image)\n```\n\n### Exercise 3.2.2 Filter Purpose\nWhat do these filters appear to be doing? Note that different filters play different roles so there are several good answers.\n\n\n```python\n# to_remove explanation\n\n\"\"\"\nBased on the areas that are highlighted in the outupt, some filters seem to be detecting edges,\nwhile others seem to react to the white color of the dog or the green of the background.\n\"\"\"\n```\n\n## Further Reading\nIf the question \"what are neural network filters looking for\" is at all interesting to you, or if you like geometric art, you'll enjoy [this post](https://distill.pub/2017/feature-visualization/) creating images that maximize output of various CNN neurons. There is also a good article showing what the space of images looks like as models train [here](https://distill.pub/2020/grand-tour/).\n\n---\n# Section 4: Convnets After AlexNet\n\n\n```python\n# @title Video 4: Residual Networks (ResNets)\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1bf4y1j7od\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"EJSZnJyy4PI\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\ndisplay(out)\n```\n\nIn this section we'll be working with a state of the art CNN model called [ResNet](https://arxiv.org/abs/1512.03385). ResNet has two particularly interesting features. First, it uses skip connections to avoid the vanishing gradient problem. Second, each block (collection of layers) in a ResNet can be treated as learning a residual function.\n\nMathematically, a neural network can be thought of as a series of operations that maps an input (like an image of a dog) to an output (like the label \"dog\"). In math-speak a mapping from an input to an output is called a function. Neural networks are a flexible way of expressing that function. \n\nIf you were to subtract out the true function mapping images to class labels from the function learned by a network, you'd be left with the residual error or \"residual function\". ResNets try to learn the original function, then the residual function, then the residual of the residual, and so on, using their residual blocks and adding them to the output of the preceeding layers.\n\nIn this section we'll run several images through a pre-trained ResNet and see what happens.\n\n\n```python\n# @title Download imagenette\n!rm -rf imagenette*\n!wget https://s3.amazonaws.com/fast-ai-imageclas/imagenette2-320.tgz\n!tar -xf imagenette2-320.tgz\n!rm -r imagenette2-320.tgz\n```\n\n\n```python\n# @title Set Up Textual ImageNet labels\ndict_map={0: 'tench, Tinca tinca',\n 1: 'goldfish, Carassius auratus',\n 2: 'great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias',\n 3: 'tiger shark, Galeocerdo cuvieri',\n 4: 'hammerhead, hammerhead shark',\n 5: 'electric ray, crampfish, numbfish, torpedo',\n 6: 'stingray',\n 7: 'cock',\n 8: 'hen',\n 9: 'ostrich, Struthio camelus',\n 10: 'brambling, Fringilla montifringilla',\n 11: 'goldfinch, Carduelis carduelis',\n 12: 'house finch, linnet, Carpodacus mexicanus',\n 13: 'junco, snowbird',\n 14: 'indigo bunting, indigo finch, indigo bird, Passerina cyanea',\n 15: 'robin, American robin, Turdus migratorius',\n 16: 'bulbul',\n 17: 'jay',\n 18: 'magpie',\n 19: 'chickadee',\n 20: 'water ouzel, dipper',\n 21: 'kite',\n 22: 'bald eagle, American eagle, Haliaeetus leucocephalus',\n 23: 'vulture',\n 24: 'great grey owl, great gray owl, Strix nebulosa',\n 25: 'European fire salamander, Salamandra salamandra',\n 26: 'common newt, Triturus vulgaris',\n 27: 'eft',\n 28: 'spotted salamander, Ambystoma maculatum',\n 29: 'axolotl, mud puppy, Ambystoma mexicanum',\n 30: 'bullfrog, Rana catesbeiana',\n 31: 'tree frog, tree-frog',\n 32: 'tailed frog, bell toad, ribbed toad, tailed toad, Ascaphus trui',\n 33: 'loggerhead, loggerhead turtle, Caretta caretta',\n 34: 'leatherback turtle, leatherback, leathery turtle, Dermochelys coriacea',\n 35: 'mud turtle',\n 36: 'terrapin',\n 37: 'box turtle, box tortoise',\n 38: 'banded gecko',\n 39: 'common iguana, iguana, Iguana iguana',\n 40: 'American chameleon, anole, Anolis carolinensis',\n 41: 'whiptail, whiptail lizard',\n 42: 'agama',\n 43: 'frilled lizard, Chlamydosaurus kingi',\n 44: 'alligator lizard',\n 45: 'Gila monster, Heloderma suspectum',\n 46: 'green lizard, Lacerta viridis',\n 47: 'African chameleon, Chamaeleo chamaeleon',\n 48: 'Komodo dragon, Komodo lizard, dragon lizard, giant lizard, Varanus komodoensis',\n 49: 'African crocodile, Nile crocodile, Crocodylus niloticus',\n 50: 'American alligator, Alligator mississipiensis',\n 51: 'triceratops',\n 52: 'thunder snake, worm snake, Carphophis amoenus',\n 53: 'ringneck snake, ring-necked snake, ring snake',\n 54: 'hognose snake, puff adder, sand viper',\n 55: 'green snake, grass snake',\n 56: 'king snake, kingsnake',\n 57: 'garter snake, grass snake',\n 58: 'water snake',\n 59: 'vine snake',\n 60: 'night snake, Hypsiglena torquata',\n 61: 'boa constrictor, Constrictor constrictor',\n 62: 'rock python, rock snake, Python sebae',\n 63: 'Indian cobra, Naja naja',\n 64: 'green mamba',\n 65: 'sea snake',\n 66: 'horned viper, cerastes, sand viper, horned asp, Cerastes cornutus',\n 67: 'diamondback, diamondback rattlesnake, Crotalus adamanteus',\n 68: 'sidewinder, horned rattlesnake, Crotalus cerastes',\n 69: 'trilobite',\n 70: 'harvestman, daddy longlegs, Phalangium opilio',\n 71: 'scorpion',\n 72: 'black and gold garden spider, Argiope aurantia',\n 73: 'barn spider, Araneus cavaticus',\n 74: 'garden spider, Aranea diademata',\n 75: 'black widow, Latrodectus mactans',\n 76: 'tarantula',\n 77: 'wolf spider, hunting spider',\n 78: 'tick',\n 79: 'centipede',\n 80: 'black grouse',\n 81: 'ptarmigan',\n 82: 'ruffed grouse, partridge, Bonasa umbellus',\n 83: 'prairie chicken, prairie grouse, prairie fowl',\n 84: 'peacock',\n 85: 'quail',\n 86: 'partridge',\n 87: 'African grey, African gray, Psittacus erithacus',\n 88: 'macaw',\n 89: 'sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita',\n 90: 'lorikeet',\n 91: 'coucal',\n 92: 'bee eater',\n 93: 'hornbill',\n 94: 'hummingbird',\n 95: 'jacamar',\n 96: 'toucan',\n 97: 'drake',\n 98: 'red-breasted merganser, Mergus serrator',\n 99: 'goose',\n 100: 'black swan, Cygnus atratus',\n 101: 'tusker',\n 102: 'echidna, spiny anteater, anteater',\n 103: 'platypus, duckbill, duckbilled platypus, duck-billed platypus, Ornithorhynchus anatinus',\n 104: 'wallaby, brush kangaroo',\n 105: 'koala, koala bear, kangaroo bear, native bear, Phascolarctos cinereus',\n 106: 'wombat',\n 107: 'jellyfish',\n 108: 'sea anemone, anemone',\n 109: 'brain coral',\n 110: 'flatworm, platyhelminth',\n 111: 'nematode, nematode worm, roundworm',\n 112: 'conch',\n 113: 'snail',\n 114: 'slug',\n 115: 'sea slug, nudibranch',\n 116: 'chiton, coat-of-mail shell, sea cradle, polyplacophore',\n 117: 'chambered nautilus, pearly nautilus, nautilus',\n 118: 'Dungeness crab, Cancer magister',\n 119: 'rock crab, Cancer irroratus',\n 120: 'fiddler crab',\n 121: 'king crab, Alaska crab, Alaskan king crab, Alaska king crab, Paralithodes camtschatica',\n 122: 'American lobster, Northern lobster, Maine lobster, Homarus americanus',\n 123: 'spiny lobster, langouste, rock lobster, crawfish, crayfish, sea crawfish',\n 124: 'crayfish, crawfish, crawdad, crawdaddy',\n 125: 'hermit crab',\n 126: 'isopod',\n 127: 'white stork, Ciconia ciconia',\n 128: 'black stork, Ciconia nigra',\n 129: 'spoonbill',\n 130: 'flamingo',\n 131: 'little blue heron, Egretta caerulea',\n 132: 'American egret, great white heron, Egretta albus',\n 133: 'bittern',\n 134: 'crane',\n 135: 'limpkin, Aramus pictus',\n 136: 'European gallinule, Porphyrio porphyrio',\n 137: 'American coot, marsh hen, mud hen, water hen, Fulica americana',\n 138: 'bustard',\n 139: 'ruddy turnstone, Arenaria interpres',\n 140: 'red-backed sandpiper, dunlin, Erolia alpina',\n 141: 'redshank, Tringa totanus',\n 142: 'dowitcher',\n 143: 'oystercatcher, oyster catcher',\n 144: 'pelican',\n 145: 'king penguin, Aptenodytes patagonica',\n 146: 'albatross, mollymawk',\n 147: 'grey whale, gray whale, devilfish, Eschrichtius gibbosus, Eschrichtius robustus',\n 148: 'killer whale, killer, orca, grampus, sea wolf, Orcinus orca',\n 149: 'dugong, Dugong dugon',\n 150: 'sea lion',\n 151: 'Chihuahua',\n 152: 'Japanese spaniel',\n 153: 'Maltese dog, Maltese terrier, Maltese',\n 154: 'Pekinese, Pekingese, Peke',\n 155: 'Shih-Tzu',\n 156: 'Blenheim spaniel',\n 157: 'papillon',\n 158: 'toy terrier',\n 159: 'Rhodesian ridgeback',\n 160: 'Afghan hound, Afghan',\n 161: 'basset, basset hound',\n 162: 'beagle',\n 163: 'bloodhound, sleuthhound',\n 164: 'bluetick',\n 165: 'black-and-tan coonhound',\n 166: 'Walker hound, Walker foxhound',\n 167: 'English foxhound',\n 168: 'redbone',\n 169: 'borzoi, Russian wolfhound',\n 170: 'Irish wolfhound',\n 171: 'Italian greyhound',\n 172: 'whippet',\n 173: 'Ibizan hound, Ibizan Podenco',\n 174: 'Norwegian elkhound, elkhound',\n 175: 'otterhound, otter hound',\n 176: 'Saluki, gazelle hound',\n 177: 'Scottish deerhound, deerhound',\n 178: 'Weimaraner',\n 179: 'Staffordshire bullterrier, Staffordshire bull terrier',\n 180: 'American Staffordshire terrier, Staffordshire terrier, American pit bull terrier, pit bull terrier',\n 181: 'Bedlington terrier',\n 182: 'Border terrier',\n 183: 'Kerry blue terrier',\n 184: 'Irish terrier',\n 185: 'Norfolk terrier',\n 186: 'Norwich terrier',\n 187: 'Yorkshire terrier',\n 188: 'wire-haired fox terrier',\n 189: 'Lakeland terrier',\n 190: 'Sealyham terrier, Sealyham',\n 191: 'Airedale, Airedale terrier',\n 192: 'cairn, cairn terrier',\n 193: 'Australian terrier',\n 194: 'Dandie Dinmont, Dandie Dinmont terrier',\n 195: 'Boston bull, Boston terrier',\n 196: 'miniature schnauzer',\n 197: 'giant schnauzer',\n 198: 'standard schnauzer',\n 199: 'Scotch terrier, Scottish terrier, Scottie',\n 200: 'Tibetan terrier, chrysanthemum dog',\n 201: 'silky terrier, Sydney silky',\n 202: 'soft-coated wheaten terrier',\n 203: 'West Highland white terrier',\n 204: 'Lhasa, Lhasa apso',\n 205: 'flat-coated retriever',\n 206: 'curly-coated retriever',\n 207: 'golden retriever',\n 208: 'Labrador retriever',\n 209: 'Chesapeake Bay retriever',\n 210: 'German short-haired pointer',\n 211: 'vizsla, Hungarian pointer',\n 212: 'English setter',\n 213: 'Irish setter, red setter',\n 214: 'Gordon setter',\n 215: 'Brittany spaniel',\n 216: 'clumber, clumber spaniel',\n 217: 'English springer, English springer spaniel',\n 218: 'Welsh springer spaniel',\n 219: 'cocker spaniel, English cocker spaniel, cocker',\n 220: 'Sussex spaniel',\n 221: 'Irish water spaniel',\n 222: 'kuvasz',\n 223: 'schipperke',\n 224: 'groenendael',\n 225: 'malinois',\n 226: 'briard',\n 227: 'kelpie',\n 228: 'komondor',\n 229: 'Old English sheepdog, bobtail',\n 230: 'Shetland sheepdog, Shetland sheep dog, Shetland',\n 231: 'collie',\n 232: 'Border collie',\n 233: 'Bouvier des Flandres, Bouviers des Flandres',\n 234: 'Rottweiler',\n 235: 'German shepherd, German shepherd dog, German police dog, alsatian',\n 236: 'Doberman, Doberman pinscher',\n 237: 'miniature pinscher',\n 238: 'Greater Swiss Mountain dog',\n 239: 'Bernese mountain dog',\n 240: 'Appenzeller',\n 241: 'EntleBucher',\n 242: 'boxer',\n 243: 'bull mastiff',\n 244: 'Tibetan mastiff',\n 245: 'French bulldog',\n 246: 'Great Dane',\n 247: 'Saint Bernard, St Bernard',\n 248: 'Eskimo dog, husky',\n 249: 'malamute, malemute, Alaskan malamute',\n 250: 'Siberian husky',\n 251: 'dalmatian, coach dog, carriage dog',\n 252: 'affenpinscher, monkey pinscher, monkey dog',\n 253: 'basenji',\n 254: 'pug, pug-dog',\n 255: 'Leonberg',\n 256: 'Newfoundland, Newfoundland dog',\n 257: 'Great Pyrenees',\n 258: 'Samoyed, Samoyede',\n 259: 'Pomeranian',\n 260: 'chow, chow chow',\n 261: 'keeshond',\n 262: 'Brabancon griffon',\n 263: 'Pembroke, Pembroke Welsh corgi',\n 264: 'Cardigan, Cardigan Welsh corgi',\n 265: 'toy poodle',\n 266: 'miniature poodle',\n 267: 'standard poodle',\n 268: 'Mexican hairless',\n 269: 'timber wolf, grey wolf, gray wolf, Canis lupus',\n 270: 'white wolf, Arctic wolf, Canis lupus tundrarum',\n 271: 'red wolf, maned wolf, Canis rufus, Canis niger',\n 272: 'coyote, prairie wolf, brush wolf, Canis latrans',\n 273: 'dingo, warrigal, warragal, Canis dingo',\n 274: 'dhole, Cuon alpinus',\n 275: 'African hunting dog, hyena dog, Cape hunting dog, Lycaon pictus',\n 276: 'hyena, hyaena',\n 277: 'red fox, Vulpes vulpes',\n 278: 'kit fox, Vulpes macrotis',\n 279: 'Arctic fox, white fox, Alopex lagopus',\n 280: 'grey fox, gray fox, Urocyon cinereoargenteus',\n 281: 'tabby, tabby cat',\n 282: 'tiger cat',\n 283: 'Persian cat',\n 284: 'Siamese cat, Siamese',\n 285: 'Egyptian cat',\n 286: 'cougar, puma, catamount, mountain lion, painter, panther, Felis concolor',\n 287: 'lynx, catamount',\n 288: 'leopard, Panthera pardus',\n 289: 'snow leopard, ounce, Panthera uncia',\n 290: 'jaguar, panther, Panthera onca, Felis onca',\n 291: 'lion, king of beasts, Panthera leo',\n 292: 'tiger, Panthera tigris',\n 293: 'cheetah, chetah, Acinonyx jubatus',\n 294: 'brown bear, bruin, Ursus arctos',\n 295: 'American black bear, black bear, Ursus americanus, Euarctos americanus',\n 296: 'ice bear, polar bear, Ursus Maritimus, Thalarctos maritimus',\n 297: 'sloth bear, Melursus ursinus, Ursus ursinus',\n 298: 'mongoose',\n 299: 'meerkat, mierkat',\n 300: 'tiger beetle',\n 301: 'ladybug, ladybeetle, lady beetle, ladybird, ladybird beetle',\n 302: 'ground beetle, carabid beetle',\n 303: 'long-horned beetle, longicorn, longicorn beetle',\n 304: 'leaf beetle, chrysomelid',\n 305: 'dung beetle',\n 306: 'rhinoceros beetle',\n 307: 'weevil',\n 308: 'fly',\n 309: 'bee',\n 310: 'ant, emmet, pismire',\n 311: 'grasshopper, hopper',\n 312: 'cricket',\n 313: 'walking stick, walkingstick, stick insect',\n 314: 'cockroach, roach',\n 315: 'mantis, mantid',\n 316: 'cicada, cicala',\n 317: 'leafhopper',\n 318: 'lacewing, lacewing fly',\n 319: \"dragonfly, darning needle, devil's darning needle, sewing needle, snake feeder, snake doctor, mosquito hawk, skeeter hawk\",\n 320: 'damselfly',\n 321: 'admiral',\n 322: 'ringlet, ringlet butterfly',\n 323: 'monarch, monarch butterfly, milkweed butterfly, Danaus plexippus',\n 324: 'cabbage butterfly',\n 325: 'sulphur butterfly, sulfur butterfly',\n 326: 'lycaenid, lycaenid butterfly',\n 327: 'starfish, sea star',\n 328: 'sea urchin',\n 329: 'sea cucumber, holothurian',\n 330: 'wood rabbit, cottontail, cottontail rabbit',\n 331: 'hare',\n 332: 'Angora, Angora rabbit',\n 333: 'hamster',\n 334: 'porcupine, hedgehog',\n 335: 'fox squirrel, eastern fox squirrel, Sciurus niger',\n 336: 'marmot',\n 337: 'beaver',\n 338: 'guinea pig, Cavia cobaya',\n 339: 'sorrel',\n 340: 'zebra',\n 341: 'hog, pig, grunter, squealer, Sus scrofa',\n 342: 'wild boar, boar, Sus scrofa',\n 343: 'warthog',\n 344: 'hippopotamus, hippo, river horse, Hippopotamus amphibius',\n 345: 'ox',\n 346: 'water buffalo, water ox, Asiatic buffalo, Bubalus bubalis',\n 347: 'bison',\n 348: 'ram, tup',\n 349: 'bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis',\n 350: 'ibex, Capra ibex',\n 351: 'hartebeest',\n 352: 'impala, Aepyceros melampus',\n 353: 'gazelle',\n 354: 'Arabian camel, dromedary, Camelus dromedarius',\n 355: 'llama',\n 356: 'weasel',\n 357: 'mink',\n 358: 'polecat, fitch, foulmart, foumart, Mustela putorius',\n 359: 'black-footed ferret, ferret, Mustela nigripes',\n 360: 'otter',\n 361: 'skunk, polecat, wood pussy',\n 362: 'badger',\n 363: 'armadillo',\n 364: 'three-toed sloth, ai, Bradypus tridactylus',\n 365: 'orangutan, orang, orangutang, Pongo pygmaeus',\n 366: 'gorilla, Gorilla gorilla',\n 367: 'chimpanzee, chimp, Pan troglodytes',\n 368: 'gibbon, Hylobates lar',\n 369: 'siamang, Hylobates syndactylus, Symphalangus syndactylus',\n 370: 'guenon, guenon monkey',\n 371: 'patas, hussar monkey, Erythrocebus patas',\n 372: 'baboon',\n 373: 'macaque',\n 374: 'langur',\n 375: 'colobus, colobus monkey',\n 376: 'proboscis monkey, Nasalis larvatus',\n 377: 'marmoset',\n 378: 'capuchin, ringtail, Cebus capucinus',\n 379: 'howler monkey, howler',\n 380: 'titi, titi monkey',\n 381: 'spider monkey, Ateles geoffroyi',\n 382: 'squirrel monkey, Saimiri sciureus',\n 383: 'Madagascar cat, ring-tailed lemur, Lemur catta',\n 384: 'indri, indris, Indri indri, Indri brevicaudatus',\n 385: 'Indian elephant, Elephas maximus',\n 386: 'African elephant, Loxodonta africana',\n 387: 'lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens',\n 388: 'giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca',\n 389: 'barracouta, snoek',\n 390: 'eel',\n 391: 'coho, cohoe, coho salmon, blue jack, silver salmon, Oncorhynchus kisutch',\n 392: 'rock beauty, Holocanthus tricolor',\n 393: 'anemone fish',\n 394: 'sturgeon',\n 395: 'gar, garfish, garpike, billfish, Lepisosteus osseus',\n 396: 'lionfish',\n 397: 'puffer, pufferfish, blowfish, globefish',\n 398: 'abacus',\n 399: 'abaya',\n 400: \"academic gown, academic robe, judge's robe\",\n 401: 'accordion, piano accordion, squeeze box',\n 402: 'acoustic guitar',\n 403: 'aircraft carrier, carrier, flattop, attack aircraft carrier',\n 404: 'airliner',\n 405: 'airship, dirigible',\n 406: 'altar',\n 407: 'ambulance',\n 408: 'amphibian, amphibious vehicle',\n 409: 'analog clock',\n 410: 'apiary, bee house',\n 411: 'apron',\n 412: 'ashcan, trash can, garbage can, wastebin, ash bin, ash-bin, ashbin, dustbin, trash barrel, trash bin',\n 413: 'assault rifle, assault gun',\n 414: 'backpack, back pack, knapsack, packsack, rucksack, haversack',\n 415: 'bakery, bakeshop, bakehouse',\n 416: 'balance beam, beam',\n 417: 'balloon',\n 418: 'ballpoint, ballpoint pen, ballpen, Biro',\n 419: 'Band Aid',\n 420: 'banjo',\n 421: 'bannister, banister, balustrade, balusters, handrail',\n 422: 'barbell',\n 423: 'barber chair',\n 424: 'barbershop',\n 425: 'barn',\n 426: 'barometer',\n 427: 'barrel, cask',\n 428: 'barrow, garden cart, lawn cart, wheelbarrow',\n 429: 'baseball',\n 430: 'basketball',\n 431: 'bassinet',\n 432: 'bassoon',\n 433: 'bathing cap, swimming cap',\n 434: 'bath towel',\n 435: 'bathtub, bathing tub, bath, tub',\n 436: 'beach wagon, station wagon, wagon, estate car, beach waggon, station waggon, waggon',\n 437: 'beacon, lighthouse, beacon light, pharos',\n 438: 'beaker',\n 439: 'bearskin, busby, shako',\n 440: 'beer bottle',\n 441: 'beer glass',\n 442: 'bell cote, bell cot',\n 443: 'bib',\n 444: 'bicycle-built-for-two, tandem bicycle, tandem',\n 445: 'bikini, two-piece',\n 446: 'binder, ring-binder',\n 447: 'binoculars, field glasses, opera glasses',\n 448: 'birdhouse',\n 449: 'boathouse',\n 450: 'bobsled, bobsleigh, bob',\n 451: 'bolo tie, bolo, bola tie, bola',\n 452: 'bonnet, poke bonnet',\n 453: 'bookcase',\n 454: 'bookshop, bookstore, bookstall',\n 455: 'bottlecap',\n 456: 'bow',\n 457: 'bow tie, bow-tie, bowtie',\n 458: 'brass, memorial tablet, plaque',\n 459: 'brassiere, bra, bandeau',\n 460: 'breakwater, groin, groyne, mole, bulwark, seawall, jetty',\n 461: 'breastplate, aegis, egis',\n 462: 'broom',\n 463: 'bucket, pail',\n 464: 'buckle',\n 465: 'bulletproof vest',\n 466: 'bullet train, bullet',\n 467: 'butcher shop, meat market',\n 468: 'cab, hack, taxi, taxicab',\n 469: 'caldron, cauldron',\n 470: 'candle, taper, wax light',\n 471: 'cannon',\n 472: 'canoe',\n 473: 'can opener, tin opener',\n 474: 'cardigan',\n 475: 'car mirror',\n 476: 'carousel, carrousel, merry-go-round, roundabout, whirligig',\n 477: \"carpenter's kit, tool kit\",\n 478: 'carton',\n 479: 'car wheel',\n 480: 'cash machine, cash dispenser, automated teller machine, automatic teller machine, automated teller, automatic teller, ATM',\n 481: 'cassette',\n 482: 'cassette player',\n 483: 'castle',\n 484: 'catamaran',\n 485: 'CD player',\n 486: 'cello, violoncello',\n 487: 'cellular telephone, cellular phone, cellphone, cell, mobile phone',\n 488: 'chain',\n 489: 'chainlink fence',\n 490: 'chain mail, ring mail, mail, chain armor, chain armour, ring armor, ring armour',\n 491: 'chain saw, chainsaw',\n 492: 'chest',\n 493: 'chiffonier, commode',\n 494: 'chime, bell, gong',\n 495: 'china cabinet, china closet',\n 496: 'Christmas stocking',\n 497: 'church, church building',\n 498: 'cinema, movie theater, movie theatre, movie house, picture palace',\n 499: 'cleaver, meat cleaver, chopper',\n 500: 'cliff dwelling',\n 501: 'cloak',\n 502: 'clog, geta, patten, sabot',\n 503: 'cocktail shaker',\n 504: 'coffee mug',\n 505: 'coffeepot',\n 506: 'coil, spiral, volute, whorl, helix',\n 507: 'combination lock',\n 508: 'computer keyboard, keypad',\n 509: 'confectionery, confectionary, candy store',\n 510: 'container ship, containership, container vessel',\n 511: 'convertible',\n 512: 'corkscrew, bottle screw',\n 513: 'cornet, horn, trumpet, trump',\n 514: 'cowboy boot',\n 515: 'cowboy hat, ten-gallon hat',\n 516: 'cradle',\n 517: 'crane',\n 518: 'crash helmet',\n 519: 'crate',\n 520: 'crib, cot',\n 521: 'Crock Pot',\n 522: 'croquet ball',\n 523: 'crutch',\n 524: 'cuirass',\n 525: 'dam, dike, dyke',\n 526: 'desk',\n 527: 'desktop computer',\n 528: 'dial telephone, dial phone',\n 529: 'diaper, nappy, napkin',\n 530: 'digital clock',\n 531: 'digital watch',\n 532: 'dining table, board',\n 533: 'dishrag, dishcloth',\n 534: 'dishwasher, dish washer, dishwashing machine',\n 535: 'disk brake, disc brake',\n 536: 'dock, dockage, docking facility',\n 537: 'dogsled, dog sled, dog sleigh',\n 538: 'dome',\n 539: 'doormat, welcome mat',\n 540: 'drilling platform, offshore rig',\n 541: 'drum, membranophone, tympan',\n 542: 'drumstick',\n 543: 'dumbbell',\n 544: 'Dutch oven',\n 545: 'electric fan, blower',\n 546: 'electric guitar',\n 547: 'electric locomotive',\n 548: 'entertainment center',\n 549: 'envelope',\n 550: 'espresso maker',\n 551: 'face powder',\n 552: 'feather boa, boa',\n 553: 'file, file cabinet, filing cabinet',\n 554: 'fireboat',\n 555: 'fire engine, fire truck',\n 556: 'fire screen, fireguard',\n 557: 'flagpole, flagstaff',\n 558: 'flute, transverse flute',\n 559: 'folding chair',\n 560: 'football helmet',\n 561: 'forklift',\n 562: 'fountain',\n 563: 'fountain pen',\n 564: 'four-poster',\n 565: 'freight car',\n 566: 'French horn, horn',\n 567: 'frying pan, frypan, skillet',\n 568: 'fur coat',\n 569: 'garbage truck, dustcart',\n 570: 'gasmask, respirator, gas helmet',\n 571: 'gas pump, gasoline pump, petrol pump, island dispenser',\n 572: 'goblet',\n 573: 'go-kart',\n 574: 'golf ball',\n 575: 'golfcart, golf cart',\n 576: 'gondola',\n 577: 'gong, tam-tam',\n 578: 'gown',\n 579: 'grand piano, grand',\n 580: 'greenhouse, nursery, glasshouse',\n 581: 'grille, radiator grille',\n 582: 'grocery store, grocery, food market, market',\n 583: 'guillotine',\n 584: 'hair slide',\n 585: 'hair spray',\n 586: 'half track',\n 587: 'hammer',\n 588: 'hamper',\n 589: 'hand blower, blow dryer, blow drier, hair dryer, hair drier',\n 590: 'hand-held computer, hand-held microcomputer',\n 591: 'handkerchief, hankie, hanky, hankey',\n 592: 'hard disc, hard disk, fixed disk',\n 593: 'harmonica, mouth organ, harp, mouth harp',\n 594: 'harp',\n 595: 'harvester, reaper',\n 596: 'hatchet',\n 597: 'holster',\n 598: 'home theater, home theatre',\n 599: 'honeycomb',\n 600: 'hook, claw',\n 601: 'hoopskirt, crinoline',\n 602: 'horizontal bar, high bar',\n 603: 'horse cart, horse-cart',\n 604: 'hourglass',\n 605: 'iPod',\n 606: 'iron, smoothing iron',\n 607: \"jack-o'-lantern\",\n 608: 'jean, blue jean, denim',\n 609: 'jeep, landrover',\n 610: 'jersey, T-shirt, tee shirt',\n 611: 'jigsaw puzzle',\n 612: 'jinrikisha, ricksha, rickshaw',\n 613: 'joystick',\n 614: 'kimono',\n 615: 'knee pad',\n 616: 'knot',\n 617: 'lab coat, laboratory coat',\n 618: 'ladle',\n 619: 'lampshade, lamp shade',\n 620: 'laptop, laptop computer',\n 621: 'lawn mower, mower',\n 622: 'lens cap, lens cover',\n 623: 'letter opener, paper knife, paperknife',\n 624: 'library',\n 625: 'lifeboat',\n 626: 'lighter, light, igniter, ignitor',\n 627: 'limousine, limo',\n 628: 'liner, ocean liner',\n 629: 'lipstick, lip rouge',\n 630: 'Loafer',\n 631: 'lotion',\n 632: 'loudspeaker, speaker, speaker unit, loudspeaker system, speaker system',\n 633: \"loupe, jeweler's loupe\",\n 634: 'lumbermill, sawmill',\n 635: 'magnetic compass',\n 636: 'mailbag, postbag',\n 637: 'mailbox, letter box',\n 638: 'maillot',\n 639: 'maillot, tank suit',\n 640: 'manhole cover',\n 641: 'maraca',\n 642: 'marimba, xylophone',\n 643: 'mask',\n 644: 'matchstick',\n 645: 'maypole',\n 646: 'maze, labyrinth',\n 647: 'measuring cup',\n 648: 'medicine chest, medicine cabinet',\n 649: 'megalith, megalithic structure',\n 650: 'microphone, mike',\n 651: 'microwave, microwave oven',\n 652: 'military uniform',\n 653: 'milk can',\n 654: 'minibus',\n 655: 'miniskirt, mini',\n 656: 'minivan',\n 657: 'missile',\n 658: 'mitten',\n 659: 'mixing bowl',\n 660: 'mobile home, manufactured home',\n 661: 'Model T',\n 662: 'modem',\n 663: 'monastery',\n 664: 'monitor',\n 665: 'moped',\n 666: 'mortar',\n 667: 'mortarboard',\n 668: 'mosque',\n 669: 'mosquito net',\n 670: 'motor scooter, scooter',\n 671: 'mountain bike, all-terrain bike, off-roader',\n 672: 'mountain tent',\n 673: 'mouse, computer mouse',\n 674: 'mousetrap',\n 675: 'moving van',\n 676: 'muzzle',\n 677: 'nail',\n 678: 'neck brace',\n 679: 'necklace',\n 680: 'nipple',\n 681: 'notebook, notebook computer',\n 682: 'obelisk',\n 683: 'oboe, hautboy, hautbois',\n 684: 'ocarina, sweet potato',\n 685: 'odometer, hodometer, mileometer, milometer',\n 686: 'oil filter',\n 687: 'organ, pipe organ',\n 688: 'oscilloscope, scope, cathode-ray oscilloscope, CRO',\n 689: 'overskirt',\n 690: 'oxcart',\n 691: 'oxygen mask',\n 692: 'packet',\n 693: 'paddle, boat paddle',\n 694: 'paddlewheel, paddle wheel',\n 695: 'padlock',\n 696: 'paintbrush',\n 697: \"pajama, pyjama, pj's, jammies\",\n 698: 'palace',\n 699: 'panpipe, pandean pipe, syrinx',\n 700: 'paper towel',\n 701: 'parachute, chute',\n 702: 'parallel bars, bars',\n 703: 'park bench',\n 704: 'parking meter',\n 705: 'passenger car, coach, carriage',\n 706: 'patio, terrace',\n 707: 'pay-phone, pay-station',\n 708: 'pedestal, plinth, footstall',\n 709: 'pencil box, pencil case',\n 710: 'pencil sharpener',\n 711: 'perfume, essence',\n 712: 'Petri dish',\n 713: 'photocopier',\n 714: 'pick, plectrum, plectron',\n 715: 'pickelhaube',\n 716: 'picket fence, paling',\n 717: 'pickup, pickup truck',\n 718: 'pier',\n 719: 'piggy bank, penny bank',\n 720: 'pill bottle',\n 721: 'pillow',\n 722: 'ping-pong ball',\n 723: 'pinwheel',\n 724: 'pirate, pirate ship',\n 725: 'pitcher, ewer',\n 726: \"plane, carpenter's plane, woodworking plane\",\n 727: 'planetarium',\n 728: 'plastic bag',\n 729: 'plate rack',\n 730: 'plow, plough',\n 731: \"plunger, plumber's helper\",\n 732: 'Polaroid camera, Polaroid Land camera',\n 733: 'pole',\n 734: 'police van, police wagon, paddy wagon, patrol wagon, wagon, black Maria',\n 735: 'poncho',\n 736: 'pool table, billiard table, snooker table',\n 737: 'pop bottle, soda bottle',\n 738: 'pot, flowerpot',\n 739: \"potter's wheel\",\n 740: 'power drill',\n 741: 'prayer rug, prayer mat',\n 742: 'printer',\n 743: 'prison, prison house',\n 744: 'projectile, missile',\n 745: 'projector',\n 746: 'puck, hockey puck',\n 747: 'punching bag, punch bag, punching ball, punchball',\n 748: 'purse',\n 749: 'quill, quill pen',\n 750: 'quilt, comforter, comfort, puff',\n 751: 'racer, race car, racing car',\n 752: 'racket, racquet',\n 753: 'radiator',\n 754: 'radio, wireless',\n 755: 'radio telescope, radio reflector',\n 756: 'rain barrel',\n 757: 'recreational vehicle, RV, R.V.',\n 758: 'reel',\n 759: 'reflex camera',\n 760: 'refrigerator, icebox',\n 761: 'remote control, remote',\n 762: 'restaurant, eating house, eating place, eatery',\n 763: 'revolver, six-gun, six-shooter',\n 764: 'rifle',\n 765: 'rocking chair, rocker',\n 766: 'rotisserie',\n 767: 'rubber eraser, rubber, pencil eraser',\n 768: 'rugby ball',\n 769: 'rule, ruler',\n 770: 'running shoe',\n 771: 'safe',\n 772: 'safety pin',\n 773: 'saltshaker, salt shaker',\n 774: 'sandal',\n 775: 'sarong',\n 776: 'sax, saxophone',\n 777: 'scabbard',\n 778: 'scale, weighing machine',\n 779: 'school bus',\n 780: 'schooner',\n 781: 'scoreboard',\n 782: 'screen, CRT screen',\n 783: 'screw',\n 784: 'screwdriver',\n 785: 'seat belt, seatbelt',\n 786: 'sewing machine',\n 787: 'shield, buckler',\n 788: 'shoe shop, shoe-shop, shoe store',\n 789: 'shoji',\n 790: 'shopping basket',\n 791: 'shopping cart',\n 792: 'shovel',\n 793: 'shower cap',\n 794: 'shower curtain',\n 795: 'ski',\n 796: 'ski mask',\n 797: 'sleeping bag',\n 798: 'slide rule, slipstick',\n 799: 'sliding door',\n 800: 'slot, one-armed bandit',\n 801: 'snorkel',\n 802: 'snowmobile',\n 803: 'snowplow, snowplough',\n 804: 'soap dispenser',\n 805: 'soccer ball',\n 806: 'sock',\n 807: 'solar dish, solar collector, solar furnace',\n 808: 'sombrero',\n 809: 'soup bowl',\n 810: 'space bar',\n 811: 'space heater',\n 812: 'space shuttle',\n 813: 'spatula',\n 814: 'speedboat',\n 815: \"spider web, spider's web\",\n 816: 'spindle',\n 817: 'sports car, sport car',\n 818: 'spotlight, spot',\n 819: 'stage',\n 820: 'steam locomotive',\n 821: 'steel arch bridge',\n 822: 'steel drum',\n 823: 'stethoscope',\n 824: 'stole',\n 825: 'stone wall',\n 826: 'stopwatch, stop watch',\n 827: 'stove',\n 828: 'strainer',\n 829: 'streetcar, tram, tramcar, trolley, trolley car',\n 830: 'stretcher',\n 831: 'studio couch, day bed',\n 832: 'stupa, tope',\n 833: 'submarine, pigboat, sub, U-boat',\n 834: 'suit, suit of clothes',\n 835: 'sundial',\n 836: 'sunglass',\n 837: 'sunglasses, dark glasses, shades',\n 838: 'sunscreen, sunblock, sun blocker',\n 839: 'suspension bridge',\n 840: 'swab, swob, mop',\n 841: 'sweatshirt',\n 842: 'swimming trunks, bathing trunks',\n 843: 'swing',\n 844: 'switch, electric switch, electrical switch',\n 845: 'syringe',\n 846: 'table lamp',\n 847: 'tank, army tank, armored combat vehicle, armoured combat vehicle',\n 848: 'tape player',\n 849: 'teapot',\n 850: 'teddy, teddy bear',\n 851: 'television, television system',\n 852: 'tennis ball',\n 853: 'thatch, thatched roof',\n 854: 'theater curtain, theatre curtain',\n 855: 'thimble',\n 856: 'thresher, thrasher, threshing machine',\n 857: 'throne',\n 858: 'tile roof',\n 859: 'toaster',\n 860: 'tobacco shop, tobacconist shop, tobacconist',\n 861: 'toilet seat',\n 862: 'torch',\n 863: 'totem pole',\n 864: 'tow truck, tow car, wrecker',\n 865: 'toyshop',\n 866: 'tractor',\n 867: 'trailer truck, tractor trailer, trucking rig, rig, articulated lorry, semi',\n 868: 'tray',\n 869: 'trench coat',\n 870: 'tricycle, trike, velocipede',\n 871: 'trimaran',\n 872: 'tripod',\n 873: 'triumphal arch',\n 874: 'trolleybus, trolley coach, trackless trolley',\n 875: 'trombone',\n 876: 'tub, vat',\n 877: 'turnstile',\n 878: 'typewriter keyboard',\n 879: 'umbrella',\n 880: 'unicycle, monocycle',\n 881: 'upright, upright piano',\n 882: 'vacuum, vacuum cleaner',\n 883: 'vase',\n 884: 'vault',\n 885: 'velvet',\n 886: 'vending machine',\n 887: 'vestment',\n 888: 'viaduct',\n 889: 'violin, fiddle',\n 890: 'volleyball',\n 891: 'waffle iron',\n 892: 'wall clock',\n 893: 'wallet, billfold, notecase, pocketbook',\n 894: 'wardrobe, closet, press',\n 895: 'warplane, military plane',\n 896: 'washbasin, handbasin, washbowl, lavabo, wash-hand basin',\n 897: 'washer, automatic washer, washing machine',\n 898: 'water bottle',\n 899: 'water jug',\n 900: 'water tower',\n 901: 'whiskey jug',\n 902: 'whistle',\n 903: 'wig',\n 904: 'window screen',\n 905: 'window shade',\n 906: 'Windsor tie',\n 907: 'wine bottle',\n 908: 'wing',\n 909: 'wok',\n 910: 'wooden spoon',\n 911: 'wool, woolen, woollen',\n 912: 'worm fence, snake fence, snake-rail fence, Virginia fence',\n 913: 'wreck',\n 914: 'yawl',\n 915: 'yurt',\n 916: 'web site, website, internet site, site',\n 917: 'comic book',\n 918: 'crossword puzzle, crossword',\n 919: 'street sign',\n 920: 'traffic light, traffic signal, stoplight',\n 921: 'book jacket, dust cover, dust jacket, dust wrapper',\n 922: 'menu',\n 923: 'plate',\n 924: 'guacamole',\n 925: 'consomme',\n 926: 'hot pot, hotpot',\n 927: 'trifle',\n 928: 'ice cream, icecream',\n 929: 'ice lolly, lolly, lollipop, popsicle',\n 930: 'French loaf',\n 931: 'bagel, beigel',\n 932: 'pretzel',\n 933: 'cheeseburger',\n 934: 'hotdog, hot dog, red hot',\n 935: 'mashed potato',\n 936: 'head cabbage',\n 937: 'broccoli',\n 938: 'cauliflower',\n 939: 'zucchini, courgette',\n 940: 'spaghetti squash',\n 941: 'acorn squash',\n 942: 'butternut squash',\n 943: 'cucumber, cuke',\n 944: 'artichoke, globe artichoke',\n 945: 'bell pepper',\n 946: 'cardoon',\n 947: 'mushroom',\n 948: 'Granny Smith',\n 949: 'strawberry',\n 950: 'orange',\n 951: 'lemon',\n 952: 'fig',\n 953: 'pineapple, ananas',\n 954: 'banana',\n 955: 'jackfruit, jak, jack',\n 956: 'custard apple',\n 957: 'pomegranate',\n 958: 'hay',\n 959: 'carbonara',\n 960: 'chocolate sauce, chocolate syrup',\n 961: 'dough',\n 962: 'meat loaf, meatloaf',\n 963: 'pizza, pizza pie',\n 964: 'potpie',\n 965: 'burrito',\n 966: 'red wine',\n 967: 'espresso',\n 968: 'cup',\n 969: 'eggnog',\n 970: 'alp',\n 971: 'bubble',\n 972: 'cliff, drop, drop-off',\n 973: 'coral reef',\n 974: 'geyser',\n 975: 'lakeside, lakeshore',\n 976: 'promontory, headland, head, foreland',\n 977: 'sandbar, sand bar',\n 978: 'seashore, coast, seacoast, sea-coast',\n 979: 'valley, vale',\n 980: 'volcano',\n 981: 'ballplayer, baseball player',\n 982: 'groom, bridegroom',\n 983: 'scuba diver',\n 984: 'rapeseed',\n 985: 'daisy',\n 986: \"yellow lady's slipper, yellow lady-slipper, Cypripedium calceolus, Cypripedium parviflorum\",\n 987: 'corn',\n 988: 'acorn',\n 989: 'hip, rose hip, rosehip',\n 990: 'buckeye, horse chestnut, conker',\n 991: 'coral fungus',\n 992: 'agaric',\n 993: 'gyromitra',\n 994: 'stinkhorn, carrion fungus',\n 995: 'earthstar',\n 996: 'hen-of-the-woods, hen of the woods, Polyporus frondosus, Grifola frondosa',\n 997: 'bolete',\n 998: 'ear, spike, capitulum',\n 999: 'toilet tissue, toilet paper, bathroom tissue'}\n```\n\n\n```python\n# @title Map Imagenette Labels to Imagenet Labels\ndir_to_imagenet_index = {\n 'n03888257': 1,\n 'n03425413': 571,\n 'n03394916': 566,\n 'n03000684': 491,\n 'n02102040': 217,\n 'n03445777': 574,\n 'n03417042': 569,\n 'n03028079': 497,\n 'n02979186': 482,\n 'n01440764': 701\n }\n\ndir_index_to_imagenet_label = {}\nordered_dirs = sorted(list(dir_to_imagenet_index.keys()))\n\nfor dir_index, dir_name in enumerate(ordered_dirs):\n dir_index_to_imagenet_label[dir_index] = dir_to_imagenet_index[dir_name]\n```\n\n\n```python\n# @title Prepare Imagenette Data\nval_transform = transforms.Compose((transforms.Resize((256, 256)),\n transforms.ToTensor()))\n\nimagenette_val = ImageFolder('imagenette2-320/val', transform=val_transform)\n\ntrain_transform = transforms.Compose((transforms.Resize((256, 256)),\n transforms.ToTensor()))\n\nimagenette_train = ImageFolder('imagenette2-320/train',\n transform=train_transform)\nrandom.seed(SEED)\nrandom_indices = random.sample(range(len(imagenette_train)), 400)\nimagenette_train_subset = torch.utils.data.Subset(imagenette_train,\n random_indices)\n\n\n\n\n# Subset to only one tenth of the data for faster runtime\nrandom_indices = random.sample(range(len(imagenette_val)), int(len(imagenette_val) * .1))\nimagenette_val = torch.utils.data.Subset(imagenette_val, random_indices)\n```\n\n\n```python\nimagenette_train_loader = torch.utils.data.DataLoader(imagenette_train_subset,\n batch_size=16,\n shuffle=True)\n\nimagenette_val_loader = torch.utils.data.DataLoader(imagenette_val,\n batch_size=16,\n shuffle=False)\n\ndataiter = iter(imagenette_val_loader)\nimages, labels = dataiter.next()\n\n# show images\nplt.figure(figsize=(8, 8))\nplt.imshow(make_grid(images, nrow=4).permute(1, 2, 0))\n```\n\n\n```python\n# @title eval_imagenette function\ndef eval_imagenette(resnet, data_loader, dataset_length):\n resnet.eval()\n with torch.no_grad():\n loss_sum = 0\n total_1_correct = 0\n total_5_correct = 0\n total = dataset_length\n for batch in tqdm.notebook.tqdm(data_loader):\n images, labels = batch\n\n # Map the imagenette labels onto the network's output\n for i, label in enumerate(labels):\n labels[i] = dir_index_to_imagenet_label[label.item()]\n\n images = images.to(DEVICE)\n labels = labels.to(DEVICE)\n output = resnet(images)\n\n # Calculate top-5 accuracy\n # Implementation from https://github.com/bearpaw/pytorch-classification/blob/cc9106d598ff1fe375cc030873ceacfea0499d77/utils/eval.py\n batch_size = labels.size(0)\n\n _, predictions = output.topk(5, 1, True, True)\n predictions = predictions.t()\n\n top_k_correct = predictions.eq(labels.view(1, -1).expand_as(predictions))\n top_k_correct = top_k_correct.sum()\n\n predictions = torch.argmax(output, dim=1)\n top_1_correct = torch.sum(predictions == labels)\n total_1_correct += top_1_correct\n total_5_correct += top_k_correct\n\n top_1_acc = total_1_correct / total\n top_5_acc = total_5_correct / total\n\n return top_1_acc, top_5_acc\n```\n\n\n```python\n# @title Imagenette Train Loop\ndef imagenette_train_loop(model, optimizer, train_loader, loss_fn):\n loss_fn = nn.CrossEntropyLoss()\n for epoch in tqdm.notebook.tqdm(range(5)):\n # Set model to use the imagenette classifier head\n model.train()\n # Train on a batch of images\n for imagenette_batch in train_loader:\n images, labels = imagenette_batch\n\n # Convert labels from imagenette indices to imagenet labels\n for i, label in enumerate(labels):\n labels[i] = dir_index_to_imagenet_label[label.item()]\n\n images = images.to(DEVICE)\n labels = labels.to(DEVICE)\n output = model(images)\n optimizer.zero_grad()\n loss = loss_fn(output, labels)\n loss.backward()\n optimizer.step()\n\n return model\n```\n\nThis cell creates a ResNet model pretrained on [ImageNet](http://www.image-net.org/), a 1000 class image prediction dataset. The model is then trained to make predictions on [Imagenette](https://github.com/fastai/imagenette), a small subset of ImageNet classes that is useful for demonstrations and prototyping.\n\n\n```python\n# Original network\ntop_1_accuracies = []\ntop_5_accuracies = []\n\n# Instantiate a pretrained resnet model\nset_seed(seed=SEED)\nresnet = torchvision.models.resnet18(pretrained=True).to(DEVICE)\nresnet_opt = torch.optim.Adam(resnet.parameters(), lr=1e-4)\nloss_fn = nn.CrossEntropyLoss()\n\nimagenette_train_loop(resnet,\n resnet_opt,\n imagenette_train_loader,\n loss_fn)\n\ntop_1_acc, top_5_acc = eval_imagenette(resnet,\n imagenette_val_loader,\n len(imagenette_val))\ntop_1_accuracies.append(top_1_acc.item())\ntop_5_accuracies.append(top_5_acc.item())\n```\n\n## Coding Exercise 4.1: Use the ResNet model\n\nComplete the function below that runs a batch of images through the trained ResNet and returns the Top 5 class predictions and their probabilities. Note that the ResNet model returns unnormalized logits$^\\dagger$. To obtain probabilities, you need to normalize the logits using softmax.\n\n
\n\n$^\\dagger$ $ \\text{logit}(p) = \\sigma^{-1}(p) = \\text{log} \\left( \\frac{p}{1-p} \\right), \\, \\text{for} \\, p \\in (0,1)$, where $\\sigma(\\cdot)$ is the sigmoid function, i.e., $\\sigma(z) = 1/(1+e^{-z})$. For more information see [here](http://machinelearningmechanic.com/deep_learning/2019/09/04/cross-entropy-loss-derivative.html).\n\n\n```python\ndef predict_top5(images, device):\n \"\"\"\n Args:\n images: torch Tensor with dimensionality B x C x H x W\n (batch size x number of channels x height x width)\n device: STRING\n `cuda` if GPU is available, else `cpu`.\n Output:\n top5_probs: torch Tensor (B, 5) with top 5 class probabilities\n top5_names: list of top 5 class names (B, 5)\n \"\"\"\n ####################################################################\n # Fill in all missing code below (...),\n # then remove or comment the line below to test your function\n raise NotImplementedError(\"Predict top 5\")\n ####################################################################\n\n B = images.size(0)\n with torch.no_grad():\n # Run images through model\n images = ...\n output = ...\n # The model output is unnormalized. To get probabilities, run a softmax on it.\n probs = ...\n # Fetch output from GPU and convert to numpy array\n probs = ...\n\n # Get top 5 predictions\n _, top5_idcs = output.topk(5, 1, True, True)\n top5_idcs = top5_idcs.t().cpu().numpy()\n top5_probs = probs[torch.arange(B), top5_idcs]\n\n # Convert indices to class names\n top5_names = []\n for b in range(B):\n temp = [dict_map[key].split(',')[0] for key in top5_idcs[:,b]]\n top5_names.append(temp)\n\n return top5_names, top5_probs\n\n\nset_seed(seed=2021)\n# get batch of images\ndataiter = iter(imagenette_val_loader)\nimages, labels = dataiter.next()\n\n## Uncomment to test your function\n## retrieve top 5 predictions\n# top5_names, top5_probs = predict_top5(images, DEVICE)\n# print(top5_names[1])\n```\n\n\n```python\n# to_remove solution\ndef predict_top5(images, device):\n \"\"\"\n Args:\n images: torch Tensor with dimensionality B x C x H x W\n (batch size x number of channels x height x width)\n device: STRING\n `cuda` if GPU is available, else `cpu`.\n Output:\n top5_probs: torch Tensor (B, 5) with top 5 class probabilities\n top5_names: list of top 5 class names (B, 5)\n \"\"\"\n B = images.size(0)\n with torch.no_grad():\n # Run images through model\n images = images.to(device)\n output = resnet(images)\n # The model output is unnormalized. To get probabilities, run a softmax on it.\n probs = torch.nn.functional.softmax(output, dim=1)\n # Fetch output from GPU and convert to numpy array\n probs = probs.cpu().numpy()\n\n # Get top 5 predictions\n _, top5_idcs = output.topk(5, 1, True, True)\n top5_idcs = top5_idcs.t().cpu().numpy()\n top5_probs = probs[torch.arange(B), top5_idcs]\n\n # Convert indices to class names\n top5_names = []\n for b in range(B):\n temp = [dict_map[key].split(',')[0] for key in top5_idcs[:,b]]\n top5_names.append(temp)\n\n return top5_names, top5_probs\n\n\nset_seed(seed=2021)\n# get batch of images\ndataiter = iter(imagenette_val_loader)\nimages, labels = dataiter.next()\n\n## Uncomment to test your function\n## retrieve top 5 predictions\ntop5_names, top5_probs = predict_top5(images, DEVICE)\nprint(top5_names[1])\n```\n\n```\nRandom seed 2021 has been set.\n['gas pump', 'chain saw', 'French horn', 'rifle', 'forklift']\n```\n\n\n```python\n# visualize probabilities of top 5 predictions\nfig, ax = plt.subplots(5, 2, figsize=(10, 20))\n\nfor i in range(5):\n ax[i, 0].imshow(np.moveaxis(images[i].numpy(), 0, -1))\n ax[i, 0].axis('off')\n\n ax[i, 1].bar(np.arange(5), top5_probs[:, i])\n ax[i, 1].set_xticks(np.arange(5))\n ax[i, 1].set_xticklabels(top5_names[i], rotation=30)\n\nfig.tight_layout()\nplt.show()\n```\n\n## Out-of-distribution examples\n\nThe code below runs two out-of-distribution examples through the trained ResNet. Look at the predictions and discuss, why the model might fail to make accurate predictions on these images. \n\n\n```python\nresponse = requests.get('https://designlooter.com/images/bonsai-svg-5.png')\nimage = Image.open(BytesIO(response.content)).resize((256, 256))\ndata = torch.from_numpy(np.asarray(image)[:, :, :3]) / 255.\n\nresponse = requests.get('https://upload.wikimedia.org/wikipedia/en/a/a6/Pokémon_Pikachu_art.png')\nimage = Image.open(BytesIO(response.content)).resize((256, 256))\ndata2 = torch.from_numpy(np.asarray(image)[:, :, :3]) / 255.\n\nimages = torch.stack([data, data2]).permute(0, 3, 1, 2)\n```\n\n\n```python\n# retrieve top 5 predictions\ntop5_names, top5_probs = predict_top5(images, DEVICE)\n```\n\n\n```python\n# visualize probabilities of top 5 predictions\nfig, ax = plt.subplots(2, 2, figsize=(10, 10))\n\nfor i in range(2):\n ax[i, 0].imshow(np.moveaxis(images[i].numpy(), 0, -1))\n ax[i, 0].axis('off')\n\n ax[i, 1].bar(np.arange(5), top5_probs[:, i])\n ax[i, 1].set_xticks(np.arange(5))\n ax[i, 1].set_xticklabels(top5_names[i], rotation=30)\n\nfig.tight_layout()\nplt.show()\n```\n\n---\n# Section 5: Inception + ResNeXt\n\n\n```python\n# @title Video 5: Improving efficiency: Inceptrion and ResNeXt\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1Zq4y1W7Px\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"TDHn7X1wNQ4\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\ndisplay(out)\n```\n\n[ResNet vs ResNeXt](https://arxiv.org/abs/1611.05431)\n\n\n\n\n## Interactive Demo 5: ResNet vs. ResNeXt\n\nThe widgets below calculate the number of parameters in a ResNet (top) and the parameters in a ResNeXt (bottom). We assume that the number of input and output channels (or feature maps) is the same (labeled \"Channels in+out\" in the widget). We refer to the number of channels after the first and the second layer of one block of either ResNet or ResNeXt as \"bottleneck channels\".\n\nThe sliders are currently in the position that is displayed in the figure above. The goal of the following tasks is to investigate the difference in expressiveness and numbers of parameters in ResNet and ResNeXt.\n\n\n```python\n# @title Parameter Calculator\n# @markdown ##### Run this cell to enable the widget\nfrom IPython.display import display as dis\n\ndef calculate_parameters_resnet(d_in, resnet_channels):\n # ResNet math: Implement how parameters scale\n d_out = d_in\n resnet_parameters = d_in*resnet_channels + 3*3*resnet_channels*resnet_channels + resnet_channels*d_out\n\n print('ResNet parameters: {}'.format(resnet_parameters))\n return None\n\n\ndef calculate_parameters_resnext(d_in, resnext_channels, num_paths):\n # ResNet math: Implement how parameters scale\n d_out = d_in\n d = resnext_channels\n\n resnext_parameters = (d_in*d + 3*3*d*d + d*d_out)*num_paths\n\n print('ResNeXt parameters: {}'.format(resnext_parameters))\n return None\n\n\nlabels = ['ResNet', 'ResNeXt']\ndescriptions_resnet = ['Channels in+out', 'Bottleneck channels']\ndescriptions_resnext = ['Channels in+out', 'Bottleneck channels',\n 'Number of paths (cardinality)']\nlbox_resnet = widgets.VBox([widgets.Label(description) for description in descriptions_resnet])\nlbox_resnext = widgets.VBox([widgets.Label(description) for description in descriptions_resnext])\n\nd_in = widgets.FloatLogSlider(\n value=256,\n base=2,\n min=1, # max exponent of base\n max=10, # min exponent of base\n step=1, # exponent step\n)\nresnet_channels = widgets.FloatLogSlider(\n value=64,\n base=2,\n min=5, # max exponent of base\n max=10, # min exponent of base\n step=1, # exponent step\n)\nresnext_channels = widgets.FloatLogSlider(\n value=4,\n base=2,\n min=1, # max exponent of base\n max=10, # min exponent of base\n step=1, # exponent step\n)\nnum_paths = widgets.FloatLogSlider(\n value=32,\n base=2,\n min=0, # max exponent of base\n max=7, # min exponent of base\n step=1, # exponent step\n)\n\nrbox_resnet = widgets.VBox([d_in, resnet_channels])\nrbox_resnext = widgets.VBox([d_in, resnext_channels, num_paths])\nui_resnet = widgets.HBox([lbox_resnet, rbox_resnet])\nui_resnet_labeled = widgets.VBox(\n [widgets.HTML(value=\"\" + labels[0] + \"\"), ui_resnet],\n layout=widgets.Layout(border='1px solid black'))\nui_resnext = widgets.HBox([lbox_resnext, rbox_resnext])\nui_resnext_labeled = widgets.VBox(\n [widgets.HTML(value=\"\" + labels[1] + \"\"), ui_resnext],\n layout=widgets.Layout(border='1px solid black'))\nui = widgets.VBox([ui_resnet_labeled, ui_resnext_labeled])\n\nout_resnet = widgets.interactive_output(calculate_parameters_resnet,\n {'d_in':d_in,\n 'resnet_channels':resnet_channels})\n\nout_resnext = widgets.interactive_output(calculate_parameters_resnext,\n {'d_in':d_in,\n 'resnext_channels':resnext_channels,\n 'num_paths':num_paths})\n\nd1 = dis(ui, out_resnet, out_resnext)\n```\n\n**Why there is $1 \\times 1$ convolution?**\n\nA $1 \\times 1$ convolution matrix essentially squashes the depth dimension of an input volume, $W \\times H \\times D$, leaving its width and height intact, $W \\times H \\times 1$.\n\n## Exercise 5: ResNet vs. ResNeXt\n\nIn the figure above, both networks – ResNet and ResNeXt – have a similar number of parameters. \n\n1. How many channels are there in the bottleneck of the two networks, respectively?\n1. How are these channels connected to each other from the first to the second layer in the blocks of the two networks, respectively? \n1. What does it mean for the expressiveness of the two models relative to each other?\n\n\n```python\n# to_remove explanation\n\n\"\"\"\n1. The ResNeXt has 32 * 4 = 128 channels in the bottleneck, whereas the ResNet has only 64.\n\n2. In ResNet all 64 output channels of the first layer are connected to all 64 output channels of the second layer.\nIn ResNeXt, channels are connected only within paths, i.e. in groups of 4.\n\n3. ResNeXt contains more channels in the bottleneck (potentially more expressive),\n but each of them \"sees\" only a subset of the previous layer's output (potentially less expressive).\n The former tends to outweigh the latter, which is why the ResNeXt architecture tends to outperform the\n vanilla ResNet architecture.\n\"\"\"\n```\n\nNow we want to look at the number of parameters.\n* How does the difference in number of parameters change if we fix the number of channels in the bottleneck of both ResNet and ResNeXt to be 64, but vary the number of paths in ResNeXt? (8 paths with 8 channels each would be one such example)\n* Which number of paths results in the biggest parameter savings?\n\n\n\n```python\n# to_remove explanation\n\n\"\"\"\n -- if number of paths=1 and channels per path=64 -> same architecture as ResNet, no parameter saving\n -- if number of paths=8 and channels per path=8 -> around half the number of parameters\n -- if number of paths=32 and channels per path=2 -> biggest parameter saving the more paths, the more saving\n\"\"\"\n```\n\n---\n# Section 6: Depthwise separable convolutions\n\n\n```python\n# @title Video 6: Improving efficiency: MobileNet\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1D44y127fS\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"kdbGpn1JfmU\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\ndisplay(out)\n```\n\n## Section 6.1: Depthwise separable convolutions\n\nAnother way to reduce the computational cost of large models is the use of depthwise separable convolutions ([introduced here](https://www.di.ens.fr/data/publications/papers/phd_sifre.pdf)). Depthwise separable convolutions are the key component making [MobileNets](https://arxiv.org/abs/1704.04861) efficient.\n\n\n\n### Coding Exercise 6.1: Calculation of parameters\n\nFill in the calculation of the parameters of regular convolution and depthwise separable convolution in the function below.\nAbove you can see the example given in the video for you to check if your calculation is correct.\n\n\n```python\ndef convolution_math(in_features, filter_size, out_features):\n \"\"\"\n Convolution math: Implement how parameters scale as a function of feature maps\n and filter size in convolution vs depthwise separable convolution.\n\n Args:\n in_features: number of input features\n filter_size: size of the filter\n out_features: number of output features\n \"\"\"\n ####################################################################\n # Fill in all missing code below (...),\n # then remove or comment the line below to test your function\n raise NotImplementedError(\"Convolution math\")\n ####################################################################\n # calculate the number of parameters for regular convolution\n conv_parameters = ...\n # calculate the number of parameters for depthwise separable convolution\n depthwise_conv_parameters = ...\n\n print('Depthwise separable: {} parameters'.format(depthwise_conv_parameters))\n print('Regular convolution: {} parameters'.format(conv_parameters))\n\n return None\n\n\n## Uncomment to test your function\n# convolution_math(in_features=4, filter_size=3, out_features=2)\n```\n\n\n```python\n# to_remove solution\ndef convolution_math(in_features, filter_size, out_features):\n \"\"\"\n Convolution math: Implement how parameters scale as a function of feature maps\n and filter size in convolution vs depthwise separable convolution.\n\n Args:\n in_features: number of input features\n filter_size: size of the filter\n out_features: number of output features\n \"\"\"\n # calculate the number of parameters for regular convolution\n conv_parameters = in_features * filter_size * filter_size * out_features\n # calculate the number of parameters for depthwise separable convolution\n depthwise_conv_parameters = in_features * filter_size * filter_size + in_features * out_features\n\n print('Depthwise separable: {} parameters'.format(depthwise_conv_parameters))\n print('Regular convolution: {} parameters'.format(conv_parameters))\n\n return None\n\n\n## Uncomment to test your function\nconvolution_math(in_features=4, filter_size=3, out_features=2)\n```\n\n```\nDepthwise separable: 44 parameters\nRegular convolution: 72 parameters\n```\n\n### Think! 6.1: How do parameter savings depend the on number of input feature maps, 4 vs. 64?\n\n\n```python\n# to_remove explanation\n\n\"\"\"\nThe more input features the more parameter saving\n 4: 28 less params\n 64: 448 less params\n\"\"\"\n```\n\n---\n# Section 7: Transfer Learning\n\n\n\n\n\n```python\n# @title Video 7: Transfer Learning\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1z54y1E714\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"Qr5l-an5ac4\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\ndisplay(out)\n```\n\nThe most common way large image models are trained in practice is via transfer learning. One first pretrains a network on a large classification dataset like ImageNet, then uses the weights of this network as initialization for training (\"fine-tuning\") that network on your task of choice. \n\nWhile training a network twice sounds like a strange thing to do, the model ends up training faster on the target dataset and often outperforms training \"from scratch\". There are also other benefits such as [robustness to noise](https://arxiv.org/pdf/1901.09960.pdf) that are the subject of [active research](https://arxiv.org/abs/2008.11687).\n\nIn this section we will demonstrate transfer learning by taking a model trained on ImageNet and teaching it to classify Pokemon.\n\n## Section 7.1: Download and prepare the data\n\n\n```python\n# @title Download Data\n!git clone --quiet https://github.com/ben-heil/cis_522_data.git\n!tar -xzf cis_522_data/archive.tar.gz\n!tar -xzf cis_522_data/faces.tar.gz\n```\n\n\n```python\n# List the different Pokemon\n!ls small_pokemon_dataset/\n```\n\n\n```python\n# @title Determine number of classes\nnum_classes = 0\nfor folders in os.listdir('small_pokemon_dataset/'):\n num_classes += 1\nprint(num_classes, 'types of Pokemon')\n```\n\n\n```python\n# @title Display Example Images\ntrain_transform = transforms.Compose((transforms.Resize((256, 256)),\n transforms.ToTensor()))\n\npokemon_dataset = ImageFolder('small_pokemon_dataset',\n transform=train_transform)\n\nimage_count = len(pokemon_dataset)\ntrain_indices = []\ntest_indices = []\nfor i in range(image_count):\n # Put ten percent of the images in the test set\n if random.random() < .1:\n test_indices.append(i)\n else:\n train_indices.append(i)\n\npokemon_test_set = torch.utils.data.Subset(pokemon_dataset, test_indices)\npokemon_train_set = torch.utils.data.Subset(pokemon_dataset, train_indices)\n\npokemon_train_loader = torch.utils.data.DataLoader(pokemon_train_set,\n batch_size=16,\n shuffle=True,)\npokemon_test_loader = torch.utils.data.DataLoader(pokemon_test_set,\n batch_size=16)\n\ndataiter = iter(pokemon_train_loader)\nimages, labels = dataiter.next()\n\n# show images\nplt.imshow(make_grid(images, nrow=4).permute(1,2,0))\n```\n\n## Section 7.2: Fine-tuning a ResNet\n\nIt is common in computer vision to take a large model trained on a large dataset (often ImageNet), replace the classification layer and fine-tune the entire network to perform a different task. \n\nHere we'll be using a pre-trained ResNet model to classify types of Pokemon.\n\n\n```python\nresnet = torchvision.models.resnet18(pretrained=True)\nnum_ftrs = resnet.fc.in_features\n# reset final fully connected layer, number of classes = types of Pokemon = 9\nresnet.fc = nn.Linear(num_ftrs, num_classes)\nresnet.to(DEVICE)\noptimizer = torch.optim.Adam(resnet.parameters(), lr=1e-4)\nloss_fn = nn.CrossEntropyLoss()\n```\n\n\n```python\n# @title Finetune ResNet\n\npretrained_accs = []\nfor epoch in range(10):\n # Train loop\n for batch in pokemon_train_loader:\n images, labels = batch\n images = images.to(DEVICE)\n labels = labels.to(DEVICE)\n\n optimizer.zero_grad()\n output = resnet(images)\n loss = loss_fn(output, labels)\n loss.backward()\n optimizer.step()\n\n # Eval loop\n with torch.no_grad():\n loss_sum = 0\n total_correct = 0\n total = len(pokemon_test_set)\n for batch in pokemon_test_loader:\n images, labels = batch\n images = images.to(DEVICE)\n labels = labels.to(DEVICE)\n output = resnet(images)\n loss = loss_fn(output, labels)\n loss_sum += loss.item()\n\n predictions = torch.argmax(output, dim=1)\n\n num_correct = torch.sum(predictions == labels)\n total_correct += num_correct\n\n # Plot accuracy\n pretrained_accs.append(total_correct / total)\n plt.plot(pretrained_accs)\n plt.xlabel('epoch')\n plt.ylabel('accuracy')\n plt.title('Pokemon prediction accuracy')\n IPython.display.clear_output(wait=True)\n IPython.display.display(plt.gcf())\n plt.close()\n```\n\n## Section 7.3: Train only classification layer\n\nAnother possible way to make use of transfer learning is to take a pre-trained model and replace the last layer, the classification layer (sometimes also called the \"linear readout\"). Instead of fine-tuning the whole model as before, we train only the classification layer.\n\n\n```python\nresnet = torchvision.models.resnet18(pretrained=True)\nfor param in resnet.parameters():\n param.requires_grad = False\nnum_ftrs = resnet.fc.in_features\n# reset final fully connected layer\nresnet.fc = nn.Linear(num_ftrs, num_classes)\nresnet.to(DEVICE)\noptimizer = torch.optim.Adam(resnet.fc.parameters(), lr=1e-2)\nloss_fn = nn.CrossEntropyLoss()\n```\n\n\n```python\n# @title Finetune readout of ResNet\nlinreadout_accs = []\nfor epoch in range(10):\n # Train loop\n for batch in pokemon_train_loader:\n images, labels = batch\n images = images.to(DEVICE)\n labels = labels.to(DEVICE)\n\n optimizer.zero_grad()\n output = resnet(images)\n loss = loss_fn(output, labels)\n loss.backward()\n optimizer.step()\n\n # Eval loop\n with torch.no_grad():\n loss_sum = 0\n total_correct = 0\n total = len(pokemon_test_set)\n for batch in pokemon_test_loader:\n images, labels = batch\n images = images.to(DEVICE)\n labels = labels.to(DEVICE)\n output = resnet(images)\n loss = loss_fn(output, labels)\n loss_sum += loss.item()\n\n predictions = torch.argmax(output, dim=1)\n\n num_correct = torch.sum(predictions == labels)\n total_correct += num_correct\n\n # Plot accuracy\n linreadout_accs.append(total_correct / total)\n plt.plot(linreadout_accs)\n plt.xlabel('epoch')\n plt.ylabel('accuracy')\n plt.title('Pokemon prediction accuracy')\n IPython.display.clear_output(wait=True)\n IPython.display.display(plt.gcf())\n plt.close()\n```\n\n## Section 7.4: Training ResNet from scratch\n\nAs a baseline and for comparison reasons we will also train the ResNet \"from scratch\" – that is: initialize the weights randomly and train the entire network exclusively on the Pokemon dataset.\n\n\n```python\nresnet = torchvision.models.resnet18(pretrained=False)\nnum_ftrs = resnet.fc.in_features\n# reset final fully connected layer\nresnet.fc = nn.Linear(num_ftrs, num_classes)\nresnet.to(DEVICE)\noptimizer = torch.optim.Adam(resnet.parameters(), lr=1e-4)\n\nloss_fn = nn.CrossEntropyLoss()\n```\n\n\n```python\n# @title Train ResNet from scratch\nscratch_accs = []\nfor epoch in range(10):\n # Train loop\n for batch in pokemon_train_loader:\n images, labels = batch\n images = images.to(DEVICE)\n labels = labels.to(DEVICE)\n\n optimizer.zero_grad()\n output = resnet(images)\n loss = loss_fn(output, labels)\n loss.backward()\n optimizer.step()\n\n # Eval loop\n with torch.no_grad():\n loss_sum = 0\n total_correct = 0\n total = len(pokemon_test_set)\n for batch in pokemon_test_loader:\n images, labels = batch\n images = images.to(DEVICE)\n labels = labels.to(DEVICE)\n output = resnet(images)\n loss = loss_fn(output, labels)\n loss_sum += loss.item()\n\n predictions = torch.argmax(output, dim=1)\n\n num_correct = torch.sum(predictions == labels)\n total_correct += num_correct\n\n scratch_accs.append(total_correct / total)\n plt.plot(scratch_accs)\n plt.xlabel('epoch')\n plt.ylabel('accuracy')\n plt.title('Pokemon prediction accuracy')\n\n IPython.display.clear_output(wait=True)\n IPython.display.display(plt.gcf())\n plt.close()\n```\n\n## Section 7.5: Head to Head Comparison\nStarting from a randomly initialized network works less well, especially in the case of small datsets. Note that the model converges more slowly and less evenly.\n\n\n```python\n# @title Plot Accuracies\nplt.plot(pretrained_accs, label='Pretrained: fine-tuning')\nplt.plot(linreadout_accs, label='Pretrained: linear Readout')\nplt.plot(scratch_accs, label='Trained from Scratch')\nplt.title('Pokemon prediction accuracy')\nplt.legend()\nplt.show()\n```\n\n### Exercise 7.5.1\n\nFirst, we compare the Pretrained ResNet with the ResNet trained from scratch. Why might pretrained models outperform models trained from scratch? In what cases would you expect them to be worse?\n\n\n```python\n# to_remove explanation\n\n\"\"\"\n1. The closer your pretraining and target data domains are, the better pretraining will work\n2. The more pretraining data you have, the better pretraining will work\n3. The better your model is able to take advantage of your pretraining data (that is to say\n the larger your model is asResNetsuming you have enough data), the better pretraing will work\n\nPretraining isn't necessarily always a benefit though. If you source domain is very different from\nthe domain you're trying to predict, your models might learn unhelpful features.\n\nAdditionally, if you have a lot of training data in your target domain, pretraining data might\ncause your model to converge to a local minimum (this process is referred to as ossification in\nthe Scaling Laws for Transfer paper cited in the Further Reading section)\n\"\"\"\n```\n\n### Exercise 7.5.2\n\nSecond, take a look at the different transfer learning methods - fine-tuning the whole network and training only the classification layer. Why might fine-tuning the whole network outperform training only the classification layer? What are the benefits of training only the classification layer? In what cases would you expect a similar performance of both methods?\n\n\n```python\n# to_remove explanation\n\n\"\"\"\n1. More weights are adjusted to the pretraining domain.\n2. Since only one layer is trained, the training procedure is faster/less computationally expensive.\n3. If your pretraining and target data domains are close.\n\"\"\"\n```\n\n## Further Reading\nSupervised pretraining as you've seen here is useful, but there are several other ways of using outside data to improve your models. The ones that are particularly popular right now are self-supervised techniques like [contrastive learning](https://arxiv.org/pdf/2002.05709.pdf).\n\nThere is also a [recent paper](https://arxiv.org/abs/2102.01293) that seeks to quantify the relationship between model size, pretraining dataset size, training dataset size, and performance.\n\n---\n# Section 8: Speed-Accuracy Trade-Off / Different Backbones\n\n\n\n```python\n# @title Video 8: Speed-accuracy trade-off\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1v64y1z7PT\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"9p4gD-QnbIQ\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\ndisplay(out)\n```\n\nAs the models got larger and the number of connections increased so did the computational costs involved. In the modern era of image processing, there is a tradeoff between model performance and computational cost. Models can reach extremely high performance on many problems, but achieving state of the art results requires [huge amounts of compute power](https://arxiv.org/pdf/1810.00736.pdf).\n\n\n\n## Coding Exercise 8.1: Compare accuracy and training speed of different models\n\nThe goal is to load three pretrained models and fine-tune them.\n`models` is a dictionary where the keys are the names of the models and the values are the corresponding model objects.\nCurrently the names are *ResNet18, AlexNet* and *VGG-19*.\nFor a start, load these models from torchvision.models and make sure they are pretrained.\n\nIf you want to try other models, just change the dictionary, or if you want to even try out more than three models, just add them to the dictionary and add their learning rates in the array below.\n\n\n```python\n# load three pretrained models from torchvision.models\n# [these are just examples, other models are possible as well]\nmodel1 = ...\nmodel2 = ...\nmodel3 = ...\n\nmodels = {'...': model1, '...': model2, '...-19': model3}\nlearning_rates = [1e-4, 1e-4, 1e-4]\n\ntimes, top_1_accuracies = [], []\n```\n\n\n```python\n# to_remove solution\n# load three pretrained models from torchvision.models\n# [these are just examples, other models are possible as well]\nmodel1 = torchvision.models.resnet18(pretrained=True)\nmodel2 = torchvision.models.alexnet(pretrained=True)\nmodel3 = torchvision.models.vgg19(pretrained=True)\n\nmodels = {'ResNet18': model1, 'AlexNet': model2, 'VGG-19': model3}\nlearning_rates = [1e-4, 1e-4, 1e-4]\n\ntimes, top_1_accuracies = [], []\n```\n\n\n```python\n# @title Imagenette Train Loop\ndef train_loop(model, optimizer, train_loader, loss_fn, device):\n\n times = []\n model.to(device)\n for epoch in tqdm.notebook.tqdm(range(5)):\n model.train()\n t_start = time.time()\n # Train on a batch of images\n for imagenette_batch in train_loader:\n images, labels = imagenette_batch\n\n # Convert labels from imagenette indices to imagenet labels\n for i, label in enumerate(labels):\n labels[i] = dir_index_to_imagenet_label[label.item()]\n\n images = images.to(device)\n labels = labels.to(device)\n output = model(images)\n optimizer.zero_grad()\n loss = loss_fn(output, labels)\n loss.backward()\n optimizer.step()\n if torch.cuda.is_available():\n torch.cuda.synchronize()\n\n times+= [time.time() - t_start]\n\n return np.mean(times)\n```\n\n\n```python\nDEVICE = set_device()\nfor (name, model), lr in zip(models.items(), learning_rates):\n\n print(name, lr)\n\n model.to(DEVICE)\n model.aux_logits = False # only important for googlenet\n\n optimizer = torch.optim.Adam(model.parameters(), lr=lr)\n loss_fn = nn.CrossEntropyLoss()\n\n model_time = train_loop(model, optimizer, imagenette_train_loader, loss_fn,\n DEVICE)\n times.append(model_time)\n\n top_1_acc, _ = eval_imagenette(model, imagenette_val_loader,\n len(imagenette_val))\n top_1_accuracies.append(top_1_acc.item())\n```\n\n\n```python\n# @title Plot accuracies vs. training speed\ndef get_parameter_count(model) -> int:\n return sum([torch.numel(p) for p in model.parameters()])\n\ndef plot_acc_speed(times, accs, models):\n ti = [t*1000 for t in times]\n for i, model in enumerate(list(models.keys())):\n scale = get_parameter_count(models[model])*1e-6\n plt.scatter(ti[i], accs[i], s=scale, label=model)\n plt.grid(True)\n plt.xlabel('speed [ms]')\n plt.ylabel('accuracy')\n plt.title('Accuracy vs. speed')\n plt.legend()\n\n\nplot_acc_speed(times, top_1_accuracies, models)\n```\n\n## Exercise 8.2\n\nLook at the plot above.\nIt shows the training speed vs. the accuracy of the models you chose.\nThe training speed is measured as the mean time the training takes per epoch.\nThe size of the marker visualizes the number of parameters of the model.\n\nWhich model seems to be the best for this task and why?\nExplain your conclusion based on speed, accuracy and number of parameters.\n\n\n```python\n# to_remove explanation\n\n\"\"\"\nGiven the 3 suggested models, the ResNet is the best model because it has the highest accuracy by being\nalmost as fast as AlexNet and having less parameters.\n\"\"\"\n```\n\n## Exercise 8.3\n\nHow does the speed correlate with the accuracy? Are faster models also more accurate?\n\n\n```python\n# to_remove explanation\n\n\"\"\"\nAlso depends on the models they chose.\nFor example, if we compare VGG with ResNet the ResNet is both faster and more accurate.\nAlexNet is a bit faster than ResNet but not as accurate.\n\"\"\"\n```\n\n---\n# Summary\n\nIn this tutorial you have learned about the modern Convnets (CNNs), their architecture, and their operating principles. Also, you are now familiar with the notion of *Transfer Learning*, and you have learned when to apply it. Finally, you have understood that speed vs. accuracy trade-off. In the next tutorial, we will see the modern convnets in a facial recognition task.\n\n", "meta": {"hexsha": "9fcf4744e7ac6cec2e4eb3802082f5d98f8bc0d1", "size": 680515, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tutorials/W2D2_ModernConvnets/W2D2_Tutorial1.ipynb", "max_stars_repo_name": "carsen-stringer/course-content-dl", "max_stars_repo_head_hexsha": "27749aec56a3d2a43b3890483675ad0338a2680f", "max_stars_repo_licenses": ["CC-BY-4.0", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tutorials/W2D2_ModernConvnets/W2D2_Tutorial1.ipynb", "max_issues_repo_name": "carsen-stringer/course-content-dl", "max_issues_repo_head_hexsha": "27749aec56a3d2a43b3890483675ad0338a2680f", "max_issues_repo_licenses": ["CC-BY-4.0", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorials/W2D2_ModernConvnets/W2D2_Tutorial1.ipynb", "max_forks_repo_name": "carsen-stringer/course-content-dl", "max_forks_repo_head_hexsha": "27749aec56a3d2a43b3890483675ad0338a2680f", "max_forks_repo_licenses": ["CC-BY-4.0", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 183.4272237197, "max_line_length": 284799, "alphanum_fraction": 0.8890384488, "converted": true, "num_tokens": 26061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.20073861107170488}}