{"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
Rewards
\n0
\nPulls
\n0
\nReward/Pull Ratio
\n0
\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 | 0 | \n
|---|---|
| count | \n100.000000 | \n
| mean | \n0.470000 | \n
| std | \n0.501614 | \n
| min | \n0.000000 | \n
| 25% | \n0.000000 | \n
| 50% | \n0.000000 | \n
| 75% | \n1.000000 | \n
| max | \n1.000000 | \n
효율성을 위해 ``Pipe`` 에 전달된 ``nn.Sequential`` 이\n 오직 두 개의 요소(2개의 GPU)로만 구성되도록 합니다. 이렇게 하면\n Pipe가 두 개의 파티션에서만 작동하고\n 파티션 간 오버헤드를 피할 수 있습니다.
Universidad de Antioquia
Angelower Santana Velasquez
Martin Elias Quintero Osorio
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\nLa 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\nUna 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\nimagen 1
The starry night in Medellín
Imagen contenido: Fotografia del centro de Medellín
Imagen estilo: The Starry Night - Vincent van Gogh
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
imagen 3
How convolutional neural networks see the world
Fuente: Blog
imagen 4
How convolutional neural networks see the world
Fuente: Blog de Keras por Francois Chollet
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| \n | 0 | \n
|---|---|
| count | \n100.000000 | \n
| mean | \n0.470000 | \n
| std | \n0.501614 | \n
| min | \n0.000000 | \n
| 25% | \n0.000000 | \n
| 50% | \n0.000000 | \n
| 75% | \n1.000000 | \n
| max | \n1.000000 | \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* |